xref: /freebsd/contrib/llvm-project/lld/ELF/Driver.cpp (revision 62987288060ff68c817b7056815aa9fb8ba8ecd7)
10b57cec5SDimitry Andric //===- Driver.cpp ---------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // The driver drives the entire linking process. It is responsible for
100b57cec5SDimitry Andric // parsing command line options and doing whatever it is instructed to do.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // One notable thing in the LLD's driver when compared to other linkers is
130b57cec5SDimitry Andric // that the LLD's driver is agnostic on the host operating system.
140b57cec5SDimitry Andric // Other linkers usually have implicit default values (such as a dynamic
150b57cec5SDimitry Andric // linker path or library paths) for each host OS.
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric // I don't think implicit default values are useful because they are
18bdd1243dSDimitry Andric // usually explicitly specified by the compiler ctx.driver. They can even
190b57cec5SDimitry Andric // be harmful when you are doing cross-linking. Therefore, in LLD, we
200b57cec5SDimitry Andric // simply trust the compiler driver to pass all required options and
210b57cec5SDimitry Andric // don't try to make effort on our side.
220b57cec5SDimitry Andric //
230b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric #include "Driver.h"
260b57cec5SDimitry Andric #include "Config.h"
270b57cec5SDimitry Andric #include "ICF.h"
280b57cec5SDimitry Andric #include "InputFiles.h"
290b57cec5SDimitry Andric #include "InputSection.h"
30bdd1243dSDimitry Andric #include "LTO.h"
310b57cec5SDimitry Andric #include "LinkerScript.h"
320b57cec5SDimitry Andric #include "MarkLive.h"
330b57cec5SDimitry Andric #include "OutputSections.h"
340b57cec5SDimitry Andric #include "ScriptParser.h"
350b57cec5SDimitry Andric #include "SymbolTable.h"
360b57cec5SDimitry Andric #include "Symbols.h"
370b57cec5SDimitry Andric #include "SyntheticSections.h"
380b57cec5SDimitry Andric #include "Target.h"
390b57cec5SDimitry Andric #include "Writer.h"
400b57cec5SDimitry Andric #include "lld/Common/Args.h"
41bdd1243dSDimitry Andric #include "lld/Common/CommonLinkerContext.h"
420b57cec5SDimitry Andric #include "lld/Common/Driver.h"
430b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
440b57cec5SDimitry Andric #include "lld/Common/Filesystem.h"
450b57cec5SDimitry Andric #include "lld/Common/Memory.h"
460b57cec5SDimitry Andric #include "lld/Common/Strings.h"
470b57cec5SDimitry Andric #include "lld/Common/TargetOptionsCommandFlags.h"
480b57cec5SDimitry Andric #include "lld/Common/Version.h"
490fca6ea1SDimitry Andric #include "llvm/ADT/STLExtras.h"
500b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
510b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
520b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
53e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
5485868e8aSDimitry Andric #include "llvm/LTO/LTO.h"
5581ad6265SDimitry Andric #include "llvm/Object/Archive.h"
565f757f3fSDimitry Andric #include "llvm/Object/IRObjectFile.h"
57e8d8bef9SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h"
580b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
590b57cec5SDimitry Andric #include "llvm/Support/Compression.h"
6081ad6265SDimitry Andric #include "llvm/Support/FileSystem.h"
610b57cec5SDimitry Andric #include "llvm/Support/GlobPattern.h"
620b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
635ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h"
640b57cec5SDimitry Andric #include "llvm/Support/Path.h"
650b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h"
660b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
675ffd83dbSDimitry Andric #include "llvm/Support/TimeProfiler.h"
680b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
690b57cec5SDimitry Andric #include <cstdlib>
7006c3fb27SDimitry Andric #include <tuple>
710b57cec5SDimitry Andric #include <utility>
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric using namespace llvm;
740b57cec5SDimitry Andric using namespace llvm::ELF;
750b57cec5SDimitry Andric using namespace llvm::object;
760b57cec5SDimitry Andric using namespace llvm::sys;
770b57cec5SDimitry Andric using namespace llvm::support;
785ffd83dbSDimitry Andric using namespace lld;
795ffd83dbSDimitry Andric using namespace lld::elf;
800b57cec5SDimitry Andric 
81bdd1243dSDimitry Andric ConfigWrapper elf::config;
82bdd1243dSDimitry Andric Ctx elf::ctx;
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args);
850b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args);
860b57cec5SDimitry Andric 
errorOrWarn(const Twine & msg)871fd87a68SDimitry Andric void elf::errorOrWarn(const Twine &msg) {
881fd87a68SDimitry Andric   if (config->noinhibitExec)
891fd87a68SDimitry Andric     warn(msg);
901fd87a68SDimitry Andric   else
911fd87a68SDimitry Andric     error(msg);
921fd87a68SDimitry Andric }
931fd87a68SDimitry Andric 
reset()94bdd1243dSDimitry Andric void Ctx::reset() {
95bdd1243dSDimitry Andric   driver = LinkerDriver();
96bdd1243dSDimitry Andric   memoryBuffers.clear();
97bdd1243dSDimitry Andric   objectFiles.clear();
98bdd1243dSDimitry Andric   sharedFiles.clear();
99bdd1243dSDimitry Andric   binaryFiles.clear();
100bdd1243dSDimitry Andric   bitcodeFiles.clear();
101bdd1243dSDimitry Andric   lazyBitcodeFiles.clear();
102bdd1243dSDimitry Andric   inputSections.clear();
103bdd1243dSDimitry Andric   ehInputSections.clear();
104bdd1243dSDimitry Andric   duplicates.clear();
105bdd1243dSDimitry Andric   nonPrevailingSyms.clear();
106bdd1243dSDimitry Andric   whyExtractRecords.clear();
107bdd1243dSDimitry Andric   backwardReferences.clear();
1085f757f3fSDimitry Andric   auxiliaryFiles.clear();
1097a6dacacSDimitry Andric   internalFile = nullptr;
110bdd1243dSDimitry Andric   hasSympart.store(false, std::memory_order_relaxed);
1115f757f3fSDimitry Andric   hasTlsIe.store(false, std::memory_order_relaxed);
112bdd1243dSDimitry Andric   needsTlsLd.store(false, std::memory_order_relaxed);
1135f757f3fSDimitry Andric   scriptSymOrderCounter = 1;
1145f757f3fSDimitry Andric   scriptSymOrder.clear();
1155f757f3fSDimitry Andric   ltoAllVtablesHaveTypeInfos = false;
116bdd1243dSDimitry Andric }
117bdd1243dSDimitry Andric 
openAuxiliaryFile(llvm::StringRef filename,std::error_code & ec)11806c3fb27SDimitry Andric llvm::raw_fd_ostream Ctx::openAuxiliaryFile(llvm::StringRef filename,
11906c3fb27SDimitry Andric                                             std::error_code &ec) {
12006c3fb27SDimitry Andric   using namespace llvm::sys::fs;
12106c3fb27SDimitry Andric   OpenFlags flags =
12206c3fb27SDimitry Andric       auxiliaryFiles.insert(filename).second ? OF_None : OF_Append;
12306c3fb27SDimitry Andric   return {filename, ec, flags};
12406c3fb27SDimitry Andric }
12506c3fb27SDimitry Andric 
12606c3fb27SDimitry Andric namespace lld {
12706c3fb27SDimitry Andric namespace elf {
link(ArrayRef<const char * > args,llvm::raw_ostream & stdoutOS,llvm::raw_ostream & stderrOS,bool exitEarly,bool disableOutput)12806c3fb27SDimitry Andric bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
12906c3fb27SDimitry Andric           llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
13006c3fb27SDimitry Andric   // This driver-specific context will be freed later by unsafeLldMain().
13104eeddc0SDimitry Andric   auto *ctx = new CommonLinkerContext;
132480093f4SDimitry Andric 
13304eeddc0SDimitry Andric   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
13404eeddc0SDimitry Andric   ctx->e.cleanupCallback = []() {
135bdd1243dSDimitry Andric     elf::ctx.reset();
136bdd1243dSDimitry Andric     symtab = SymbolTable();
137bdd1243dSDimitry Andric 
1380b57cec5SDimitry Andric     outputSections.clear();
13904eeddc0SDimitry Andric     symAux.clear();
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric     tar = nullptr;
14204eeddc0SDimitry Andric     in.reset();
1430b57cec5SDimitry Andric 
14404eeddc0SDimitry Andric     partitions.clear();
14504eeddc0SDimitry Andric     partitions.emplace_back();
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric     SharedFile::vernauxNum = 0;
148e8d8bef9SDimitry Andric   };
14904eeddc0SDimitry Andric   ctx->e.logName = args::getFilenameWithoutExe(args[0]);
15004eeddc0SDimitry Andric   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use "
15181ad6265SDimitry Andric                                  "--error-limit=0 to see all errors)";
152e8d8bef9SDimitry Andric 
153bdd1243dSDimitry Andric   config = ConfigWrapper();
1540fca6ea1SDimitry Andric   script = ScriptWrapper();
155bdd1243dSDimitry Andric 
156bdd1243dSDimitry Andric   symAux.emplace_back();
157e8d8bef9SDimitry Andric 
15804eeddc0SDimitry Andric   partitions.clear();
15904eeddc0SDimitry Andric   partitions.emplace_back();
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   config->progName = args[0];
1620b57cec5SDimitry Andric 
163bdd1243dSDimitry Andric   elf::ctx.driver.linkerMain(args);
1640b57cec5SDimitry Andric 
16504eeddc0SDimitry Andric   return errorCount() == 0;
1660b57cec5SDimitry Andric }
16706c3fb27SDimitry Andric } // namespace elf
16806c3fb27SDimitry Andric } // namespace lld
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric // Parses a linker -m option.
parseEmulation(StringRef emul)1710b57cec5SDimitry Andric static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
1720b57cec5SDimitry Andric   uint8_t osabi = 0;
1730b57cec5SDimitry Andric   StringRef s = emul;
17406c3fb27SDimitry Andric   if (s.ends_with("_fbsd")) {
1750b57cec5SDimitry Andric     s = s.drop_back(5);
1760b57cec5SDimitry Andric     osabi = ELFOSABI_FREEBSD;
1770b57cec5SDimitry Andric   }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   std::pair<ELFKind, uint16_t> ret =
1800b57cec5SDimitry Andric       StringSwitch<std::pair<ELFKind, uint16_t>>(s)
181fe6060f1SDimitry Andric           .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
182fe6060f1SDimitry Andric           .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})
1830b57cec5SDimitry Andric           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
18406c3fb27SDimitry Andric           .Cases("armelfb", "armelfb_linux_eabi", {ELF32BEKind, EM_ARM})
1850b57cec5SDimitry Andric           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
1860b57cec5SDimitry Andric           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
1870b57cec5SDimitry Andric           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
1880b57cec5SDimitry Andric           .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
1890b57cec5SDimitry Andric           .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
190e8d8bef9SDimitry Andric           .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})
19106c3fb27SDimitry Andric           .Case("elf32loongarch", {ELF32LEKind, EM_LOONGARCH})
1920b57cec5SDimitry Andric           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
1930b57cec5SDimitry Andric           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
1940b57cec5SDimitry Andric           .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
1950b57cec5SDimitry Andric           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
1960b57cec5SDimitry Andric           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
1970b57cec5SDimitry Andric           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
1980b57cec5SDimitry Andric           .Case("elf_i386", {ELF32LEKind, EM_386})
1990b57cec5SDimitry Andric           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
2005ffd83dbSDimitry Andric           .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
201e8d8bef9SDimitry Andric           .Case("msp430elf", {ELF32LEKind, EM_MSP430})
202bdd1243dSDimitry Andric           .Case("elf64_amdgpu", {ELF64LEKind, EM_AMDGPU})
20306c3fb27SDimitry Andric           .Case("elf64loongarch", {ELF64LEKind, EM_LOONGARCH})
20474626c16SDimitry Andric           .Case("elf64_s390", {ELF64BEKind, EM_S390})
2050fca6ea1SDimitry Andric           .Case("hexagonelf", {ELF32LEKind, EM_HEXAGON})
2060b57cec5SDimitry Andric           .Default({ELFNoneKind, EM_NONE});
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   if (ret.first == ELFNoneKind)
2090b57cec5SDimitry Andric     error("unknown emulation: " + emul);
210e8d8bef9SDimitry Andric   if (ret.second == EM_MSP430)
211e8d8bef9SDimitry Andric     osabi = ELFOSABI_STANDALONE;
212bdd1243dSDimitry Andric   else if (ret.second == EM_AMDGPU)
213bdd1243dSDimitry Andric     osabi = ELFOSABI_AMDGPU_HSA;
2140b57cec5SDimitry Andric   return std::make_tuple(ret.first, ret.second, osabi);
2150b57cec5SDimitry Andric }
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric // Returns slices of MB by parsing MB as an archive file.
2180b57cec5SDimitry Andric // Each slice consists of a member file in the archive.
getArchiveMembers(MemoryBufferRef mb)2190b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
2200b57cec5SDimitry Andric     MemoryBufferRef mb) {
2210b57cec5SDimitry Andric   std::unique_ptr<Archive> file =
2220b57cec5SDimitry Andric       CHECK(Archive::create(mb),
2230b57cec5SDimitry Andric             mb.getBufferIdentifier() + ": failed to parse archive");
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
2260b57cec5SDimitry Andric   Error err = Error::success();
2270b57cec5SDimitry Andric   bool addToTar = file->isThin() && tar;
228480093f4SDimitry Andric   for (const Archive::Child &c : file->children(err)) {
2290b57cec5SDimitry Andric     MemoryBufferRef mbref =
2300b57cec5SDimitry Andric         CHECK(c.getMemoryBufferRef(),
2310b57cec5SDimitry Andric               mb.getBufferIdentifier() +
2320b57cec5SDimitry Andric                   ": could not get the buffer for a child of the archive");
2330b57cec5SDimitry Andric     if (addToTar)
2340b57cec5SDimitry Andric       tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
2350b57cec5SDimitry Andric     v.push_back(std::make_pair(mbref, c.getChildOffset()));
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric   if (err)
2380b57cec5SDimitry Andric     fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
2390b57cec5SDimitry Andric           toString(std::move(err)));
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   // Take ownership of memory buffers created for members of thin archives.
2421fd87a68SDimitry Andric   std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers();
243bdd1243dSDimitry Andric   std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers));
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   return v;
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric 
isBitcode(MemoryBufferRef mb)248fcaf7f86SDimitry Andric static bool isBitcode(MemoryBufferRef mb) {
249fcaf7f86SDimitry Andric   return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode;
250fcaf7f86SDimitry Andric }
251fcaf7f86SDimitry Andric 
tryAddFatLTOFile(MemoryBufferRef mb,StringRef archiveName,uint64_t offsetInArchive,bool lazy)2525f757f3fSDimitry Andric bool LinkerDriver::tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName,
2535f757f3fSDimitry Andric                                     uint64_t offsetInArchive, bool lazy) {
2545f757f3fSDimitry Andric   if (!config->fatLTOObjects)
2555f757f3fSDimitry Andric     return false;
2565f757f3fSDimitry Andric   Expected<MemoryBufferRef> fatLTOData =
2575f757f3fSDimitry Andric       IRObjectFile::findBitcodeInMemBuffer(mb);
2585f757f3fSDimitry Andric   if (errorToBool(fatLTOData.takeError()))
2595f757f3fSDimitry Andric     return false;
2605f757f3fSDimitry Andric   files.push_back(
2615f757f3fSDimitry Andric       make<BitcodeFile>(*fatLTOData, archiveName, offsetInArchive, lazy));
2625f757f3fSDimitry Andric   return true;
2635f757f3fSDimitry Andric }
2645f757f3fSDimitry Andric 
2650b57cec5SDimitry Andric // Opens a file and create a file object. Path has to be resolved already.
addFile(StringRef path,bool withLOption)2660b57cec5SDimitry Andric void LinkerDriver::addFile(StringRef path, bool withLOption) {
2670b57cec5SDimitry Andric   using namespace sys::fs;
2680b57cec5SDimitry Andric 
269bdd1243dSDimitry Andric   std::optional<MemoryBufferRef> buffer = readFile(path);
27081ad6265SDimitry Andric   if (!buffer)
2710b57cec5SDimitry Andric     return;
2720b57cec5SDimitry Andric   MemoryBufferRef mbref = *buffer;
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric   if (config->formatBinary) {
2750b57cec5SDimitry Andric     files.push_back(make<BinaryFile>(mbref));
2760b57cec5SDimitry Andric     return;
2770b57cec5SDimitry Andric   }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   switch (identify_magic(mbref.getBuffer())) {
2800b57cec5SDimitry Andric   case file_magic::unknown:
2810b57cec5SDimitry Andric     readLinkerScript(mbref);
2820b57cec5SDimitry Andric     return;
2830b57cec5SDimitry Andric   case file_magic::archive: {
284bdd1243dSDimitry Andric     auto members = getArchiveMembers(mbref);
2850b57cec5SDimitry Andric     if (inWholeArchive) {
286bdd1243dSDimitry Andric       for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {
287fcaf7f86SDimitry Andric         if (isBitcode(p.first))
288fcaf7f86SDimitry Andric           files.push_back(make<BitcodeFile>(p.first, path, p.second, false));
2895f757f3fSDimitry Andric         else if (!tryAddFatLTOFile(p.first, path, p.second, false))
290fcaf7f86SDimitry Andric           files.push_back(createObjFile(p.first, path));
291fcaf7f86SDimitry Andric       }
2920b57cec5SDimitry Andric       return;
2930b57cec5SDimitry Andric     }
2940b57cec5SDimitry Andric 
29581ad6265SDimitry Andric     archiveFiles.emplace_back(path, members.size());
2960b57cec5SDimitry Andric 
29781ad6265SDimitry Andric     // Handle archives and --start-lib/--end-lib using the same code path. This
29881ad6265SDimitry Andric     // scans all the ELF relocatable object files and bitcode files in the
29981ad6265SDimitry Andric     // archive rather than just the index file, with the benefit that the
30081ad6265SDimitry Andric     // symbols are only loaded once. For many projects archives see high
30181ad6265SDimitry Andric     // utilization rates and it is a net performance win. --start-lib scans
30281ad6265SDimitry Andric     // symbols in the same order that llvm-ar adds them to the index, so in the
30381ad6265SDimitry Andric     // common case the semantics are identical. If the archive symbol table was
30481ad6265SDimitry Andric     // created in a different order, or is incomplete, this strategy has
30581ad6265SDimitry Andric     // different semantics. Such output differences are considered user error.
30681ad6265SDimitry Andric     //
307d56accc7SDimitry Andric     // All files within the archive get the same group ID to allow mutual
308d56accc7SDimitry Andric     // references for --warn-backrefs.
309d56accc7SDimitry Andric     bool saved = InputFile::isInGroup;
310d56accc7SDimitry Andric     InputFile::isInGroup = true;
31181ad6265SDimitry Andric     for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {
31204eeddc0SDimitry Andric       auto magic = identify_magic(p.first.getBuffer());
3135f757f3fSDimitry Andric       if (magic == file_magic::elf_relocatable) {
3145f757f3fSDimitry Andric         if (!tryAddFatLTOFile(p.first, path, p.second, true))
315fcaf7f86SDimitry Andric           files.push_back(createObjFile(p.first, path, true));
3165f757f3fSDimitry Andric       } else if (magic == file_magic::bitcode)
317fcaf7f86SDimitry Andric         files.push_back(make<BitcodeFile>(p.first, path, p.second, true));
31804eeddc0SDimitry Andric       else
31981ad6265SDimitry Andric         warn(path + ": archive member '" + p.first.getBufferIdentifier() +
32004eeddc0SDimitry Andric              "' is neither ET_REL nor LLVM bitcode");
32104eeddc0SDimitry Andric     }
322d56accc7SDimitry Andric     InputFile::isInGroup = saved;
323d56accc7SDimitry Andric     if (!saved)
324d56accc7SDimitry Andric       ++InputFile::nextGroupId;
3250b57cec5SDimitry Andric     return;
3260b57cec5SDimitry Andric   }
327bdd1243dSDimitry Andric   case file_magic::elf_shared_object: {
3280fca6ea1SDimitry Andric     if (config->isStatic) {
3290b57cec5SDimitry Andric       error("attempted static link of dynamic object " + path);
3300b57cec5SDimitry Andric       return;
3310b57cec5SDimitry Andric     }
3320b57cec5SDimitry Andric 
333349cc55cSDimitry Andric     // Shared objects are identified by soname. soname is (if specified)
334349cc55cSDimitry Andric     // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
335349cc55cSDimitry Andric     // the directory part is ignored. Note that path may be a temporary and
336349cc55cSDimitry Andric     // cannot be stored into SharedFile::soName.
337349cc55cSDimitry Andric     path = mbref.getBufferIdentifier();
338bdd1243dSDimitry Andric     auto *f =
339bdd1243dSDimitry Andric         make<SharedFile>(mbref, withLOption ? path::filename(path) : path);
340bdd1243dSDimitry Andric     f->init();
341bdd1243dSDimitry Andric     files.push_back(f);
3420b57cec5SDimitry Andric     return;
343bdd1243dSDimitry Andric   }
3440b57cec5SDimitry Andric   case file_magic::bitcode:
345fcaf7f86SDimitry Andric     files.push_back(make<BitcodeFile>(mbref, "", 0, inLib));
346fcaf7f86SDimitry Andric     break;
3470b57cec5SDimitry Andric   case file_magic::elf_relocatable:
3485f757f3fSDimitry Andric     if (!tryAddFatLTOFile(mbref, "", 0, inLib))
349fcaf7f86SDimitry Andric       files.push_back(createObjFile(mbref, "", inLib));
3500b57cec5SDimitry Andric     break;
3510b57cec5SDimitry Andric   default:
3520b57cec5SDimitry Andric     error(path + ": unknown file type");
3530b57cec5SDimitry Andric   }
3540b57cec5SDimitry Andric }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric // Add a given library by searching it from input search paths.
addLibrary(StringRef name)3570b57cec5SDimitry Andric void LinkerDriver::addLibrary(StringRef name) {
358bdd1243dSDimitry Andric   if (std::optional<std::string> path = searchLibrary(name))
359972a253aSDimitry Andric     addFile(saver().save(*path), /*withLOption=*/true);
3600b57cec5SDimitry Andric   else
361e8d8bef9SDimitry Andric     error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
3620b57cec5SDimitry Andric }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric // This function is called on startup. We need this for LTO since
3650b57cec5SDimitry Andric // LTO calls LLVM functions to compile bitcode files to native code.
3660b57cec5SDimitry Andric // Technically this can be delayed until we read bitcode files, but
3670b57cec5SDimitry Andric // we don't bother to do lazily because the initialization is fast.
initLLVM()3680b57cec5SDimitry Andric static void initLLVM() {
3690b57cec5SDimitry Andric   InitializeAllTargets();
3700b57cec5SDimitry Andric   InitializeAllTargetMCs();
3710b57cec5SDimitry Andric   InitializeAllAsmPrinters();
3720b57cec5SDimitry Andric   InitializeAllAsmParsers();
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric // Some command line options or some combinations of them are not allowed.
3760b57cec5SDimitry Andric // This function checks for such errors.
checkOptions()3770b57cec5SDimitry Andric static void checkOptions() {
3780b57cec5SDimitry Andric   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
3790b57cec5SDimitry Andric   // table which is a relatively new feature.
3800b57cec5SDimitry Andric   if (config->emachine == EM_MIPS && config->gnuHash)
3810b57cec5SDimitry Andric     error("the .gnu.hash section is not compatible with the MIPS target");
3820b57cec5SDimitry Andric 
38306c3fb27SDimitry Andric   if (config->emachine == EM_ARM) {
38406c3fb27SDimitry Andric     if (!config->cmseImplib) {
38506c3fb27SDimitry Andric       if (!config->cmseInputLib.empty())
38606c3fb27SDimitry Andric         error("--in-implib may not be used without --cmse-implib");
38706c3fb27SDimitry Andric       if (!config->cmseOutputLib.empty())
38806c3fb27SDimitry Andric         error("--out-implib may not be used without --cmse-implib");
38906c3fb27SDimitry Andric     }
39006c3fb27SDimitry Andric   } else {
39106c3fb27SDimitry Andric     if (config->cmseImplib)
39206c3fb27SDimitry Andric       error("--cmse-implib is only supported on ARM targets");
39306c3fb27SDimitry Andric     if (!config->cmseInputLib.empty())
39406c3fb27SDimitry Andric       error("--in-implib is only supported on ARM targets");
39506c3fb27SDimitry Andric     if (!config->cmseOutputLib.empty())
39606c3fb27SDimitry Andric       error("--out-implib is only supported on ARM targets");
39706c3fb27SDimitry Andric   }
39806c3fb27SDimitry Andric 
3990b57cec5SDimitry Andric   if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
4000b57cec5SDimitry Andric     error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
4010b57cec5SDimitry Andric 
40285868e8aSDimitry Andric   if (config->fixCortexA8 && config->emachine != EM_ARM)
40385868e8aSDimitry Andric     error("--fix-cortex-a8 is only supported on ARM targets");
40485868e8aSDimitry Andric 
40506c3fb27SDimitry Andric   if (config->armBe8 && config->emachine != EM_ARM)
40606c3fb27SDimitry Andric     error("--be8 is only supported on ARM targets");
40706c3fb27SDimitry Andric 
40806c3fb27SDimitry Andric   if (config->fixCortexA8 && !config->isLE)
40906c3fb27SDimitry Andric     error("--fix-cortex-a8 is not supported on big endian targets");
41006c3fb27SDimitry Andric 
4110b57cec5SDimitry Andric   if (config->tocOptimize && config->emachine != EM_PPC64)
412e8d8bef9SDimitry Andric     error("--toc-optimize is only supported on PowerPC64 targets");
413e8d8bef9SDimitry Andric 
414e8d8bef9SDimitry Andric   if (config->pcRelOptimize && config->emachine != EM_PPC64)
415e8d8bef9SDimitry Andric     error("--pcrel-optimize is only supported on PowerPC64 targets");
4160b57cec5SDimitry Andric 
41706c3fb27SDimitry Andric   if (config->relaxGP && config->emachine != EM_RISCV)
41806c3fb27SDimitry Andric     error("--relax-gp is only supported on RISC-V targets");
41906c3fb27SDimitry Andric 
4200b57cec5SDimitry Andric   if (config->pie && config->shared)
4210b57cec5SDimitry Andric     error("-shared and -pie may not be used together");
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   if (!config->shared && !config->filterList.empty())
4240b57cec5SDimitry Andric     error("-F may not be used without -shared");
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   if (!config->shared && !config->auxiliaryList.empty())
4270b57cec5SDimitry Andric     error("-f may not be used without -shared");
4280b57cec5SDimitry Andric 
42985868e8aSDimitry Andric   if (config->strip == StripPolicy::All && config->emitRelocs)
43085868e8aSDimitry Andric     error("--strip-all and --emit-relocs may not be used together");
43185868e8aSDimitry Andric 
4320b57cec5SDimitry Andric   if (config->zText && config->zIfuncNoplt)
4330b57cec5SDimitry Andric     error("-z text and -z ifunc-noplt may not be used together");
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   if (config->relocatable) {
4360b57cec5SDimitry Andric     if (config->shared)
4370b57cec5SDimitry Andric       error("-r and -shared may not be used together");
4380b57cec5SDimitry Andric     if (config->gdbIndex)
4390b57cec5SDimitry Andric       error("-r and --gdb-index may not be used together");
4400b57cec5SDimitry Andric     if (config->icf != ICFLevel::None)
4410b57cec5SDimitry Andric       error("-r and --icf may not be used together");
4420b57cec5SDimitry Andric     if (config->pie)
4430b57cec5SDimitry Andric       error("-r and -pie may not be used together");
44485868e8aSDimitry Andric     if (config->exportDynamic)
44585868e8aSDimitry Andric       error("-r and --export-dynamic may not be used together");
4460fca6ea1SDimitry Andric     if (config->debugNames)
4470fca6ea1SDimitry Andric       error("-r and --debug-names may not be used together");
4480b57cec5SDimitry Andric   }
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   if (config->executeOnly) {
4510b57cec5SDimitry Andric     if (config->emachine != EM_AARCH64)
452349cc55cSDimitry Andric       error("--execute-only is only supported on AArch64 targets");
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric     if (config->singleRoRx && !script->hasSectionsCommand)
455349cc55cSDimitry Andric       error("--execute-only and --no-rosegment cannot be used together");
4560b57cec5SDimitry Andric   }
4570b57cec5SDimitry Andric 
458480093f4SDimitry Andric   if (config->zRetpolineplt && config->zForceIbt)
459480093f4SDimitry Andric     error("-z force-ibt may not be used with -z retpolineplt");
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric   if (config->emachine != EM_AARCH64) {
4625ffd83dbSDimitry Andric     if (config->zPacPlt)
463480093f4SDimitry Andric       error("-z pac-plt only supported on AArch64");
4645ffd83dbSDimitry Andric     if (config->zForceBti)
465480093f4SDimitry Andric       error("-z force-bti only supported on AArch64");
4660eae32dcSDimitry Andric     if (config->zBtiReport != "none")
4670eae32dcSDimitry Andric       error("-z bti-report only supported on AArch64");
4680fca6ea1SDimitry Andric     if (config->zPauthReport != "none")
4690fca6ea1SDimitry Andric       error("-z pauth-report only supported on AArch64");
4700fca6ea1SDimitry Andric     if (config->zGcsReport != "none")
4710fca6ea1SDimitry Andric       error("-z gcs-report only supported on AArch64");
4720fca6ea1SDimitry Andric     if (config->zGcs != GcsPolicy::Implicit)
4730fca6ea1SDimitry Andric       error("-z gcs only supported on AArch64");
4740b57cec5SDimitry Andric   }
4750eae32dcSDimitry Andric 
4760eae32dcSDimitry Andric   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
4770eae32dcSDimitry Andric       config->zCetReport != "none")
4780eae32dcSDimitry Andric     error("-z cet-report only supported on X86 and X86_64");
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
getReproduceOption(opt::InputArgList & args)4810b57cec5SDimitry Andric static const char *getReproduceOption(opt::InputArgList &args) {
4820b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_reproduce))
4830b57cec5SDimitry Andric     return arg->getValue();
4840b57cec5SDimitry Andric   return getenv("LLD_REPRODUCE");
4850b57cec5SDimitry Andric }
4860b57cec5SDimitry Andric 
hasZOption(opt::InputArgList & args,StringRef key)4870b57cec5SDimitry Andric static bool hasZOption(opt::InputArgList &args, StringRef key) {
4887a6dacacSDimitry Andric   bool ret = false;
4890b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_z))
4907a6dacacSDimitry Andric     if (key == arg->getValue()) {
4917a6dacacSDimitry Andric       ret = true;
4927a6dacacSDimitry Andric       arg->claim();
4937a6dacacSDimitry Andric     }
4947a6dacacSDimitry Andric   return ret;
4950b57cec5SDimitry Andric }
4960b57cec5SDimitry Andric 
getZFlag(opt::InputArgList & args,StringRef k1,StringRef k2,bool defaultValue)4970b57cec5SDimitry Andric static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
4987a6dacacSDimitry Andric                      bool defaultValue) {
4997a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
5007a6dacacSDimitry Andric     StringRef v = arg->getValue();
5017a6dacacSDimitry Andric     if (k1 == v)
5027a6dacacSDimitry Andric       defaultValue = true;
5037a6dacacSDimitry Andric     else if (k2 == v)
5047a6dacacSDimitry Andric       defaultValue = false;
5057a6dacacSDimitry Andric     else
5067a6dacacSDimitry Andric       continue;
5077a6dacacSDimitry Andric     arg->claim();
5080b57cec5SDimitry Andric   }
5097a6dacacSDimitry Andric   return defaultValue;
5100b57cec5SDimitry Andric }
5110b57cec5SDimitry Andric 
getZSeparate(opt::InputArgList & args)51285868e8aSDimitry Andric static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
5137a6dacacSDimitry Andric   auto ret = SeparateSegmentKind::None;
5147a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
51585868e8aSDimitry Andric     StringRef v = arg->getValue();
51685868e8aSDimitry Andric     if (v == "noseparate-code")
5177a6dacacSDimitry Andric       ret = SeparateSegmentKind::None;
5187a6dacacSDimitry Andric     else if (v == "separate-code")
5197a6dacacSDimitry Andric       ret = SeparateSegmentKind::Code;
5207a6dacacSDimitry Andric     else if (v == "separate-loadable-segments")
5217a6dacacSDimitry Andric       ret = SeparateSegmentKind::Loadable;
5227a6dacacSDimitry Andric     else
5237a6dacacSDimitry Andric       continue;
5247a6dacacSDimitry Andric     arg->claim();
52585868e8aSDimitry Andric   }
5267a6dacacSDimitry Andric   return ret;
52785868e8aSDimitry Andric }
52885868e8aSDimitry Andric 
getZGnuStack(opt::InputArgList & args)529480093f4SDimitry Andric static GnuStackKind getZGnuStack(opt::InputArgList &args) {
5307a6dacacSDimitry Andric   auto ret = GnuStackKind::NoExec;
5317a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
5327a6dacacSDimitry Andric     StringRef v = arg->getValue();
5337a6dacacSDimitry Andric     if (v == "execstack")
5347a6dacacSDimitry Andric       ret = GnuStackKind::Exec;
5357a6dacacSDimitry Andric     else if (v == "noexecstack")
5367a6dacacSDimitry Andric       ret = GnuStackKind::NoExec;
5377a6dacacSDimitry Andric     else if (v == "nognustack")
5387a6dacacSDimitry Andric       ret = GnuStackKind::None;
5397a6dacacSDimitry Andric     else
5407a6dacacSDimitry Andric       continue;
5417a6dacacSDimitry Andric     arg->claim();
542480093f4SDimitry Andric   }
5437a6dacacSDimitry Andric   return ret;
544480093f4SDimitry Andric }
545480093f4SDimitry Andric 
getZStartStopVisibility(opt::InputArgList & args)5465ffd83dbSDimitry Andric static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
5477a6dacacSDimitry Andric   uint8_t ret = STV_PROTECTED;
5487a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
5495ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
5505ffd83dbSDimitry Andric     if (kv.first == "start-stop-visibility") {
5517a6dacacSDimitry Andric       arg->claim();
5525ffd83dbSDimitry Andric       if (kv.second == "default")
5537a6dacacSDimitry Andric         ret = STV_DEFAULT;
5545ffd83dbSDimitry Andric       else if (kv.second == "internal")
5557a6dacacSDimitry Andric         ret = STV_INTERNAL;
5565ffd83dbSDimitry Andric       else if (kv.second == "hidden")
5577a6dacacSDimitry Andric         ret = STV_HIDDEN;
5585ffd83dbSDimitry Andric       else if (kv.second == "protected")
5597a6dacacSDimitry Andric         ret = STV_PROTECTED;
5607a6dacacSDimitry Andric       else
5617a6dacacSDimitry Andric         error("unknown -z start-stop-visibility= value: " +
5627a6dacacSDimitry Andric               StringRef(kv.second));
5635ffd83dbSDimitry Andric     }
5645ffd83dbSDimitry Andric   }
5657a6dacacSDimitry Andric   return ret;
5660b57cec5SDimitry Andric }
5670b57cec5SDimitry Andric 
getZGcs(opt::InputArgList & args)5680fca6ea1SDimitry Andric static GcsPolicy getZGcs(opt::InputArgList &args) {
5690fca6ea1SDimitry Andric   GcsPolicy ret = GcsPolicy::Implicit;
5700fca6ea1SDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
5710fca6ea1SDimitry Andric     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
5720fca6ea1SDimitry Andric     if (kv.first == "gcs") {
5730fca6ea1SDimitry Andric       arg->claim();
5740fca6ea1SDimitry Andric       if (kv.second == "implicit")
5750fca6ea1SDimitry Andric         ret = GcsPolicy::Implicit;
5760fca6ea1SDimitry Andric       else if (kv.second == "never")
5770fca6ea1SDimitry Andric         ret = GcsPolicy::Never;
5780fca6ea1SDimitry Andric       else if (kv.second == "always")
5790fca6ea1SDimitry Andric         ret = GcsPolicy::Always;
5800fca6ea1SDimitry Andric       else
5810fca6ea1SDimitry Andric         error("unknown -z gcs= value: " + kv.second);
5820fca6ea1SDimitry Andric     }
5830fca6ea1SDimitry Andric   }
5840fca6ea1SDimitry Andric   return ret;
5850fca6ea1SDimitry Andric }
5860fca6ea1SDimitry Andric 
5874824e7fdSDimitry Andric // Report a warning for an unknown -z option.
checkZOptions(opt::InputArgList & args)5880b57cec5SDimitry Andric static void checkZOptions(opt::InputArgList &args) {
5897a6dacacSDimitry Andric   // This function is called before getTarget(), when certain options are not
5907a6dacacSDimitry Andric   // initialized yet. Claim them here.
5917a6dacacSDimitry Andric   args::getZOptionValue(args, OPT_z, "max-page-size", 0);
5927a6dacacSDimitry Andric   args::getZOptionValue(args, OPT_z, "common-page-size", 0);
5937a6dacacSDimitry Andric   getZFlag(args, "rel", "rela", false);
5940b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_z))
5957a6dacacSDimitry Andric     if (!arg->isClaimed())
5964824e7fdSDimitry Andric       warn("unknown -z value: " + StringRef(arg->getValue()));
5970b57cec5SDimitry Andric }
5980b57cec5SDimitry Andric 
599753f127fSDimitry Andric constexpr const char *saveTempsValues[] = {
600753f127fSDimitry Andric     "resolution", "preopt",     "promote", "internalize",  "import",
601753f127fSDimitry Andric     "opt",        "precodegen", "prelink", "combinedindex"};
602753f127fSDimitry Andric 
linkerMain(ArrayRef<const char * > argsArr)603e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
6040b57cec5SDimitry Andric   ELFOptTable parser;
6050b57cec5SDimitry Andric   opt::InputArgList args = parser.parse(argsArr.slice(1));
6060b57cec5SDimitry Andric 
60781ad6265SDimitry Andric   // Interpret these flags early because error()/warn() depend on them.
6080b57cec5SDimitry Andric   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
6094824e7fdSDimitry Andric   errorHandler().fatalWarnings =
610bdd1243dSDimitry Andric       args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) &&
611bdd1243dSDimitry Andric       !args.hasArg(OPT_no_warnings);
612bdd1243dSDimitry Andric   errorHandler().suppressWarnings = args.hasArg(OPT_no_warnings);
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   // Handle -help
6150b57cec5SDimitry Andric   if (args.hasArg(OPT_help)) {
6160b57cec5SDimitry Andric     printHelp();
6170b57cec5SDimitry Andric     return;
6180b57cec5SDimitry Andric   }
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   // Handle -v or -version.
6210b57cec5SDimitry Andric   //
6220b57cec5SDimitry Andric   // A note about "compatible with GNU linkers" message: this is a hack for
623349cc55cSDimitry Andric   // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
624349cc55cSDimitry Andric   // a GNU compatible linker. See
625349cc55cSDimitry Andric   // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
6260b57cec5SDimitry Andric   //
6270b57cec5SDimitry Andric   // This is somewhat ugly hack, but in reality, we had no choice other
6280b57cec5SDimitry Andric   // than doing this. Considering the very long release cycle of Libtool,
6290b57cec5SDimitry Andric   // it is not easy to improve it to recognize LLD as a GNU compatible
6300b57cec5SDimitry Andric   // linker in a timely manner. Even if we can make it, there are still a
6310b57cec5SDimitry Andric   // lot of "configure" scripts out there that are generated by old version
6320b57cec5SDimitry Andric   // of Libtool. We cannot convince every software developer to migrate to
6330b57cec5SDimitry Andric   // the latest version and re-generate scripts. So we have this hack.
6340b57cec5SDimitry Andric   if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
6350b57cec5SDimitry Andric     message(getLLDVersion() + " (compatible with GNU linkers)");
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   if (const char *path = getReproduceOption(args)) {
6380b57cec5SDimitry Andric     // Note that --reproduce is a debug option so you can ignore it
6390b57cec5SDimitry Andric     // if you are trying to understand the whole picture of the code.
6400b57cec5SDimitry Andric     Expected<std::unique_ptr<TarWriter>> errOrWriter =
6410b57cec5SDimitry Andric         TarWriter::create(path, path::stem(path));
6420b57cec5SDimitry Andric     if (errOrWriter) {
6430b57cec5SDimitry Andric       tar = std::move(*errOrWriter);
6440b57cec5SDimitry Andric       tar->append("response.txt", createResponseFile(args));
6450b57cec5SDimitry Andric       tar->append("version.txt", getLLDVersion() + "\n");
646e8d8bef9SDimitry Andric       StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
647e8d8bef9SDimitry Andric       if (!ltoSampleProfile.empty())
648e8d8bef9SDimitry Andric         readFile(ltoSampleProfile);
6490b57cec5SDimitry Andric     } else {
6500b57cec5SDimitry Andric       error("--reproduce: " + toString(errOrWriter.takeError()));
6510b57cec5SDimitry Andric     }
6520b57cec5SDimitry Andric   }
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   readConfigs(args);
6557a6dacacSDimitry Andric   checkZOptions(args);
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric   // The behavior of -v or --version is a bit strange, but this is
6580b57cec5SDimitry Andric   // needed for compatibility with GNU linkers.
6590b57cec5SDimitry Andric   if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
6600b57cec5SDimitry Andric     return;
6610b57cec5SDimitry Andric   if (args.hasArg(OPT_version))
6620b57cec5SDimitry Andric     return;
6630b57cec5SDimitry Andric 
6645ffd83dbSDimitry Andric   // Initialize time trace profiler.
6655ffd83dbSDimitry Andric   if (config->timeTraceEnabled)
6665ffd83dbSDimitry Andric     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
6675ffd83dbSDimitry Andric 
6685ffd83dbSDimitry Andric   {
6695ffd83dbSDimitry Andric     llvm::TimeTraceScope timeScope("ExecuteLinker");
6705ffd83dbSDimitry Andric 
6710b57cec5SDimitry Andric     initLLVM();
6720b57cec5SDimitry Andric     createFiles(args);
6730b57cec5SDimitry Andric     if (errorCount())
6740b57cec5SDimitry Andric       return;
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric     inferMachineType();
6770b57cec5SDimitry Andric     setConfigs(args);
6780b57cec5SDimitry Andric     checkOptions();
6790b57cec5SDimitry Andric     if (errorCount())
6800b57cec5SDimitry Andric       return;
6810b57cec5SDimitry Andric 
6820fca6ea1SDimitry Andric     invokeELFT(link, args);
6830b57cec5SDimitry Andric   }
6840b57cec5SDimitry Andric 
6855ffd83dbSDimitry Andric   if (config->timeTraceEnabled) {
686349cc55cSDimitry Andric     checkError(timeTraceProfilerWrite(
68781ad6265SDimitry Andric         args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
6885ffd83dbSDimitry Andric     timeTraceProfilerCleanup();
6895ffd83dbSDimitry Andric   }
6905ffd83dbSDimitry Andric }
6915ffd83dbSDimitry Andric 
getRpath(opt::InputArgList & args)6920b57cec5SDimitry Andric static std::string getRpath(opt::InputArgList &args) {
693bdd1243dSDimitry Andric   SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath);
6940b57cec5SDimitry Andric   return llvm::join(v.begin(), v.end(), ":");
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric // Determines what we should do if there are remaining unresolved
6980b57cec5SDimitry Andric // symbols after the name resolution.
setUnresolvedSymbolPolicy(opt::InputArgList & args)699e8d8bef9SDimitry Andric static void setUnresolvedSymbolPolicy(opt::InputArgList &args) {
7000b57cec5SDimitry Andric   UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
7010b57cec5SDimitry Andric                                               OPT_warn_unresolved_symbols, true)
7020b57cec5SDimitry Andric                                      ? UnresolvedPolicy::ReportError
7030b57cec5SDimitry Andric                                      : UnresolvedPolicy::Warn;
704349cc55cSDimitry Andric   // -shared implies --unresolved-symbols=ignore-all because missing
705e8d8bef9SDimitry Andric   // symbols are likely to be resolved at runtime.
706e8d8bef9SDimitry Andric   bool diagRegular = !config->shared, diagShlib = !config->shared;
7070b57cec5SDimitry Andric 
708e8d8bef9SDimitry Andric   for (const opt::Arg *arg : args) {
7090b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
7100b57cec5SDimitry Andric     case OPT_unresolved_symbols: {
7110b57cec5SDimitry Andric       StringRef s = arg->getValue();
712e8d8bef9SDimitry Andric       if (s == "ignore-all") {
713e8d8bef9SDimitry Andric         diagRegular = false;
714e8d8bef9SDimitry Andric         diagShlib = false;
715e8d8bef9SDimitry Andric       } else if (s == "ignore-in-object-files") {
716e8d8bef9SDimitry Andric         diagRegular = false;
717e8d8bef9SDimitry Andric         diagShlib = true;
718e8d8bef9SDimitry Andric       } else if (s == "ignore-in-shared-libs") {
719e8d8bef9SDimitry Andric         diagRegular = true;
720e8d8bef9SDimitry Andric         diagShlib = false;
721e8d8bef9SDimitry Andric       } else if (s == "report-all") {
722e8d8bef9SDimitry Andric         diagRegular = true;
723e8d8bef9SDimitry Andric         diagShlib = true;
724e8d8bef9SDimitry Andric       } else {
7250b57cec5SDimitry Andric         error("unknown --unresolved-symbols value: " + s);
726e8d8bef9SDimitry Andric       }
727e8d8bef9SDimitry Andric       break;
7280b57cec5SDimitry Andric     }
7290b57cec5SDimitry Andric     case OPT_no_undefined:
730e8d8bef9SDimitry Andric       diagRegular = true;
731e8d8bef9SDimitry Andric       break;
7320b57cec5SDimitry Andric     case OPT_z:
7330b57cec5SDimitry Andric       if (StringRef(arg->getValue()) == "defs")
734e8d8bef9SDimitry Andric         diagRegular = true;
735e8d8bef9SDimitry Andric       else if (StringRef(arg->getValue()) == "undefs")
736e8d8bef9SDimitry Andric         diagRegular = false;
7377a6dacacSDimitry Andric       else
7387a6dacacSDimitry Andric         break;
7397a6dacacSDimitry Andric       arg->claim();
740e8d8bef9SDimitry Andric       break;
741e8d8bef9SDimitry Andric     case OPT_allow_shlib_undefined:
742e8d8bef9SDimitry Andric       diagShlib = false;
743e8d8bef9SDimitry Andric       break;
744e8d8bef9SDimitry Andric     case OPT_no_allow_shlib_undefined:
745e8d8bef9SDimitry Andric       diagShlib = true;
746e8d8bef9SDimitry Andric       break;
7470b57cec5SDimitry Andric     }
7480b57cec5SDimitry Andric   }
7490b57cec5SDimitry Andric 
750e8d8bef9SDimitry Andric   config->unresolvedSymbols =
751e8d8bef9SDimitry Andric       diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;
752e8d8bef9SDimitry Andric   config->unresolvedSymbolsInShlib =
753e8d8bef9SDimitry Andric       diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric 
getTarget2(opt::InputArgList & args)7560b57cec5SDimitry Andric static Target2Policy getTarget2(opt::InputArgList &args) {
7570b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
7580b57cec5SDimitry Andric   if (s == "rel")
7590b57cec5SDimitry Andric     return Target2Policy::Rel;
7600b57cec5SDimitry Andric   if (s == "abs")
7610b57cec5SDimitry Andric     return Target2Policy::Abs;
7620b57cec5SDimitry Andric   if (s == "got-rel")
7630b57cec5SDimitry Andric     return Target2Policy::GotRel;
7640b57cec5SDimitry Andric   error("unknown --target2 option: " + s);
7650b57cec5SDimitry Andric   return Target2Policy::GotRel;
7660b57cec5SDimitry Andric }
7670b57cec5SDimitry Andric 
isOutputFormatBinary(opt::InputArgList & args)7680b57cec5SDimitry Andric static bool isOutputFormatBinary(opt::InputArgList &args) {
7690b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_oformat, "elf");
7700b57cec5SDimitry Andric   if (s == "binary")
7710b57cec5SDimitry Andric     return true;
77206c3fb27SDimitry Andric   if (!s.starts_with("elf"))
7730b57cec5SDimitry Andric     error("unknown --oformat value: " + s);
7740b57cec5SDimitry Andric   return false;
7750b57cec5SDimitry Andric }
7760b57cec5SDimitry Andric 
getDiscard(opt::InputArgList & args)7770b57cec5SDimitry Andric static DiscardPolicy getDiscard(opt::InputArgList &args) {
7780b57cec5SDimitry Andric   auto *arg =
7790b57cec5SDimitry Andric       args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
7800b57cec5SDimitry Andric   if (!arg)
7810b57cec5SDimitry Andric     return DiscardPolicy::Default;
7820b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_discard_all)
7830b57cec5SDimitry Andric     return DiscardPolicy::All;
7840b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_discard_locals)
7850b57cec5SDimitry Andric     return DiscardPolicy::Locals;
7860b57cec5SDimitry Andric   return DiscardPolicy::None;
7870b57cec5SDimitry Andric }
7880b57cec5SDimitry Andric 
getDynamicLinker(opt::InputArgList & args)7890b57cec5SDimitry Andric static StringRef getDynamicLinker(opt::InputArgList &args) {
7900b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
79155e4f9d5SDimitry Andric   if (!arg)
7920b57cec5SDimitry Andric     return "";
79355e4f9d5SDimitry Andric   if (arg->getOption().getID() == OPT_no_dynamic_linker) {
79455e4f9d5SDimitry Andric     // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
79555e4f9d5SDimitry Andric     config->noDynamicLinker = true;
79655e4f9d5SDimitry Andric     return "";
79755e4f9d5SDimitry Andric   }
7980b57cec5SDimitry Andric   return arg->getValue();
7990b57cec5SDimitry Andric }
8000b57cec5SDimitry Andric 
getMemtagMode(opt::InputArgList & args)80181ad6265SDimitry Andric static int getMemtagMode(opt::InputArgList &args) {
80281ad6265SDimitry Andric   StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode);
80306c3fb27SDimitry Andric   if (memtagModeArg.empty()) {
80406c3fb27SDimitry Andric     if (config->androidMemtagStack)
80506c3fb27SDimitry Andric       warn("--android-memtag-mode is unspecified, leaving "
80606c3fb27SDimitry Andric            "--android-memtag-stack a no-op");
80706c3fb27SDimitry Andric     else if (config->androidMemtagHeap)
80806c3fb27SDimitry Andric       warn("--android-memtag-mode is unspecified, leaving "
80906c3fb27SDimitry Andric            "--android-memtag-heap a no-op");
81006c3fb27SDimitry Andric     return ELF::NT_MEMTAG_LEVEL_NONE;
81106c3fb27SDimitry Andric   }
81206c3fb27SDimitry Andric 
81306c3fb27SDimitry Andric   if (memtagModeArg == "sync")
81481ad6265SDimitry Andric     return ELF::NT_MEMTAG_LEVEL_SYNC;
81581ad6265SDimitry Andric   if (memtagModeArg == "async")
81681ad6265SDimitry Andric     return ELF::NT_MEMTAG_LEVEL_ASYNC;
81781ad6265SDimitry Andric   if (memtagModeArg == "none")
81881ad6265SDimitry Andric     return ELF::NT_MEMTAG_LEVEL_NONE;
81981ad6265SDimitry Andric 
82081ad6265SDimitry Andric   error("unknown --android-memtag-mode value: \"" + memtagModeArg +
82181ad6265SDimitry Andric         "\", should be one of {async, sync, none}");
82281ad6265SDimitry Andric   return ELF::NT_MEMTAG_LEVEL_NONE;
82381ad6265SDimitry Andric }
82481ad6265SDimitry Andric 
getICF(opt::InputArgList & args)8250b57cec5SDimitry Andric static ICFLevel getICF(opt::InputArgList &args) {
8260b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
8270b57cec5SDimitry Andric   if (!arg || arg->getOption().getID() == OPT_icf_none)
8280b57cec5SDimitry Andric     return ICFLevel::None;
8290b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_icf_safe)
8300b57cec5SDimitry Andric     return ICFLevel::Safe;
8310b57cec5SDimitry Andric   return ICFLevel::All;
8320b57cec5SDimitry Andric }
8330b57cec5SDimitry Andric 
getStrip(opt::InputArgList & args)8340b57cec5SDimitry Andric static StripPolicy getStrip(opt::InputArgList &args) {
8350b57cec5SDimitry Andric   if (args.hasArg(OPT_relocatable))
8360b57cec5SDimitry Andric     return StripPolicy::None;
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
8390b57cec5SDimitry Andric   if (!arg)
8400b57cec5SDimitry Andric     return StripPolicy::None;
8410b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_strip_all)
8420b57cec5SDimitry Andric     return StripPolicy::All;
8430b57cec5SDimitry Andric   return StripPolicy::Debug;
8440b57cec5SDimitry Andric }
8450b57cec5SDimitry Andric 
parseSectionAddress(StringRef s,opt::InputArgList & args,const opt::Arg & arg)8460b57cec5SDimitry Andric static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
8470b57cec5SDimitry Andric                                     const opt::Arg &arg) {
8480b57cec5SDimitry Andric   uint64_t va = 0;
84906c3fb27SDimitry Andric   if (s.starts_with("0x"))
8500b57cec5SDimitry Andric     s = s.drop_front(2);
8510b57cec5SDimitry Andric   if (!to_integer(s, va, 16))
8520b57cec5SDimitry Andric     error("invalid argument: " + arg.getAsString(args));
8530b57cec5SDimitry Andric   return va;
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric 
getSectionStartMap(opt::InputArgList & args)8560b57cec5SDimitry Andric static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
8570b57cec5SDimitry Andric   StringMap<uint64_t> ret;
8580b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_section_start)) {
8590b57cec5SDimitry Andric     StringRef name;
8600b57cec5SDimitry Andric     StringRef addr;
8610b57cec5SDimitry Andric     std::tie(name, addr) = StringRef(arg->getValue()).split('=');
8620b57cec5SDimitry Andric     ret[name] = parseSectionAddress(addr, args, *arg);
8630b57cec5SDimitry Andric   }
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Ttext))
8660b57cec5SDimitry Andric     ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
8670b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Tdata))
8680b57cec5SDimitry Andric     ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
8690b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Tbss))
8700b57cec5SDimitry Andric     ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
8710b57cec5SDimitry Andric   return ret;
8720b57cec5SDimitry Andric }
8730b57cec5SDimitry Andric 
getSortSection(opt::InputArgList & args)8740b57cec5SDimitry Andric static SortSectionPolicy getSortSection(opt::InputArgList &args) {
8750b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_sort_section);
8760b57cec5SDimitry Andric   if (s == "alignment")
8770b57cec5SDimitry Andric     return SortSectionPolicy::Alignment;
8780b57cec5SDimitry Andric   if (s == "name")
8790b57cec5SDimitry Andric     return SortSectionPolicy::Name;
8800b57cec5SDimitry Andric   if (!s.empty())
8810b57cec5SDimitry Andric     error("unknown --sort-section rule: " + s);
8820b57cec5SDimitry Andric   return SortSectionPolicy::Default;
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
getOrphanHandling(opt::InputArgList & args)8850b57cec5SDimitry Andric static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
8860b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
8870b57cec5SDimitry Andric   if (s == "warn")
8880b57cec5SDimitry Andric     return OrphanHandlingPolicy::Warn;
8890b57cec5SDimitry Andric   if (s == "error")
8900b57cec5SDimitry Andric     return OrphanHandlingPolicy::Error;
8910b57cec5SDimitry Andric   if (s != "place")
8920b57cec5SDimitry Andric     error("unknown --orphan-handling mode: " + s);
8930b57cec5SDimitry Andric   return OrphanHandlingPolicy::Place;
8940b57cec5SDimitry Andric }
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric // Parse --build-id or --build-id=<style>. We handle "tree" as a
8970b57cec5SDimitry Andric // synonym for "sha1" because all our hash functions including
898349cc55cSDimitry Andric // --build-id=sha1 are actually tree hashes for performance reasons.
899bdd1243dSDimitry Andric static std::pair<BuildIdKind, SmallVector<uint8_t, 0>>
getBuildId(opt::InputArgList & args)9000b57cec5SDimitry Andric getBuildId(opt::InputArgList &args) {
901972a253aSDimitry Andric   auto *arg = args.getLastArg(OPT_build_id);
9020b57cec5SDimitry Andric   if (!arg)
9030b57cec5SDimitry Andric     return {BuildIdKind::None, {}};
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric   StringRef s = arg->getValue();
9060b57cec5SDimitry Andric   if (s == "fast")
9070b57cec5SDimitry Andric     return {BuildIdKind::Fast, {}};
9080b57cec5SDimitry Andric   if (s == "md5")
9090b57cec5SDimitry Andric     return {BuildIdKind::Md5, {}};
9100b57cec5SDimitry Andric   if (s == "sha1" || s == "tree")
9110b57cec5SDimitry Andric     return {BuildIdKind::Sha1, {}};
9120b57cec5SDimitry Andric   if (s == "uuid")
9130b57cec5SDimitry Andric     return {BuildIdKind::Uuid, {}};
91406c3fb27SDimitry Andric   if (s.starts_with("0x"))
9150b57cec5SDimitry Andric     return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   if (s != "none")
9180b57cec5SDimitry Andric     error("unknown --build-id style: " + s);
9190b57cec5SDimitry Andric   return {BuildIdKind::None, {}};
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric 
getPackDynRelocs(opt::InputArgList & args)9220b57cec5SDimitry Andric static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
9230b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
9240b57cec5SDimitry Andric   if (s == "android")
9250b57cec5SDimitry Andric     return {true, false};
9260b57cec5SDimitry Andric   if (s == "relr")
9270b57cec5SDimitry Andric     return {false, true};
9280b57cec5SDimitry Andric   if (s == "android+relr")
9290b57cec5SDimitry Andric     return {true, true};
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric   if (s != "none")
932349cc55cSDimitry Andric     error("unknown --pack-dyn-relocs format: " + s);
9330b57cec5SDimitry Andric   return {false, false};
9340b57cec5SDimitry Andric }
9350b57cec5SDimitry Andric 
readCallGraph(MemoryBufferRef mb)9360b57cec5SDimitry Andric static void readCallGraph(MemoryBufferRef mb) {
9370b57cec5SDimitry Andric   // Build a map from symbol name to section
9380b57cec5SDimitry Andric   DenseMap<StringRef, Symbol *> map;
939bdd1243dSDimitry Andric   for (ELFFileBase *file : ctx.objectFiles)
9400b57cec5SDimitry Andric     for (Symbol *sym : file->getSymbols())
9410b57cec5SDimitry Andric       map[sym->getName()] = sym;
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric   auto findSection = [&](StringRef name) -> InputSectionBase * {
9440b57cec5SDimitry Andric     Symbol *sym = map.lookup(name);
9450b57cec5SDimitry Andric     if (!sym) {
9460b57cec5SDimitry Andric       if (config->warnSymbolOrdering)
9470b57cec5SDimitry Andric         warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
9480b57cec5SDimitry Andric       return nullptr;
9490b57cec5SDimitry Andric     }
9500b57cec5SDimitry Andric     maybeWarnUnorderableSymbol(sym);
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric     if (Defined *dr = dyn_cast_or_null<Defined>(sym))
9530b57cec5SDimitry Andric       return dyn_cast_or_null<InputSectionBase>(dr->section);
9540b57cec5SDimitry Andric     return nullptr;
9550b57cec5SDimitry Andric   };
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric   for (StringRef line : args::getLines(mb)) {
9580b57cec5SDimitry Andric     SmallVector<StringRef, 3> fields;
9590b57cec5SDimitry Andric     line.split(fields, ' ');
9600b57cec5SDimitry Andric     uint64_t count;
9610b57cec5SDimitry Andric 
9620b57cec5SDimitry Andric     if (fields.size() != 3 || !to_integer(fields[2], count)) {
9630b57cec5SDimitry Andric       error(mb.getBufferIdentifier() + ": parse error");
9640b57cec5SDimitry Andric       return;
9650b57cec5SDimitry Andric     }
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric     if (InputSectionBase *from = findSection(fields[0]))
9680b57cec5SDimitry Andric       if (InputSectionBase *to = findSection(fields[1]))
9690b57cec5SDimitry Andric         config->callGraphProfile[std::make_pair(from, to)] += count;
9700b57cec5SDimitry Andric   }
9710b57cec5SDimitry Andric }
9720b57cec5SDimitry Andric 
973fe6060f1SDimitry Andric // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
974fe6060f1SDimitry Andric // true and populates cgProfile and symbolIndices.
975fe6060f1SDimitry Andric template <class ELFT>
976fe6060f1SDimitry Andric static bool
processCallGraphRelocations(SmallVector<uint32_t,32> & symbolIndices,ArrayRef<typename ELFT::CGProfile> & cgProfile,ObjFile<ELFT> * inputObj)977fe6060f1SDimitry Andric processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices,
978fe6060f1SDimitry Andric                             ArrayRef<typename ELFT::CGProfile> &cgProfile,
979fe6060f1SDimitry Andric                             ObjFile<ELFT> *inputObj) {
980fe6060f1SDimitry Andric   if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
981fe6060f1SDimitry Andric     return false;
982fe6060f1SDimitry Andric 
9830eae32dcSDimitry Andric   ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
9840eae32dcSDimitry Andric       inputObj->template getELFShdrs<ELFT>();
9850eae32dcSDimitry Andric   symbolIndices.clear();
9860eae32dcSDimitry Andric   const ELFFile<ELFT> &obj = inputObj->getObj();
987fe6060f1SDimitry Andric   cgProfile =
988fe6060f1SDimitry Andric       check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(
989fe6060f1SDimitry Andric           objSections[inputObj->cgProfileSectionIndex]));
990fe6060f1SDimitry Andric 
991fe6060f1SDimitry Andric   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
992fe6060f1SDimitry Andric     const Elf_Shdr_Impl<ELFT> &sec = objSections[i];
993fe6060f1SDimitry Andric     if (sec.sh_info == inputObj->cgProfileSectionIndex) {
994*62987288SDimitry Andric       if (sec.sh_type == SHT_CREL) {
995*62987288SDimitry Andric         auto crels =
996*62987288SDimitry Andric             CHECK(obj.crels(sec), "could not retrieve cg profile rela section");
997*62987288SDimitry Andric         for (const auto &rel : crels.first)
998*62987288SDimitry Andric           symbolIndices.push_back(rel.getSymbol(false));
999*62987288SDimitry Andric         for (const auto &rel : crels.second)
1000*62987288SDimitry Andric           symbolIndices.push_back(rel.getSymbol(false));
1001*62987288SDimitry Andric         break;
1002*62987288SDimitry Andric       }
1003fe6060f1SDimitry Andric       if (sec.sh_type == SHT_RELA) {
1004fe6060f1SDimitry Andric         ArrayRef<typename ELFT::Rela> relas =
1005fe6060f1SDimitry Andric             CHECK(obj.relas(sec), "could not retrieve cg profile rela section");
1006fe6060f1SDimitry Andric         for (const typename ELFT::Rela &rel : relas)
1007fe6060f1SDimitry Andric           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
1008fe6060f1SDimitry Andric         break;
1009fe6060f1SDimitry Andric       }
1010fe6060f1SDimitry Andric       if (sec.sh_type == SHT_REL) {
1011fe6060f1SDimitry Andric         ArrayRef<typename ELFT::Rel> rels =
1012fe6060f1SDimitry Andric             CHECK(obj.rels(sec), "could not retrieve cg profile rel section");
1013fe6060f1SDimitry Andric         for (const typename ELFT::Rel &rel : rels)
1014fe6060f1SDimitry Andric           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
1015fe6060f1SDimitry Andric         break;
1016fe6060f1SDimitry Andric       }
1017fe6060f1SDimitry Andric     }
1018fe6060f1SDimitry Andric   }
1019fe6060f1SDimitry Andric   if (symbolIndices.empty())
1020fe6060f1SDimitry Andric     warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");
1021fe6060f1SDimitry Andric   return !symbolIndices.empty();
1022fe6060f1SDimitry Andric }
1023fe6060f1SDimitry Andric 
readCallGraphsFromObjectFiles()10240b57cec5SDimitry Andric template <class ELFT> static void readCallGraphsFromObjectFiles() {
1025fe6060f1SDimitry Andric   SmallVector<uint32_t, 32> symbolIndices;
1026fe6060f1SDimitry Andric   ArrayRef<typename ELFT::CGProfile> cgProfile;
1027bdd1243dSDimitry Andric   for (auto file : ctx.objectFiles) {
10280b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(file);
1029fe6060f1SDimitry Andric     if (!processCallGraphRelocations(symbolIndices, cgProfile, obj))
1030fe6060f1SDimitry Andric       continue;
10310b57cec5SDimitry Andric 
1032fe6060f1SDimitry Andric     if (symbolIndices.size() != cgProfile.size() * 2)
1033fe6060f1SDimitry Andric       fatal("number of relocations doesn't match Weights");
1034fe6060f1SDimitry Andric 
1035fe6060f1SDimitry Andric     for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {
1036fe6060f1SDimitry Andric       const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];
1037fe6060f1SDimitry Andric       uint32_t fromIndex = symbolIndices[i * 2];
1038fe6060f1SDimitry Andric       uint32_t toIndex = symbolIndices[i * 2 + 1];
1039fe6060f1SDimitry Andric       auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
1040fe6060f1SDimitry Andric       auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
10410b57cec5SDimitry Andric       if (!fromSym || !toSym)
10420b57cec5SDimitry Andric         continue;
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric       auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
10450b57cec5SDimitry Andric       auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
10460b57cec5SDimitry Andric       if (from && to)
10470b57cec5SDimitry Andric         config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
10480b57cec5SDimitry Andric     }
10490b57cec5SDimitry Andric   }
10500b57cec5SDimitry Andric }
10510b57cec5SDimitry Andric 
10525f757f3fSDimitry Andric template <class ELFT>
ltoValidateAllVtablesHaveTypeInfos(opt::InputArgList & args)10535f757f3fSDimitry Andric static void ltoValidateAllVtablesHaveTypeInfos(opt::InputArgList &args) {
10545f757f3fSDimitry Andric   DenseSet<StringRef> typeInfoSymbols;
10555f757f3fSDimitry Andric   SmallSetVector<StringRef, 0> vtableSymbols;
10565f757f3fSDimitry Andric   auto processVtableAndTypeInfoSymbols = [&](StringRef name) {
10575f757f3fSDimitry Andric     if (name.consume_front("_ZTI"))
10585f757f3fSDimitry Andric       typeInfoSymbols.insert(name);
10595f757f3fSDimitry Andric     else if (name.consume_front("_ZTV"))
10605f757f3fSDimitry Andric       vtableSymbols.insert(name);
10615f757f3fSDimitry Andric   };
10625f757f3fSDimitry Andric 
10635f757f3fSDimitry Andric   // Examine all native symbol tables.
10645f757f3fSDimitry Andric   for (ELFFileBase *f : ctx.objectFiles) {
10655f757f3fSDimitry Andric     using Elf_Sym = typename ELFT::Sym;
10665f757f3fSDimitry Andric     for (const Elf_Sym &s : f->template getGlobalELFSyms<ELFT>()) {
10675f757f3fSDimitry Andric       if (s.st_shndx != SHN_UNDEF) {
10685f757f3fSDimitry Andric         StringRef name = check(s.getName(f->getStringTable()));
10695f757f3fSDimitry Andric         processVtableAndTypeInfoSymbols(name);
10705f757f3fSDimitry Andric       }
10715f757f3fSDimitry Andric     }
10725f757f3fSDimitry Andric   }
10735f757f3fSDimitry Andric 
10745f757f3fSDimitry Andric   for (SharedFile *f : ctx.sharedFiles) {
10755f757f3fSDimitry Andric     using Elf_Sym = typename ELFT::Sym;
10765f757f3fSDimitry Andric     for (const Elf_Sym &s : f->template getELFSyms<ELFT>()) {
10775f757f3fSDimitry Andric       if (s.st_shndx != SHN_UNDEF) {
10785f757f3fSDimitry Andric         StringRef name = check(s.getName(f->getStringTable()));
10795f757f3fSDimitry Andric         processVtableAndTypeInfoSymbols(name);
10805f757f3fSDimitry Andric       }
10815f757f3fSDimitry Andric     }
10825f757f3fSDimitry Andric   }
10835f757f3fSDimitry Andric 
10845f757f3fSDimitry Andric   SmallSetVector<StringRef, 0> vtableSymbolsWithNoRTTI;
10855f757f3fSDimitry Andric   for (StringRef s : vtableSymbols)
10865f757f3fSDimitry Andric     if (!typeInfoSymbols.count(s))
10875f757f3fSDimitry Andric       vtableSymbolsWithNoRTTI.insert(s);
10885f757f3fSDimitry Andric 
10895f757f3fSDimitry Andric   // Remove known safe symbols.
10905f757f3fSDimitry Andric   for (auto *arg : args.filtered(OPT_lto_known_safe_vtables)) {
10915f757f3fSDimitry Andric     StringRef knownSafeName = arg->getValue();
10925f757f3fSDimitry Andric     if (!knownSafeName.consume_front("_ZTV"))
10935f757f3fSDimitry Andric       error("--lto-known-safe-vtables=: expected symbol to start with _ZTV, "
10945f757f3fSDimitry Andric             "but got " +
10955f757f3fSDimitry Andric             knownSafeName);
10967a6dacacSDimitry Andric     Expected<GlobPattern> pat = GlobPattern::create(knownSafeName);
10977a6dacacSDimitry Andric     if (!pat)
10987a6dacacSDimitry Andric       error("--lto-known-safe-vtables=: " + toString(pat.takeError()));
10997a6dacacSDimitry Andric     vtableSymbolsWithNoRTTI.remove_if(
11007a6dacacSDimitry Andric         [&](StringRef s) { return pat->match(s); });
11015f757f3fSDimitry Andric   }
11025f757f3fSDimitry Andric 
11035f757f3fSDimitry Andric   ctx.ltoAllVtablesHaveTypeInfos = vtableSymbolsWithNoRTTI.empty();
11045f757f3fSDimitry Andric   // Check for unmatched RTTI symbols
11055f757f3fSDimitry Andric   for (StringRef s : vtableSymbolsWithNoRTTI) {
11065f757f3fSDimitry Andric     message(
11075f757f3fSDimitry Andric         "--lto-validate-all-vtables-have-type-infos: RTTI missing for vtable "
11085f757f3fSDimitry Andric         "_ZTV" +
11095f757f3fSDimitry Andric         s + ", --lto-whole-program-visibility disabled");
11105f757f3fSDimitry Andric   }
11115f757f3fSDimitry Andric }
11125f757f3fSDimitry Andric 
getCGProfileSortKind(opt::InputArgList & args)11135f757f3fSDimitry Andric static CGProfileSortKind getCGProfileSortKind(opt::InputArgList &args) {
11145f757f3fSDimitry Andric   StringRef s = args.getLastArgValue(OPT_call_graph_profile_sort, "cdsort");
11155f757f3fSDimitry Andric   if (s == "hfsort")
11165f757f3fSDimitry Andric     return CGProfileSortKind::Hfsort;
11175f757f3fSDimitry Andric   if (s == "cdsort")
11185f757f3fSDimitry Andric     return CGProfileSortKind::Cdsort;
11195f757f3fSDimitry Andric   if (s != "none")
11205f757f3fSDimitry Andric     error("unknown --call-graph-profile-sort= value: " + s);
11215f757f3fSDimitry Andric   return CGProfileSortKind::None;
11225f757f3fSDimitry Andric }
11235f757f3fSDimitry Andric 
getCompressionType(StringRef s,StringRef option)112406c3fb27SDimitry Andric static DebugCompressionType getCompressionType(StringRef s, StringRef option) {
112506c3fb27SDimitry Andric   DebugCompressionType type = StringSwitch<DebugCompressionType>(s)
112606c3fb27SDimitry Andric                                   .Case("zlib", DebugCompressionType::Zlib)
112706c3fb27SDimitry Andric                                   .Case("zstd", DebugCompressionType::Zstd)
112806c3fb27SDimitry Andric                                   .Default(DebugCompressionType::None);
112906c3fb27SDimitry Andric   if (type == DebugCompressionType::None) {
1130bdd1243dSDimitry Andric     if (s != "none")
113106c3fb27SDimitry Andric       error("unknown " + option + " value: " + s);
113206c3fb27SDimitry Andric   } else if (const char *reason = compression::getReasonIfUnsupported(
113306c3fb27SDimitry Andric                  compression::formatFor(type))) {
113406c3fb27SDimitry Andric     error(option + ": " + reason);
113506c3fb27SDimitry Andric   }
113606c3fb27SDimitry Andric   return type;
11370b57cec5SDimitry Andric }
11380b57cec5SDimitry Andric 
getAliasSpelling(opt::Arg * arg)113985868e8aSDimitry Andric static StringRef getAliasSpelling(opt::Arg *arg) {
114085868e8aSDimitry Andric   if (const opt::Arg *alias = arg->getAlias())
114185868e8aSDimitry Andric     return alias->getSpelling();
114285868e8aSDimitry Andric   return arg->getSpelling();
114385868e8aSDimitry Andric }
114485868e8aSDimitry Andric 
getOldNewOptions(opt::InputArgList & args,unsigned id)11450b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
11460b57cec5SDimitry Andric                                                         unsigned id) {
11470b57cec5SDimitry Andric   auto *arg = args.getLastArg(id);
11480b57cec5SDimitry Andric   if (!arg)
11490b57cec5SDimitry Andric     return {"", ""};
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric   StringRef s = arg->getValue();
11520b57cec5SDimitry Andric   std::pair<StringRef, StringRef> ret = s.split(';');
11530b57cec5SDimitry Andric   if (ret.second.empty())
115485868e8aSDimitry Andric     error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
11550b57cec5SDimitry Andric   return ret;
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric 
115806c3fb27SDimitry Andric // Parse options of the form "old;new[;extra]".
115906c3fb27SDimitry Andric static std::tuple<StringRef, StringRef, StringRef>
getOldNewOptionsExtra(opt::InputArgList & args,unsigned id)116006c3fb27SDimitry Andric getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {
116106c3fb27SDimitry Andric   auto [oldDir, second] = getOldNewOptions(args, id);
116206c3fb27SDimitry Andric   auto [newDir, extraDir] = second.split(';');
116306c3fb27SDimitry Andric   return {oldDir, newDir, extraDir};
116406c3fb27SDimitry Andric }
116506c3fb27SDimitry Andric 
11660b57cec5SDimitry Andric // Parse the symbol ordering file and warn for any duplicate entries.
getSymbolOrderingFile(MemoryBufferRef mb)1167bdd1243dSDimitry Andric static SmallVector<StringRef, 0> getSymbolOrderingFile(MemoryBufferRef mb) {
1168bdd1243dSDimitry Andric   SetVector<StringRef, SmallVector<StringRef, 0>> names;
11690b57cec5SDimitry Andric   for (StringRef s : args::getLines(mb))
11700b57cec5SDimitry Andric     if (!names.insert(s) && config->warnSymbolOrdering)
11710b57cec5SDimitry Andric       warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   return names.takeVector();
11740b57cec5SDimitry Andric }
11750b57cec5SDimitry Andric 
getIsRela(opt::InputArgList & args)11765ffd83dbSDimitry Andric static bool getIsRela(opt::InputArgList &args) {
11777a6dacacSDimitry Andric   // The psABI specifies the default relocation entry format.
11787a6dacacSDimitry Andric   bool rela = is_contained({EM_AARCH64, EM_AMDGPU, EM_HEXAGON, EM_LOONGARCH,
117974626c16SDimitry Andric                             EM_PPC, EM_PPC64, EM_RISCV, EM_S390, EM_X86_64},
11807a6dacacSDimitry Andric                            config->emachine);
11815ffd83dbSDimitry Andric   // If -z rel or -z rela is specified, use the last option.
11827a6dacacSDimitry Andric   for (auto *arg : args.filtered(OPT_z)) {
11835ffd83dbSDimitry Andric     StringRef s(arg->getValue());
11845ffd83dbSDimitry Andric     if (s == "rel")
11857a6dacacSDimitry Andric       rela = false;
11867a6dacacSDimitry Andric     else if (s == "rela")
11877a6dacacSDimitry Andric       rela = true;
11887a6dacacSDimitry Andric     else
11897a6dacacSDimitry Andric       continue;
11907a6dacacSDimitry Andric     arg->claim();
11915ffd83dbSDimitry Andric   }
11927a6dacacSDimitry Andric   return rela;
11935ffd83dbSDimitry Andric }
11945ffd83dbSDimitry Andric 
parseClangOption(StringRef opt,const Twine & msg)11950b57cec5SDimitry Andric static void parseClangOption(StringRef opt, const Twine &msg) {
11960b57cec5SDimitry Andric   std::string err;
11970b57cec5SDimitry Andric   raw_string_ostream os(err);
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric   const char *argv[] = {config->progName.data(), opt.data()};
12000b57cec5SDimitry Andric   if (cl::ParseCommandLineOptions(2, argv, "", &os))
12010b57cec5SDimitry Andric     return;
12020b57cec5SDimitry Andric   os.flush();
12030b57cec5SDimitry Andric   error(msg + ": " + StringRef(err).trim());
12040b57cec5SDimitry Andric }
12050b57cec5SDimitry Andric 
12060eae32dcSDimitry Andric // Checks the parameter of the bti-report and cet-report options.
isValidReportString(StringRef arg)12070eae32dcSDimitry Andric static bool isValidReportString(StringRef arg) {
12080eae32dcSDimitry Andric   return arg == "none" || arg == "warning" || arg == "error";
12090eae32dcSDimitry Andric }
12100eae32dcSDimitry Andric 
121106c3fb27SDimitry Andric // Process a remap pattern 'from-glob=to-file'.
remapInputs(StringRef line,const Twine & location)121206c3fb27SDimitry Andric static bool remapInputs(StringRef line, const Twine &location) {
121306c3fb27SDimitry Andric   SmallVector<StringRef, 0> fields;
121406c3fb27SDimitry Andric   line.split(fields, '=');
121506c3fb27SDimitry Andric   if (fields.size() != 2 || fields[1].empty()) {
121606c3fb27SDimitry Andric     error(location + ": parse error, not 'from-glob=to-file'");
121706c3fb27SDimitry Andric     return true;
121806c3fb27SDimitry Andric   }
121906c3fb27SDimitry Andric   if (!hasWildcard(fields[0]))
122006c3fb27SDimitry Andric     config->remapInputs[fields[0]] = fields[1];
122106c3fb27SDimitry Andric   else if (Expected<GlobPattern> pat = GlobPattern::create(fields[0]))
122206c3fb27SDimitry Andric     config->remapInputsWildcards.emplace_back(std::move(*pat), fields[1]);
122306c3fb27SDimitry Andric   else {
12245f757f3fSDimitry Andric     error(location + ": " + toString(pat.takeError()) + ": " + fields[0]);
122506c3fb27SDimitry Andric     return true;
122606c3fb27SDimitry Andric   }
122706c3fb27SDimitry Andric   return false;
122806c3fb27SDimitry Andric }
122906c3fb27SDimitry Andric 
12300b57cec5SDimitry Andric // Initializes Config members by the command line options.
readConfigs(opt::InputArgList & args)12310b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args) {
12320b57cec5SDimitry Andric   errorHandler().verbose = args.hasArg(OPT_verbose);
12330b57cec5SDimitry Andric   errorHandler().vsDiagnostics =
12340b57cec5SDimitry Andric       args.hasArg(OPT_visual_studio_diagnostics_format, false);
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric   config->allowMultipleDefinition =
12377a6dacacSDimitry Andric       hasZOption(args, "muldefs") ||
12380b57cec5SDimitry Andric       args.hasFlag(OPT_allow_multiple_definition,
12397a6dacacSDimitry Andric                    OPT_no_allow_multiple_definition, false);
124081ad6265SDimitry Andric   config->androidMemtagHeap =
124181ad6265SDimitry Andric       args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false);
124281ad6265SDimitry Andric   config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack,
124381ad6265SDimitry Andric                                             OPT_no_android_memtag_stack, false);
12445f757f3fSDimitry Andric   config->fatLTOObjects =
12455f757f3fSDimitry Andric       args.hasFlag(OPT_fat_lto_objects, OPT_no_fat_lto_objects, false);
124681ad6265SDimitry Andric   config->androidMemtagMode = getMemtagMode(args);
12470b57cec5SDimitry Andric   config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
124806c3fb27SDimitry Andric   config->armBe8 = args.hasArg(OPT_be8);
12495f757f3fSDimitry Andric   if (opt::Arg *arg = args.getLastArg(
12505f757f3fSDimitry Andric           OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,
12515f757f3fSDimitry Andric           OPT_Bsymbolic_functions, OPT_Bsymbolic_non_weak, OPT_Bsymbolic)) {
12526e75b2fbSDimitry Andric     if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
12536e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::NonWeakFunctions;
12546e75b2fbSDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic_functions))
12556e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::Functions;
12565f757f3fSDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic_non_weak))
12575f757f3fSDimitry Andric       config->bsymbolic = BsymbolicKind::NonWeak;
1258fe6060f1SDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic))
12596e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::All;
1260fe6060f1SDimitry Andric   }
12615f757f3fSDimitry Andric   config->callGraphProfileSort = getCGProfileSortKind(args);
12620b57cec5SDimitry Andric   config->checkSections =
12630b57cec5SDimitry Andric       args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
12640b57cec5SDimitry Andric   config->chroot = args.getLastArgValue(OPT_chroot);
12650fca6ea1SDimitry Andric   if (auto *arg = args.getLastArg(OPT_compress_debug_sections)) {
12660fca6ea1SDimitry Andric     config->compressDebugSections =
12670fca6ea1SDimitry Andric         getCompressionType(arg->getValue(), "--compress-debug-sections");
12680fca6ea1SDimitry Andric   }
1269fe6060f1SDimitry Andric   config->cref = args.hasArg(OPT_cref);
12705ffd83dbSDimitry Andric   config->optimizeBBJumps =
12715ffd83dbSDimitry Andric       args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
12720fca6ea1SDimitry Andric   config->debugNames = args.hasFlag(OPT_debug_names, OPT_no_debug_names, false);
12730b57cec5SDimitry Andric   config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
1274e8d8bef9SDimitry Andric   config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
12750b57cec5SDimitry Andric   config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
12760b57cec5SDimitry Andric   config->disableVerify = args.hasArg(OPT_disable_verify);
12770b57cec5SDimitry Andric   config->discard = getDiscard(args);
12780b57cec5SDimitry Andric   config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
12790b57cec5SDimitry Andric   config->dynamicLinker = getDynamicLinker(args);
12800b57cec5SDimitry Andric   config->ehFrameHdr =
12810b57cec5SDimitry Andric       args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
12820fca6ea1SDimitry Andric   config->emitLLVM = args.hasArg(OPT_lto_emit_llvm);
12830b57cec5SDimitry Andric   config->emitRelocs = args.hasArg(OPT_emit_relocs);
12840b57cec5SDimitry Andric   config->enableNewDtags =
12850b57cec5SDimitry Andric       args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
12860fca6ea1SDimitry Andric   config->enableNonContiguousRegions =
12870fca6ea1SDimitry Andric       args.hasArg(OPT_enable_non_contiguous_regions);
12880b57cec5SDimitry Andric   config->entry = args.getLastArgValue(OPT_entry);
1289e8d8bef9SDimitry Andric 
1290e8d8bef9SDimitry Andric   errorHandler().errorHandlingScript =
1291e8d8bef9SDimitry Andric       args.getLastArgValue(OPT_error_handling_script);
1292e8d8bef9SDimitry Andric 
12930b57cec5SDimitry Andric   config->executeOnly =
12940b57cec5SDimitry Andric       args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
12950b57cec5SDimitry Andric   config->exportDynamic =
129681ad6265SDimitry Andric       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) ||
129781ad6265SDimitry Andric       args.hasArg(OPT_shared);
12980b57cec5SDimitry Andric   config->filterList = args::getStrings(args, OPT_filter);
12990b57cec5SDimitry Andric   config->fini = args.getLastArgValue(OPT_fini, "_fini");
13005ffd83dbSDimitry Andric   config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
13015ffd83dbSDimitry Andric                                      !args.hasArg(OPT_relocatable);
130206c3fb27SDimitry Andric   config->cmseImplib = args.hasArg(OPT_cmse_implib);
130306c3fb27SDimitry Andric   config->cmseInputLib = args.getLastArgValue(OPT_in_implib);
130406c3fb27SDimitry Andric   config->cmseOutputLib = args.getLastArgValue(OPT_out_implib);
13055ffd83dbSDimitry Andric   config->fixCortexA8 =
13065ffd83dbSDimitry Andric       args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
1307e8d8bef9SDimitry Andric   config->fortranCommon =
130881ad6265SDimitry Andric       args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false);
13090b57cec5SDimitry Andric   config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
13100b57cec5SDimitry Andric   config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
13110b57cec5SDimitry Andric   config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
13120b57cec5SDimitry Andric   config->icf = getICF(args);
13130b57cec5SDimitry Andric   config->ignoreDataAddressEquality =
13140b57cec5SDimitry Andric       args.hasArg(OPT_ignore_data_address_equality);
13150b57cec5SDimitry Andric   config->ignoreFunctionAddressEquality =
13160b57cec5SDimitry Andric       args.hasArg(OPT_ignore_function_address_equality);
13170b57cec5SDimitry Andric   config->init = args.getLastArgValue(OPT_init, "_init");
13180b57cec5SDimitry Andric   config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
13190b57cec5SDimitry Andric   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
13200b57cec5SDimitry Andric   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1321349cc55cSDimitry Andric   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1322349cc55cSDimitry Andric                                             OPT_no_lto_pgo_warn_mismatch, true);
13230b57cec5SDimitry Andric   config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
13245ffd83dbSDimitry Andric   config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
13250b57cec5SDimitry Andric   config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
13265ffd83dbSDimitry Andric   config->ltoWholeProgramVisibility =
1327e8d8bef9SDimitry Andric       args.hasFlag(OPT_lto_whole_program_visibility,
1328e8d8bef9SDimitry Andric                    OPT_no_lto_whole_program_visibility, false);
13295f757f3fSDimitry Andric   config->ltoValidateAllVtablesHaveTypeInfos =
13305f757f3fSDimitry Andric       args.hasFlag(OPT_lto_validate_all_vtables_have_type_infos,
13315f757f3fSDimitry Andric                    OPT_no_lto_validate_all_vtables_have_type_infos, false);
13320b57cec5SDimitry Andric   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
133306c3fb27SDimitry Andric   if (config->ltoo > 3)
133406c3fb27SDimitry Andric     error("invalid optimization level for LTO: " + Twine(config->ltoo));
133506c3fb27SDimitry Andric   unsigned ltoCgo =
133606c3fb27SDimitry Andric       args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo));
133706c3fb27SDimitry Andric   if (auto level = CodeGenOpt::getLevel(ltoCgo))
133806c3fb27SDimitry Andric     config->ltoCgo = *level;
133906c3fb27SDimitry Andric   else
134006c3fb27SDimitry Andric     error("invalid codegen optimization level for LTO: " + Twine(ltoCgo));
134185868e8aSDimitry Andric   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
13420b57cec5SDimitry Andric   config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
13430b57cec5SDimitry Andric   config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
13440fca6ea1SDimitry Andric   config->ltoBBAddrMap =
13450fca6ea1SDimitry Andric       args.hasFlag(OPT_lto_basic_block_address_map,
13460fca6ea1SDimitry Andric                    OPT_no_lto_basic_block_address_map, false);
13475ffd83dbSDimitry Andric   config->ltoBasicBlockSections =
1348e8d8bef9SDimitry Andric       args.getLastArgValue(OPT_lto_basic_block_sections);
13495ffd83dbSDimitry Andric   config->ltoUniqueBasicBlockSectionNames =
1350e8d8bef9SDimitry Andric       args.hasFlag(OPT_lto_unique_basic_block_section_names,
1351e8d8bef9SDimitry Andric                    OPT_no_lto_unique_basic_block_section_names, false);
13520b57cec5SDimitry Andric   config->mapFile = args.getLastArgValue(OPT_Map);
13530b57cec5SDimitry Andric   config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
13540b57cec5SDimitry Andric   config->mergeArmExidx =
13550b57cec5SDimitry Andric       args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
1356480093f4SDimitry Andric   config->mmapOutputFile =
1357480093f4SDimitry Andric       args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
13580b57cec5SDimitry Andric   config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
13590b57cec5SDimitry Andric   config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
13600b57cec5SDimitry Andric   config->nostdlib = args.hasArg(OPT_nostdlib);
13610b57cec5SDimitry Andric   config->oFormatBinary = isOutputFormatBinary(args);
13620b57cec5SDimitry Andric   config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
13630b57cec5SDimitry Andric   config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
136481ad6265SDimitry Andric   config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file);
1365e8d8bef9SDimitry Andric 
1366e8d8bef9SDimitry Andric   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1367e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {
1368e8d8bef9SDimitry Andric     auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());
1369e8d8bef9SDimitry Andric     if (!resultOrErr)
1370e8d8bef9SDimitry Andric       error(arg->getSpelling() + ": invalid argument '" + arg->getValue() +
1371e8d8bef9SDimitry Andric             "', only integer or 'auto' is supported");
1372e8d8bef9SDimitry Andric     else
1373e8d8bef9SDimitry Andric       config->optRemarksHotnessThreshold = *resultOrErr;
1374e8d8bef9SDimitry Andric   }
1375e8d8bef9SDimitry Andric 
13760b57cec5SDimitry Andric   config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
13770b57cec5SDimitry Andric   config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
13780b57cec5SDimitry Andric   config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
13790b57cec5SDimitry Andric   config->optimize = args::getInteger(args, OPT_O, 1);
13800b57cec5SDimitry Andric   config->orphanHandling = getOrphanHandling(args);
13810b57cec5SDimitry Andric   config->outputFile = args.getLastArgValue(OPT_o);
138261cfbce3SDimitry Andric   config->packageMetadata = args.getLastArgValue(OPT_package_metadata);
13830b57cec5SDimitry Andric   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
13840b57cec5SDimitry Andric   config->printIcfSections =
13850b57cec5SDimitry Andric       args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
13860b57cec5SDimitry Andric   config->printGcSections =
13870b57cec5SDimitry Andric       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
138806c3fb27SDimitry Andric   config->printMemoryUsage = args.hasArg(OPT_print_memory_usage);
13895ffd83dbSDimitry Andric   config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
13900b57cec5SDimitry Andric   config->printSymbolOrder =
13910b57cec5SDimitry Andric       args.getLastArgValue(OPT_print_symbol_order);
13920fca6ea1SDimitry Andric   config->rejectMismatch = !args.hasArg(OPT_no_warn_mismatch);
1393349cc55cSDimitry Andric   config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true);
139406c3fb27SDimitry Andric   config->relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false);
13950b57cec5SDimitry Andric   config->rpath = getRpath(args);
13960b57cec5SDimitry Andric   config->relocatable = args.hasArg(OPT_relocatable);
13970fca6ea1SDimitry Andric   config->resolveGroups =
13980fca6ea1SDimitry Andric       !args.hasArg(OPT_relocatable) || args.hasArg(OPT_force_group_allocation);
1399753f127fSDimitry Andric 
1400753f127fSDimitry Andric   if (args.hasArg(OPT_save_temps)) {
1401753f127fSDimitry Andric     // --save-temps implies saving all temps.
1402753f127fSDimitry Andric     for (const char *s : saveTempsValues)
1403753f127fSDimitry Andric       config->saveTempsArgs.insert(s);
1404753f127fSDimitry Andric   } else {
1405753f127fSDimitry Andric     for (auto *arg : args.filtered(OPT_save_temps_eq)) {
1406753f127fSDimitry Andric       StringRef s = arg->getValue();
1407753f127fSDimitry Andric       if (llvm::is_contained(saveTempsValues, s))
1408753f127fSDimitry Andric         config->saveTempsArgs.insert(s);
1409753f127fSDimitry Andric       else
1410753f127fSDimitry Andric         error("unknown --save-temps value: " + s);
1411753f127fSDimitry Andric     }
1412753f127fSDimitry Andric   }
1413753f127fSDimitry Andric 
14140b57cec5SDimitry Andric   config->searchPaths = args::getStrings(args, OPT_library_path);
14150b57cec5SDimitry Andric   config->sectionStartMap = getSectionStartMap(args);
14160b57cec5SDimitry Andric   config->shared = args.hasArg(OPT_shared);
14175ffd83dbSDimitry Andric   config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
14180b57cec5SDimitry Andric   config->soName = args.getLastArgValue(OPT_soname);
14190b57cec5SDimitry Andric   config->sortSection = getSortSection(args);
14200b57cec5SDimitry Andric   config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
14210b57cec5SDimitry Andric   config->strip = getStrip(args);
14220b57cec5SDimitry Andric   config->sysroot = args.getLastArgValue(OPT_sysroot);
14230b57cec5SDimitry Andric   config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
14240b57cec5SDimitry Andric   config->target2 = getTarget2(args);
14250b57cec5SDimitry Andric   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
14260b57cec5SDimitry Andric   config->thinLTOCachePolicy = CHECK(
14270b57cec5SDimitry Andric       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
14280b57cec5SDimitry Andric       "--thinlto-cache-policy: invalid cache policy");
142985868e8aSDimitry Andric   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
143081ad6265SDimitry Andric   config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||
143181ad6265SDimitry Andric                                   args.hasArg(OPT_thinlto_index_only) ||
143281ad6265SDimitry Andric                                   args.hasArg(OPT_thinlto_index_only_eq);
143385868e8aSDimitry Andric   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
143485868e8aSDimitry Andric                              args.hasArg(OPT_thinlto_index_only_eq);
143585868e8aSDimitry Andric   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
14360b57cec5SDimitry Andric   config->thinLTOObjectSuffixReplace =
143785868e8aSDimitry Andric       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
143806c3fb27SDimitry Andric   std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,
143906c3fb27SDimitry Andric            config->thinLTOPrefixReplaceNativeObject) =
144006c3fb27SDimitry Andric       getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace_eq);
144181ad6265SDimitry Andric   if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {
144281ad6265SDimitry Andric     if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))
144381ad6265SDimitry Andric       error("--thinlto-object-suffix-replace is not supported with "
144481ad6265SDimitry Andric             "--thinlto-emit-index-files");
144581ad6265SDimitry Andric     else if (args.hasArg(OPT_thinlto_prefix_replace_eq))
144681ad6265SDimitry Andric       error("--thinlto-prefix-replace is not supported with "
144781ad6265SDimitry Andric             "--thinlto-emit-index-files");
144881ad6265SDimitry Andric   }
144906c3fb27SDimitry Andric   if (!config->thinLTOPrefixReplaceNativeObject.empty() &&
145006c3fb27SDimitry Andric       config->thinLTOIndexOnlyArg.empty()) {
145106c3fb27SDimitry Andric     error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "
145206c3fb27SDimitry Andric           "--thinlto-index-only=");
145306c3fb27SDimitry Andric   }
14545ffd83dbSDimitry Andric   config->thinLTOModulesToCompile =
14555ffd83dbSDimitry Andric       args::getStrings(args, OPT_thinlto_single_module_eq);
145681ad6265SDimitry Andric   config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
14575ffd83dbSDimitry Andric   config->timeTraceGranularity =
14585ffd83dbSDimitry Andric       args::getInteger(args, OPT_time_trace_granularity, 500);
14590b57cec5SDimitry Andric   config->trace = args.hasArg(OPT_trace);
14600b57cec5SDimitry Andric   config->undefined = args::getStrings(args, OPT_undefined);
14610b57cec5SDimitry Andric   config->undefinedVersion =
1462bdd1243dSDimitry Andric       args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false);
14635ffd83dbSDimitry Andric   config->unique = args.hasArg(OPT_unique);
14640b57cec5SDimitry Andric   config->useAndroidRelrTags = args.hasFlag(
14650b57cec5SDimitry Andric       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
14660b57cec5SDimitry Andric   config->warnBackrefs =
14670b57cec5SDimitry Andric       args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
14680b57cec5SDimitry Andric   config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
14690b57cec5SDimitry Andric   config->warnSymbolOrdering =
14700b57cec5SDimitry Andric       args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1471349cc55cSDimitry Andric   config->whyExtract = args.getLastArgValue(OPT_why_extract);
14720b57cec5SDimitry Andric   config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
14730b57cec5SDimitry Andric   config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
14745ffd83dbSDimitry Andric   config->zForceBti = hasZOption(args, "force-bti");
1475480093f4SDimitry Andric   config->zForceIbt = hasZOption(args, "force-ibt");
14760fca6ea1SDimitry Andric   config->zGcs = getZGcs(args);
14770b57cec5SDimitry Andric   config->zGlobal = hasZOption(args, "global");
1478480093f4SDimitry Andric   config->zGnustack = getZGnuStack(args);
14790b57cec5SDimitry Andric   config->zHazardplt = hasZOption(args, "hazardplt");
14800b57cec5SDimitry Andric   config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
14810b57cec5SDimitry Andric   config->zInitfirst = hasZOption(args, "initfirst");
14820b57cec5SDimitry Andric   config->zInterpose = hasZOption(args, "interpose");
14830b57cec5SDimitry Andric   config->zKeepTextSectionPrefix = getZFlag(
14840b57cec5SDimitry Andric       args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
14850fca6ea1SDimitry Andric   config->zLrodataAfterBss =
14860fca6ea1SDimitry Andric       getZFlag(args, "lrodata-after-bss", "nolrodata-after-bss", false);
14870b57cec5SDimitry Andric   config->zNodefaultlib = hasZOption(args, "nodefaultlib");
14880b57cec5SDimitry Andric   config->zNodelete = hasZOption(args, "nodelete");
14890b57cec5SDimitry Andric   config->zNodlopen = hasZOption(args, "nodlopen");
14900b57cec5SDimitry Andric   config->zNow = getZFlag(args, "now", "lazy", false);
14910b57cec5SDimitry Andric   config->zOrigin = hasZOption(args, "origin");
14925ffd83dbSDimitry Andric   config->zPacPlt = hasZOption(args, "pac-plt");
14930b57cec5SDimitry Andric   config->zRelro = getZFlag(args, "relro", "norelro", true);
14940b57cec5SDimitry Andric   config->zRetpolineplt = hasZOption(args, "retpolineplt");
14950b57cec5SDimitry Andric   config->zRodynamic = hasZOption(args, "rodynamic");
149685868e8aSDimitry Andric   config->zSeparate = getZSeparate(args);
1497480093f4SDimitry Andric   config->zShstk = hasZOption(args, "shstk");
14980b57cec5SDimitry Andric   config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1499fe6060f1SDimitry Andric   config->zStartStopGC =
1500fe6060f1SDimitry Andric       getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);
15015ffd83dbSDimitry Andric   config->zStartStopVisibility = getZStartStopVisibility(args);
15020b57cec5SDimitry Andric   config->zText = getZFlag(args, "text", "notext", true);
15030b57cec5SDimitry Andric   config->zWxneeded = hasZOption(args, "wxneeded");
1504e8d8bef9SDimitry Andric   setUnresolvedSymbolPolicy(args);
15054824e7fdSDimitry Andric   config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";
1506fe6060f1SDimitry Andric 
1507fe6060f1SDimitry Andric   if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {
1508fe6060f1SDimitry Andric     if (arg->getOption().matches(OPT_eb))
1509fe6060f1SDimitry Andric       config->optEB = true;
1510fe6060f1SDimitry Andric     else
1511fe6060f1SDimitry Andric       config->optEL = true;
1512fe6060f1SDimitry Andric   }
1513fe6060f1SDimitry Andric 
151406c3fb27SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_remap_inputs)) {
151506c3fb27SDimitry Andric     StringRef value(arg->getValue());
151606c3fb27SDimitry Andric     remapInputs(value, arg->getSpelling());
151706c3fb27SDimitry Andric   }
151806c3fb27SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_remap_inputs_file)) {
151906c3fb27SDimitry Andric     StringRef filename(arg->getValue());
152006c3fb27SDimitry Andric     std::optional<MemoryBufferRef> buffer = readFile(filename);
152106c3fb27SDimitry Andric     if (!buffer)
152206c3fb27SDimitry Andric       continue;
152306c3fb27SDimitry Andric     // Parse 'from-glob=to-file' lines, ignoring #-led comments.
152406c3fb27SDimitry Andric     for (auto [lineno, line] : llvm::enumerate(args::getLines(*buffer)))
152506c3fb27SDimitry Andric       if (remapInputs(line, filename + ":" + Twine(lineno + 1)))
152606c3fb27SDimitry Andric         break;
152706c3fb27SDimitry Andric   }
152806c3fb27SDimitry Andric 
1529fe6060f1SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {
1530fe6060f1SDimitry Andric     constexpr StringRef errPrefix = "--shuffle-sections=: ";
1531fe6060f1SDimitry Andric     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
1532fe6060f1SDimitry Andric     if (kv.first.empty() || kv.second.empty()) {
1533fe6060f1SDimitry Andric       error(errPrefix + "expected <section_glob>=<seed>, but got '" +
1534fe6060f1SDimitry Andric             arg->getValue() + "'");
1535fe6060f1SDimitry Andric       continue;
1536fe6060f1SDimitry Andric     }
1537fe6060f1SDimitry Andric     // Signed so that <section_glob>=-1 is allowed.
1538fe6060f1SDimitry Andric     int64_t v;
1539fe6060f1SDimitry Andric     if (!to_integer(kv.second, v))
1540fe6060f1SDimitry Andric       error(errPrefix + "expected an integer, but got '" + kv.second + "'");
1541fe6060f1SDimitry Andric     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1542fe6060f1SDimitry Andric       config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v));
1543fe6060f1SDimitry Andric     else
15445f757f3fSDimitry Andric       error(errPrefix + toString(pat.takeError()) + ": " + kv.first);
1545fe6060f1SDimitry Andric   }
15460b57cec5SDimitry Andric 
15470eae32dcSDimitry Andric   auto reports = {std::make_pair("bti-report", &config->zBtiReport),
15480fca6ea1SDimitry Andric                   std::make_pair("cet-report", &config->zCetReport),
15490fca6ea1SDimitry Andric                   std::make_pair("gcs-report", &config->zGcsReport),
15500fca6ea1SDimitry Andric                   std::make_pair("pauth-report", &config->zPauthReport)};
15510eae32dcSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_z)) {
15520eae32dcSDimitry Andric     std::pair<StringRef, StringRef> option =
15530eae32dcSDimitry Andric         StringRef(arg->getValue()).split('=');
15540eae32dcSDimitry Andric     for (auto reportArg : reports) {
15550eae32dcSDimitry Andric       if (option.first != reportArg.first)
15560eae32dcSDimitry Andric         continue;
15577a6dacacSDimitry Andric       arg->claim();
15580eae32dcSDimitry Andric       if (!isValidReportString(option.second)) {
15590eae32dcSDimitry Andric         error(Twine("-z ") + reportArg.first + "= parameter " + option.second +
15600eae32dcSDimitry Andric               " is not recognized");
15610eae32dcSDimitry Andric         continue;
15620eae32dcSDimitry Andric       }
15630eae32dcSDimitry Andric       *reportArg.second = option.second;
15640eae32dcSDimitry Andric     }
15650eae32dcSDimitry Andric   }
15660eae32dcSDimitry Andric 
15670fca6ea1SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_compress_sections)) {
15680fca6ea1SDimitry Andric     SmallVector<StringRef, 0> fields;
15690fca6ea1SDimitry Andric     StringRef(arg->getValue()).split(fields, '=');
15700fca6ea1SDimitry Andric     if (fields.size() != 2 || fields[1].empty()) {
15710fca6ea1SDimitry Andric       error(arg->getSpelling() +
15720fca6ea1SDimitry Andric             ": parse error, not 'section-glob=[none|zlib|zstd]'");
15730fca6ea1SDimitry Andric       continue;
15740fca6ea1SDimitry Andric     }
15750fca6ea1SDimitry Andric     auto [typeStr, levelStr] = fields[1].split(':');
15760fca6ea1SDimitry Andric     auto type = getCompressionType(typeStr, arg->getSpelling());
15770fca6ea1SDimitry Andric     unsigned level = 0;
15780fca6ea1SDimitry Andric     if (fields[1].size() != typeStr.size() &&
15790fca6ea1SDimitry Andric         !llvm::to_integer(levelStr, level)) {
15800fca6ea1SDimitry Andric       error(arg->getSpelling() +
15810fca6ea1SDimitry Andric             ": expected a non-negative integer compression level, but got '" +
15820fca6ea1SDimitry Andric             levelStr + "'");
15830fca6ea1SDimitry Andric     }
15840fca6ea1SDimitry Andric     if (Expected<GlobPattern> pat = GlobPattern::create(fields[0])) {
15850fca6ea1SDimitry Andric       config->compressSections.emplace_back(std::move(*pat), type, level);
15860fca6ea1SDimitry Andric     } else {
15870fca6ea1SDimitry Andric       error(arg->getSpelling() + ": " + toString(pat.takeError()));
15880fca6ea1SDimitry Andric       continue;
15890fca6ea1SDimitry Andric     }
15900fca6ea1SDimitry Andric   }
15910fca6ea1SDimitry Andric 
15925ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_z)) {
15935ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> option =
15945ffd83dbSDimitry Andric         StringRef(arg->getValue()).split('=');
15955ffd83dbSDimitry Andric     if (option.first != "dead-reloc-in-nonalloc")
15965ffd83dbSDimitry Andric       continue;
15977a6dacacSDimitry Andric     arg->claim();
15985ffd83dbSDimitry Andric     constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
15995ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> kv = option.second.split('=');
16005ffd83dbSDimitry Andric     if (kv.first.empty() || kv.second.empty()) {
16015ffd83dbSDimitry Andric       error(errPrefix + "expected <section_glob>=<value>");
16025ffd83dbSDimitry Andric       continue;
16035ffd83dbSDimitry Andric     }
16045ffd83dbSDimitry Andric     uint64_t v;
16055ffd83dbSDimitry Andric     if (!to_integer(kv.second, v))
16065ffd83dbSDimitry Andric       error(errPrefix + "expected a non-negative integer, but got '" +
16075ffd83dbSDimitry Andric             kv.second + "'");
16085ffd83dbSDimitry Andric     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
16095ffd83dbSDimitry Andric       config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
16105ffd83dbSDimitry Andric     else
16115f757f3fSDimitry Andric       error(errPrefix + toString(pat.takeError()) + ": " + kv.first);
16125ffd83dbSDimitry Andric   }
16135ffd83dbSDimitry Andric 
1614e8d8bef9SDimitry Andric   cl::ResetAllOptionOccurrences();
1615e8d8bef9SDimitry Andric 
16160b57cec5SDimitry Andric   // Parse LTO options.
16170b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
161804eeddc0SDimitry Andric     parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
16190b57cec5SDimitry Andric                      arg->getSpelling());
16200b57cec5SDimitry Andric 
16215ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
16225ffd83dbSDimitry Andric     parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
16235ffd83dbSDimitry Andric 
16245ffd83dbSDimitry Andric   // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1625f3fd488fSDimitry Andric   // relative path. Just ignore. If not ended with "lto-wrapper" (or
1626f3fd488fSDimitry Andric   // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
16275ffd83dbSDimitry Andric   // unsupported LLVMgold.so option and error.
1628f3fd488fSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) {
1629f3fd488fSDimitry Andric     StringRef v(arg->getValue());
163006c3fb27SDimitry Andric     if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe"))
16315ffd83dbSDimitry Andric       error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
16325ffd83dbSDimitry Andric             "'");
1633f3fd488fSDimitry Andric   }
16340b57cec5SDimitry Andric 
163581ad6265SDimitry Andric   config->passPlugins = args::getStrings(args, OPT_load_pass_plugins);
163681ad6265SDimitry Andric 
16370b57cec5SDimitry Andric   // Parse -mllvm options.
1638bdd1243dSDimitry Andric   for (const auto *arg : args.filtered(OPT_mllvm)) {
16390b57cec5SDimitry Andric     parseClangOption(arg->getValue(), arg->getSpelling());
1640bdd1243dSDimitry Andric     config->mllvmOpts.emplace_back(arg->getValue());
1641bdd1243dSDimitry Andric   }
16420b57cec5SDimitry Andric 
164306c3fb27SDimitry Andric   config->ltoKind = LtoKind::Default;
164406c3fb27SDimitry Andric   if (auto *arg = args.getLastArg(OPT_lto)) {
164506c3fb27SDimitry Andric     StringRef s = arg->getValue();
164606c3fb27SDimitry Andric     if (s == "thin")
164706c3fb27SDimitry Andric       config->ltoKind = LtoKind::UnifiedThin;
164806c3fb27SDimitry Andric     else if (s == "full")
164906c3fb27SDimitry Andric       config->ltoKind = LtoKind::UnifiedRegular;
165006c3fb27SDimitry Andric     else if (s == "default")
165106c3fb27SDimitry Andric       config->ltoKind = LtoKind::Default;
165206c3fb27SDimitry Andric     else
165306c3fb27SDimitry Andric       error("unknown LTO mode: " + s);
165406c3fb27SDimitry Andric   }
165506c3fb27SDimitry Andric 
16565ffd83dbSDimitry Andric   // --threads= takes a positive integer and provides the default value for
165706c3fb27SDimitry Andric   // --thinlto-jobs=. If unspecified, cap the number of threads since
165806c3fb27SDimitry Andric   // overhead outweighs optimization for used parallel algorithms for the
165906c3fb27SDimitry Andric   // non-LTO parts.
16605ffd83dbSDimitry Andric   if (auto *arg = args.getLastArg(OPT_threads)) {
16615ffd83dbSDimitry Andric     StringRef v(arg->getValue());
16625ffd83dbSDimitry Andric     unsigned threads = 0;
16635ffd83dbSDimitry Andric     if (!llvm::to_integer(v, threads, 0) || threads == 0)
16645ffd83dbSDimitry Andric       error(arg->getSpelling() + ": expected a positive integer, but got '" +
16655ffd83dbSDimitry Andric             arg->getValue() + "'");
16665ffd83dbSDimitry Andric     parallel::strategy = hardware_concurrency(threads);
16675ffd83dbSDimitry Andric     config->thinLTOJobs = v;
166806c3fb27SDimitry Andric   } else if (parallel::strategy.compute_thread_count() > 16) {
166906c3fb27SDimitry Andric     log("set maximum concurrency to 16, specify --threads= to change");
167006c3fb27SDimitry Andric     parallel::strategy = hardware_concurrency(16);
16715ffd83dbSDimitry Andric   }
1672bdd1243dSDimitry Andric   if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
16735ffd83dbSDimitry Andric     config->thinLTOJobs = arg->getValue();
1674bdd1243dSDimitry Andric   config->threadCount = parallel::strategy.compute_thread_count();
16755ffd83dbSDimitry Andric 
16760b57cec5SDimitry Andric   if (config->ltoPartitions == 0)
16770b57cec5SDimitry Andric     error("--lto-partitions: number of threads must be > 0");
16785ffd83dbSDimitry Andric   if (!get_threadpool_strategy(config->thinLTOJobs))
16795ffd83dbSDimitry Andric     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric   if (config->splitStackAdjustSize < 0)
16820b57cec5SDimitry Andric     error("--split-stack-adjust-size: size must be >= 0");
16830b57cec5SDimitry Andric 
1684480093f4SDimitry Andric   // The text segment is traditionally the first segment, whose address equals
1685480093f4SDimitry Andric   // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1686480093f4SDimitry Andric   // is an old-fashioned option that does not play well with lld's layout.
1687480093f4SDimitry Andric   // Suggest --image-base as a likely alternative.
1688480093f4SDimitry Andric   if (args.hasArg(OPT_Ttext_segment))
1689480093f4SDimitry Andric     error("-Ttext-segment is not supported. Use --image-base if you "
1690480093f4SDimitry Andric           "intend to set the base address");
1691480093f4SDimitry Andric 
16920b57cec5SDimitry Andric   // Parse ELF{32,64}{LE,BE} and CPU type.
16930b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_m)) {
16940b57cec5SDimitry Andric     StringRef s = arg->getValue();
16950b57cec5SDimitry Andric     std::tie(config->ekind, config->emachine, config->osabi) =
16960b57cec5SDimitry Andric         parseEmulation(s);
16970b57cec5SDimitry Andric     config->mipsN32Abi =
169806c3fb27SDimitry Andric         (s.starts_with("elf32btsmipn32") || s.starts_with("elf32ltsmipn32"));
16990b57cec5SDimitry Andric     config->emulation = s;
17000b57cec5SDimitry Andric   }
17010b57cec5SDimitry Andric 
1702349cc55cSDimitry Andric   // Parse --hash-style={sysv,gnu,both}.
17030b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_hash_style)) {
17040b57cec5SDimitry Andric     StringRef s = arg->getValue();
17050b57cec5SDimitry Andric     if (s == "sysv")
17060b57cec5SDimitry Andric       config->sysvHash = true;
17070b57cec5SDimitry Andric     else if (s == "gnu")
17080b57cec5SDimitry Andric       config->gnuHash = true;
17090b57cec5SDimitry Andric     else if (s == "both")
17100b57cec5SDimitry Andric       config->sysvHash = config->gnuHash = true;
17110b57cec5SDimitry Andric     else
1712349cc55cSDimitry Andric       error("unknown --hash-style: " + s);
17130b57cec5SDimitry Andric   }
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   if (args.hasArg(OPT_print_map))
17160b57cec5SDimitry Andric     config->mapFile = "-";
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
17190b57cec5SDimitry Andric   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
17205f757f3fSDimitry Andric   // it. Also disable RELRO for -r.
17215f757f3fSDimitry Andric   if (config->nmagic || config->omagic || config->relocatable)
17220b57cec5SDimitry Andric     config->zRelro = false;
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
17250b57cec5SDimitry Andric 
172681ad6265SDimitry Andric   if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) {
172781ad6265SDimitry Andric     config->relrGlibc = true;
172881ad6265SDimitry Andric     config->relrPackDynRelocs = true;
172981ad6265SDimitry Andric   } else {
17300b57cec5SDimitry Andric     std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
17310b57cec5SDimitry Andric         getPackDynRelocs(args);
173281ad6265SDimitry Andric   }
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
17350b57cec5SDimitry Andric     if (args.hasArg(OPT_call_graph_ordering_file))
17360b57cec5SDimitry Andric       error("--symbol-ordering-file and --call-graph-order-file "
17370b57cec5SDimitry Andric             "may not be used together");
1738bdd1243dSDimitry Andric     if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) {
17390b57cec5SDimitry Andric       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
17400b57cec5SDimitry Andric       // Also need to disable CallGraphProfileSort to prevent
17410b57cec5SDimitry Andric       // LLD order symbols with CGProfile
17425f757f3fSDimitry Andric       config->callGraphProfileSort = CGProfileSortKind::None;
17430b57cec5SDimitry Andric     }
17440b57cec5SDimitry Andric   }
17450b57cec5SDimitry Andric 
174685868e8aSDimitry Andric   assert(config->versionDefinitions.empty());
174785868e8aSDimitry Andric   config->versionDefinitions.push_back(
17486e75b2fbSDimitry Andric       {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});
17496e75b2fbSDimitry Andric   config->versionDefinitions.push_back(
17506e75b2fbSDimitry Andric       {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});
175185868e8aSDimitry Andric 
17520b57cec5SDimitry Andric   // If --retain-symbol-file is used, we'll keep only the symbols listed in
17530b57cec5SDimitry Andric   // the file and discard all others.
17540b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
17556e75b2fbSDimitry Andric     config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
175685868e8aSDimitry Andric         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1757bdd1243dSDimitry Andric     if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
17580b57cec5SDimitry Andric       for (StringRef s : args::getLines(*buffer))
17596e75b2fbSDimitry Andric         config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
176085868e8aSDimitry Andric             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
17610b57cec5SDimitry Andric   }
17620b57cec5SDimitry Andric 
17635ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
17645ffd83dbSDimitry Andric     StringRef pattern(arg->getValue());
17655ffd83dbSDimitry Andric     if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
17665ffd83dbSDimitry Andric       config->warnBackrefsExclude.push_back(std::move(*pat));
17675ffd83dbSDimitry Andric     else
17685f757f3fSDimitry Andric       error(arg->getSpelling() + ": " + toString(pat.takeError()) + ": " +
17695f757f3fSDimitry Andric             pattern);
17705ffd83dbSDimitry Andric   }
17715ffd83dbSDimitry Andric 
1772349cc55cSDimitry Andric   // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1773349cc55cSDimitry Andric   // which should be exported. For -shared, references to matched non-local
1774349cc55cSDimitry Andric   // STV_DEFAULT symbols are not bound to definitions within the shared object,
1775349cc55cSDimitry Andric   // even if other options express a symbolic intention: -Bsymbolic,
17765ffd83dbSDimitry Andric   // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
17770b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
17780b57cec5SDimitry Andric     config->dynamicList.push_back(
17795ffd83dbSDimitry Andric         {arg->getValue(), /*isExternCpp=*/false,
17805ffd83dbSDimitry Andric          /*hasWildcard=*/hasWildcard(arg->getValue())});
17810b57cec5SDimitry Andric 
1782349cc55cSDimitry Andric   // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1783349cc55cSDimitry Andric   // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1784349cc55cSDimitry Andric   // like semantics.
1785349cc55cSDimitry Andric   config->symbolic =
1786349cc55cSDimitry Andric       config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1787349cc55cSDimitry Andric   for (auto *arg :
1788349cc55cSDimitry Andric        args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))
1789bdd1243dSDimitry Andric     if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1790349cc55cSDimitry Andric       readDynamicList(*buffer);
1791349cc55cSDimitry Andric 
17920b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_version_script))
1793bdd1243dSDimitry Andric     if (std::optional<std::string> path = searchScript(arg->getValue())) {
1794bdd1243dSDimitry Andric       if (std::optional<MemoryBufferRef> buffer = readFile(*path))
17950b57cec5SDimitry Andric         readVersionScript(*buffer);
17960b57cec5SDimitry Andric     } else {
17970b57cec5SDimitry Andric       error(Twine("cannot find version script ") + arg->getValue());
17980b57cec5SDimitry Andric     }
17990b57cec5SDimitry Andric }
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric // Some Config members do not directly correspond to any particular
18020b57cec5SDimitry Andric // command line options, but computed based on other Config values.
18030b57cec5SDimitry Andric // This function initialize such members. See Config.h for the details
18040b57cec5SDimitry Andric // of these values.
setConfigs(opt::InputArgList & args)18050b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args) {
18060b57cec5SDimitry Andric   ELFKind k = config->ekind;
18070b57cec5SDimitry Andric   uint16_t m = config->emachine;
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   config->copyRelocs = (config->relocatable || config->emitRelocs);
18100b57cec5SDimitry Andric   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
18110b57cec5SDimitry Andric   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
18120b57cec5SDimitry Andric   config->endianness = config->isLE ? endianness::little : endianness::big;
18130b57cec5SDimitry Andric   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
18140b57cec5SDimitry Andric   config->isPic = config->pie || config->shared;
18150b57cec5SDimitry Andric   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
18160b57cec5SDimitry Andric   config->wordsize = config->is64 ? 8 : 4;
18170b57cec5SDimitry Andric 
18180b57cec5SDimitry Andric   // ELF defines two different ways to store relocation addends as shown below:
18190b57cec5SDimitry Andric   //
18205ffd83dbSDimitry Andric   //  Rel: Addends are stored to the location where relocations are applied. It
18215ffd83dbSDimitry Andric   //  cannot pack the full range of addend values for all relocation types, but
18225ffd83dbSDimitry Andric   //  this only affects relocation types that we don't support emitting as
18235ffd83dbSDimitry Andric   //  dynamic relocations (see getDynRel).
18240b57cec5SDimitry Andric   //  Rela: Addends are stored as part of relocation entry.
18250b57cec5SDimitry Andric   //
18260b57cec5SDimitry Andric   // In other words, Rela makes it easy to read addends at the price of extra
18275ffd83dbSDimitry Andric   // 4 or 8 byte for each relocation entry.
18280b57cec5SDimitry Andric   //
18295ffd83dbSDimitry Andric   // We pick the format for dynamic relocations according to the psABI for each
18305ffd83dbSDimitry Andric   // processor, but a contrary choice can be made if the dynamic loader
18315ffd83dbSDimitry Andric   // supports.
18325ffd83dbSDimitry Andric   config->isRela = getIsRela(args);
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   // If the output uses REL relocations we must store the dynamic relocation
18350b57cec5SDimitry Andric   // addends to the output sections. We also store addends for RELA relocations
18360b57cec5SDimitry Andric   // if --apply-dynamic-relocs is used.
18370b57cec5SDimitry Andric   // We default to not writing the addends when using RELA relocations since
18380b57cec5SDimitry Andric   // any standard conforming tool can find it in r_addend.
18390b57cec5SDimitry Andric   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
18400b57cec5SDimitry Andric                                       OPT_no_apply_dynamic_relocs, false) ||
18410b57cec5SDimitry Andric                          !config->isRela;
1842fe6060f1SDimitry Andric   // Validation of dynamic relocation addends is on by default for assertions
18435f757f3fSDimitry Andric   // builds and disabled otherwise. This check is enabled when writeAddends is
18445f757f3fSDimitry Andric   // true.
1845fe6060f1SDimitry Andric #ifndef NDEBUG
18465f757f3fSDimitry Andric   bool checkDynamicRelocsDefault = true;
1847fe6060f1SDimitry Andric #else
1848fe6060f1SDimitry Andric   bool checkDynamicRelocsDefault = false;
1849fe6060f1SDimitry Andric #endif
1850fe6060f1SDimitry Andric   config->checkDynamicRelocs =
1851fe6060f1SDimitry Andric       args.hasFlag(OPT_check_dynamic_relocations,
1852fe6060f1SDimitry Andric                    OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);
18530b57cec5SDimitry Andric   config->tocOptimize =
18540b57cec5SDimitry Andric       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1855e8d8bef9SDimitry Andric   config->pcRelOptimize =
1856e8d8bef9SDimitry Andric       args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
18570fca6ea1SDimitry Andric 
18580fca6ea1SDimitry Andric   if (!args.hasArg(OPT_hash_style)) {
18590fca6ea1SDimitry Andric     if (config->emachine == EM_MIPS)
18600fca6ea1SDimitry Andric       config->sysvHash = true;
18610fca6ea1SDimitry Andric     else
18620fca6ea1SDimitry Andric       config->sysvHash = config->gnuHash = true;
18630fca6ea1SDimitry Andric   }
18640fca6ea1SDimitry Andric 
18650fca6ea1SDimitry Andric   // Set default entry point and output file if not specified by command line or
18660fca6ea1SDimitry Andric   // linker scripts.
18670fca6ea1SDimitry Andric   config->warnMissingEntry =
18680fca6ea1SDimitry Andric       (!config->entry.empty() || (!config->shared && !config->relocatable));
18690fca6ea1SDimitry Andric   if (config->entry.empty() && !config->relocatable)
18700fca6ea1SDimitry Andric     config->entry = config->emachine == EM_MIPS ? "__start" : "_start";
18710fca6ea1SDimitry Andric   if (config->outputFile.empty())
18720fca6ea1SDimitry Andric     config->outputFile = "a.out";
18730fca6ea1SDimitry Andric 
18740fca6ea1SDimitry Andric   // Fail early if the output file or map file is not writable. If a user has a
18750fca6ea1SDimitry Andric   // long link, e.g. due to a large LTO link, they do not wish to run it and
18760fca6ea1SDimitry Andric   // find that it failed because there was a mistake in their command-line.
18770fca6ea1SDimitry Andric   {
18780fca6ea1SDimitry Andric     llvm::TimeTraceScope timeScope("Create output files");
18790fca6ea1SDimitry Andric     if (auto e = tryCreateFile(config->outputFile))
18800fca6ea1SDimitry Andric       error("cannot open output file " + config->outputFile + ": " +
18810fca6ea1SDimitry Andric             e.message());
18820fca6ea1SDimitry Andric     if (auto e = tryCreateFile(config->mapFile))
18830fca6ea1SDimitry Andric       error("cannot open map file " + config->mapFile + ": " + e.message());
18840fca6ea1SDimitry Andric     if (auto e = tryCreateFile(config->whyExtract))
18850fca6ea1SDimitry Andric       error("cannot open --why-extract= file " + config->whyExtract + ": " +
18860fca6ea1SDimitry Andric             e.message());
18870fca6ea1SDimitry Andric   }
18880b57cec5SDimitry Andric }
18890b57cec5SDimitry Andric 
isFormatBinary(StringRef s)18900b57cec5SDimitry Andric static bool isFormatBinary(StringRef s) {
18910b57cec5SDimitry Andric   if (s == "binary")
18920b57cec5SDimitry Andric     return true;
18930b57cec5SDimitry Andric   if (s == "elf" || s == "default")
18940b57cec5SDimitry Andric     return false;
1895349cc55cSDimitry Andric   error("unknown --format value: " + s +
18960b57cec5SDimitry Andric         " (supported formats: elf, default, binary)");
18970b57cec5SDimitry Andric   return false;
18980b57cec5SDimitry Andric }
18990b57cec5SDimitry Andric 
createFiles(opt::InputArgList & args)19000b57cec5SDimitry Andric void LinkerDriver::createFiles(opt::InputArgList &args) {
1901e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Load input files");
19020b57cec5SDimitry Andric   // For --{push,pop}-state.
19030b57cec5SDimitry Andric   std::vector<std::tuple<bool, bool, bool>> stack;
19040b57cec5SDimitry Andric 
19050fca6ea1SDimitry Andric   // -r implies -Bstatic and has precedence over -Bdynamic.
19060fca6ea1SDimitry Andric   config->isStatic = config->relocatable;
19070fca6ea1SDimitry Andric 
19080b57cec5SDimitry Andric   // Iterate over argv to process input files and positional arguments.
19090fca6ea1SDimitry Andric   std::optional<MemoryBufferRef> defaultScript;
1910e8d8bef9SDimitry Andric   InputFile::isInGroup = false;
19110fca6ea1SDimitry Andric   bool hasInput = false, hasScript = false;
19120b57cec5SDimitry Andric   for (auto *arg : args) {
19130b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
19140b57cec5SDimitry Andric     case OPT_library:
19150b57cec5SDimitry Andric       addLibrary(arg->getValue());
191681ad6265SDimitry Andric       hasInput = true;
19170b57cec5SDimitry Andric       break;
19180b57cec5SDimitry Andric     case OPT_INPUT:
19190b57cec5SDimitry Andric       addFile(arg->getValue(), /*withLOption=*/false);
192081ad6265SDimitry Andric       hasInput = true;
19210b57cec5SDimitry Andric       break;
19220b57cec5SDimitry Andric     case OPT_defsym: {
19230b57cec5SDimitry Andric       StringRef from;
19240b57cec5SDimitry Andric       StringRef to;
19250b57cec5SDimitry Andric       std::tie(from, to) = StringRef(arg->getValue()).split('=');
19260b57cec5SDimitry Andric       if (from.empty() || to.empty())
1927349cc55cSDimitry Andric         error("--defsym: syntax error: " + StringRef(arg->getValue()));
19280b57cec5SDimitry Andric       else
1929349cc55cSDimitry Andric         readDefsym(from, MemoryBufferRef(to, "--defsym"));
19300b57cec5SDimitry Andric       break;
19310b57cec5SDimitry Andric     }
19320b57cec5SDimitry Andric     case OPT_script:
19330fca6ea1SDimitry Andric     case OPT_default_script:
1934bdd1243dSDimitry Andric       if (std::optional<std::string> path = searchScript(arg->getValue())) {
19350fca6ea1SDimitry Andric         if (std::optional<MemoryBufferRef> mb = readFile(*path)) {
19360fca6ea1SDimitry Andric           if (arg->getOption().matches(OPT_default_script)) {
19370fca6ea1SDimitry Andric             defaultScript = mb;
19380fca6ea1SDimitry Andric           } else {
19390b57cec5SDimitry Andric             readLinkerScript(*mb);
19400fca6ea1SDimitry Andric             hasScript = true;
19410fca6ea1SDimitry Andric           }
19420fca6ea1SDimitry Andric         }
19430b57cec5SDimitry Andric         break;
19440b57cec5SDimitry Andric       }
19450b57cec5SDimitry Andric       error(Twine("cannot find linker script ") + arg->getValue());
19460b57cec5SDimitry Andric       break;
19470b57cec5SDimitry Andric     case OPT_as_needed:
19480b57cec5SDimitry Andric       config->asNeeded = true;
19490b57cec5SDimitry Andric       break;
19500b57cec5SDimitry Andric     case OPT_format:
19510b57cec5SDimitry Andric       config->formatBinary = isFormatBinary(arg->getValue());
19520b57cec5SDimitry Andric       break;
19530b57cec5SDimitry Andric     case OPT_no_as_needed:
19540b57cec5SDimitry Andric       config->asNeeded = false;
19550b57cec5SDimitry Andric       break;
19560b57cec5SDimitry Andric     case OPT_Bstatic:
19570b57cec5SDimitry Andric     case OPT_omagic:
19580b57cec5SDimitry Andric     case OPT_nmagic:
19590b57cec5SDimitry Andric       config->isStatic = true;
19600b57cec5SDimitry Andric       break;
19610b57cec5SDimitry Andric     case OPT_Bdynamic:
19620fca6ea1SDimitry Andric       if (!config->relocatable)
19630b57cec5SDimitry Andric         config->isStatic = false;
19640b57cec5SDimitry Andric       break;
19650b57cec5SDimitry Andric     case OPT_whole_archive:
19660b57cec5SDimitry Andric       inWholeArchive = true;
19670b57cec5SDimitry Andric       break;
19680b57cec5SDimitry Andric     case OPT_no_whole_archive:
19690b57cec5SDimitry Andric       inWholeArchive = false;
19700b57cec5SDimitry Andric       break;
19710b57cec5SDimitry Andric     case OPT_just_symbols:
1972bdd1243dSDimitry Andric       if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1973fcaf7f86SDimitry Andric         files.push_back(createObjFile(*mb));
19740b57cec5SDimitry Andric         files.back()->justSymbols = true;
19750b57cec5SDimitry Andric       }
19760b57cec5SDimitry Andric       break;
197706c3fb27SDimitry Andric     case OPT_in_implib:
197806c3fb27SDimitry Andric       if (armCmseImpLib)
197906c3fb27SDimitry Andric         error("multiple CMSE import libraries not supported");
198006c3fb27SDimitry Andric       else if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue()))
198106c3fb27SDimitry Andric         armCmseImpLib = createObjFile(*mb);
198206c3fb27SDimitry Andric       break;
19830b57cec5SDimitry Andric     case OPT_start_group:
19840b57cec5SDimitry Andric       if (InputFile::isInGroup)
19850b57cec5SDimitry Andric         error("nested --start-group");
19860b57cec5SDimitry Andric       InputFile::isInGroup = true;
19870b57cec5SDimitry Andric       break;
19880b57cec5SDimitry Andric     case OPT_end_group:
19890b57cec5SDimitry Andric       if (!InputFile::isInGroup)
19900b57cec5SDimitry Andric         error("stray --end-group");
19910b57cec5SDimitry Andric       InputFile::isInGroup = false;
19920b57cec5SDimitry Andric       ++InputFile::nextGroupId;
19930b57cec5SDimitry Andric       break;
19940b57cec5SDimitry Andric     case OPT_start_lib:
19950b57cec5SDimitry Andric       if (inLib)
19960b57cec5SDimitry Andric         error("nested --start-lib");
19970b57cec5SDimitry Andric       if (InputFile::isInGroup)
19980b57cec5SDimitry Andric         error("may not nest --start-lib in --start-group");
19990b57cec5SDimitry Andric       inLib = true;
20000b57cec5SDimitry Andric       InputFile::isInGroup = true;
20010b57cec5SDimitry Andric       break;
20020b57cec5SDimitry Andric     case OPT_end_lib:
20030b57cec5SDimitry Andric       if (!inLib)
20040b57cec5SDimitry Andric         error("stray --end-lib");
20050b57cec5SDimitry Andric       inLib = false;
20060b57cec5SDimitry Andric       InputFile::isInGroup = false;
20070b57cec5SDimitry Andric       ++InputFile::nextGroupId;
20080b57cec5SDimitry Andric       break;
20090b57cec5SDimitry Andric     case OPT_push_state:
20100b57cec5SDimitry Andric       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
20110b57cec5SDimitry Andric       break;
20120b57cec5SDimitry Andric     case OPT_pop_state:
20130b57cec5SDimitry Andric       if (stack.empty()) {
20140b57cec5SDimitry Andric         error("unbalanced --push-state/--pop-state");
20150b57cec5SDimitry Andric         break;
20160b57cec5SDimitry Andric       }
20170b57cec5SDimitry Andric       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
20180b57cec5SDimitry Andric       stack.pop_back();
20190b57cec5SDimitry Andric       break;
20200b57cec5SDimitry Andric     }
20210b57cec5SDimitry Andric   }
20220b57cec5SDimitry Andric 
20230fca6ea1SDimitry Andric   if (defaultScript && !hasScript)
20240fca6ea1SDimitry Andric     readLinkerScript(*defaultScript);
202581ad6265SDimitry Andric   if (files.empty() && !hasInput && errorCount() == 0)
20260b57cec5SDimitry Andric     error("no input files");
20270b57cec5SDimitry Andric }
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric // If -m <machine_type> was not given, infer it from object files.
inferMachineType()20300b57cec5SDimitry Andric void LinkerDriver::inferMachineType() {
20310b57cec5SDimitry Andric   if (config->ekind != ELFNoneKind)
20320b57cec5SDimitry Andric     return;
20330b57cec5SDimitry Andric 
20340fca6ea1SDimitry Andric   bool inferred = false;
20350b57cec5SDimitry Andric   for (InputFile *f : files) {
20360b57cec5SDimitry Andric     if (f->ekind == ELFNoneKind)
20370b57cec5SDimitry Andric       continue;
20380fca6ea1SDimitry Andric     if (!inferred) {
20390fca6ea1SDimitry Andric       inferred = true;
20400b57cec5SDimitry Andric       config->ekind = f->ekind;
20410b57cec5SDimitry Andric       config->emachine = f->emachine;
20420b57cec5SDimitry Andric       config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
20430fca6ea1SDimitry Andric     }
20440fca6ea1SDimitry Andric     config->osabi = f->osabi;
20450fca6ea1SDimitry Andric     if (f->osabi != ELFOSABI_NONE)
20460b57cec5SDimitry Andric       return;
20470b57cec5SDimitry Andric   }
20480fca6ea1SDimitry Andric   if (!inferred)
20490b57cec5SDimitry Andric     error("target emulation unknown: -m or at least one .o file required");
20500b57cec5SDimitry Andric }
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric // Parse -z max-page-size=<value>. The default value is defined by
20530b57cec5SDimitry Andric // each target.
getMaxPageSize(opt::InputArgList & args)20540b57cec5SDimitry Andric static uint64_t getMaxPageSize(opt::InputArgList &args) {
20550b57cec5SDimitry Andric   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
20560b57cec5SDimitry Andric                                        target->defaultMaxPageSize);
2057972a253aSDimitry Andric   if (!isPowerOf2_64(val)) {
20580b57cec5SDimitry Andric     error("max-page-size: value isn't a power of 2");
2059972a253aSDimitry Andric     return target->defaultMaxPageSize;
2060972a253aSDimitry Andric   }
20610b57cec5SDimitry Andric   if (config->nmagic || config->omagic) {
20620b57cec5SDimitry Andric     if (val != target->defaultMaxPageSize)
20630b57cec5SDimitry Andric       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
20640b57cec5SDimitry Andric     return 1;
20650b57cec5SDimitry Andric   }
20660b57cec5SDimitry Andric   return val;
20670b57cec5SDimitry Andric }
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric // Parse -z common-page-size=<value>. The default value is defined by
20700b57cec5SDimitry Andric // each target.
getCommonPageSize(opt::InputArgList & args)20710b57cec5SDimitry Andric static uint64_t getCommonPageSize(opt::InputArgList &args) {
20720b57cec5SDimitry Andric   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
20730b57cec5SDimitry Andric                                        target->defaultCommonPageSize);
2074972a253aSDimitry Andric   if (!isPowerOf2_64(val)) {
20750b57cec5SDimitry Andric     error("common-page-size: value isn't a power of 2");
2076972a253aSDimitry Andric     return target->defaultCommonPageSize;
2077972a253aSDimitry Andric   }
20780b57cec5SDimitry Andric   if (config->nmagic || config->omagic) {
20790b57cec5SDimitry Andric     if (val != target->defaultCommonPageSize)
20800b57cec5SDimitry Andric       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
20810b57cec5SDimitry Andric     return 1;
20820b57cec5SDimitry Andric   }
20830b57cec5SDimitry Andric   // commonPageSize can't be larger than maxPageSize.
20840b57cec5SDimitry Andric   if (val > config->maxPageSize)
20850b57cec5SDimitry Andric     val = config->maxPageSize;
20860b57cec5SDimitry Andric   return val;
20870b57cec5SDimitry Andric }
20880b57cec5SDimitry Andric 
2089349cc55cSDimitry Andric // Parses --image-base option.
getImageBase(opt::InputArgList & args)2090bdd1243dSDimitry Andric static std::optional<uint64_t> getImageBase(opt::InputArgList &args) {
20910b57cec5SDimitry Andric   // Because we are using "Config->maxPageSize" here, this function has to be
20920b57cec5SDimitry Andric   // called after the variable is initialized.
20930b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_image_base);
20940b57cec5SDimitry Andric   if (!arg)
2095bdd1243dSDimitry Andric     return std::nullopt;
20960b57cec5SDimitry Andric 
20970b57cec5SDimitry Andric   StringRef s = arg->getValue();
20980b57cec5SDimitry Andric   uint64_t v;
20990b57cec5SDimitry Andric   if (!to_integer(s, v)) {
2100349cc55cSDimitry Andric     error("--image-base: number expected, but got " + s);
21010b57cec5SDimitry Andric     return 0;
21020b57cec5SDimitry Andric   }
21030b57cec5SDimitry Andric   if ((v % config->maxPageSize) != 0)
2104349cc55cSDimitry Andric     warn("--image-base: address isn't multiple of page size: " + s);
21050b57cec5SDimitry Andric   return v;
21060b57cec5SDimitry Andric }
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric // Parses `--exclude-libs=lib,lib,...`.
21090b57cec5SDimitry Andric // The library names may be delimited by commas or colons.
getExcludeLibs(opt::InputArgList & args)21100b57cec5SDimitry Andric static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
21110b57cec5SDimitry Andric   DenseSet<StringRef> ret;
21120b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_exclude_libs)) {
21130b57cec5SDimitry Andric     StringRef s = arg->getValue();
21140b57cec5SDimitry Andric     for (;;) {
21150b57cec5SDimitry Andric       size_t pos = s.find_first_of(",:");
21160b57cec5SDimitry Andric       if (pos == StringRef::npos)
21170b57cec5SDimitry Andric         break;
21180b57cec5SDimitry Andric       ret.insert(s.substr(0, pos));
21190b57cec5SDimitry Andric       s = s.substr(pos + 1);
21200b57cec5SDimitry Andric     }
21210b57cec5SDimitry Andric     ret.insert(s);
21220b57cec5SDimitry Andric   }
21230b57cec5SDimitry Andric   return ret;
21240b57cec5SDimitry Andric }
21250b57cec5SDimitry Andric 
2126349cc55cSDimitry Andric // Handles the --exclude-libs option. If a static library file is specified
2127349cc55cSDimitry Andric // by the --exclude-libs option, all public symbols from the archive become
21280b57cec5SDimitry Andric // private unless otherwise specified by version scripts or something.
21290b57cec5SDimitry Andric // A special library name "ALL" means all archive files.
21300b57cec5SDimitry Andric //
21310b57cec5SDimitry Andric // This is not a popular option, but some programs such as bionic libc use it.
excludeLibs(opt::InputArgList & args)21320b57cec5SDimitry Andric static void excludeLibs(opt::InputArgList &args) {
21330b57cec5SDimitry Andric   DenseSet<StringRef> libs = getExcludeLibs(args);
21340b57cec5SDimitry Andric   bool all = libs.count("ALL");
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric   auto visit = [&](InputFile *file) {
213781ad6265SDimitry Andric     if (file->archiveName.empty() ||
213881ad6265SDimitry Andric         !(all || libs.count(path::filename(file->archiveName))))
213981ad6265SDimitry Andric       return;
214081ad6265SDimitry Andric     ArrayRef<Symbol *> symbols = file->getSymbols();
214181ad6265SDimitry Andric     if (isa<ELFFileBase>(file))
214281ad6265SDimitry Andric       symbols = cast<ELFFileBase>(file)->getGlobalSymbols();
214381ad6265SDimitry Andric     for (Symbol *sym : symbols)
214481ad6265SDimitry Andric       if (!sym->isUndefined() && sym->file == file)
21450b57cec5SDimitry Andric         sym->versionId = VER_NDX_LOCAL;
21460b57cec5SDimitry Andric   };
21470b57cec5SDimitry Andric 
2148bdd1243dSDimitry Andric   for (ELFFileBase *file : ctx.objectFiles)
21490b57cec5SDimitry Andric     visit(file);
21500b57cec5SDimitry Andric 
2151bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.bitcodeFiles)
21520b57cec5SDimitry Andric     visit(file);
21530b57cec5SDimitry Andric }
21540b57cec5SDimitry Andric 
21555ffd83dbSDimitry Andric // Force Sym to be entered in the output.
handleUndefined(Symbol * sym,const char * option)2156349cc55cSDimitry Andric static void handleUndefined(Symbol *sym, const char *option) {
21570b57cec5SDimitry Andric   // Since a symbol may not be used inside the program, LTO may
21580b57cec5SDimitry Andric   // eliminate it. Mark the symbol as "used" to prevent it.
21590b57cec5SDimitry Andric   sym->isUsedInRegularObj = true;
21600b57cec5SDimitry Andric 
2161349cc55cSDimitry Andric   if (!sym->isLazy())
2162349cc55cSDimitry Andric     return;
21634824e7fdSDimitry Andric   sym->extract();
2164349cc55cSDimitry Andric   if (!config->whyExtract.empty())
2165bdd1243dSDimitry Andric     ctx.whyExtractRecords.emplace_back(option, sym->file, *sym);
21660b57cec5SDimitry Andric }
21670b57cec5SDimitry Andric 
2168480093f4SDimitry Andric // As an extension to GNU linkers, lld supports a variant of `-u`
21690b57cec5SDimitry Andric // which accepts wildcard patterns. All symbols that match a given
21700b57cec5SDimitry Andric // pattern are handled as if they were given by `-u`.
handleUndefinedGlob(StringRef arg)21710b57cec5SDimitry Andric static void handleUndefinedGlob(StringRef arg) {
21720b57cec5SDimitry Andric   Expected<GlobPattern> pat = GlobPattern::create(arg);
21730b57cec5SDimitry Andric   if (!pat) {
21745f757f3fSDimitry Andric     error("--undefined-glob: " + toString(pat.takeError()) + ": " + arg);
21750b57cec5SDimitry Andric     return;
21760b57cec5SDimitry Andric   }
21770b57cec5SDimitry Andric 
21784824e7fdSDimitry Andric   // Calling sym->extract() in the loop is not safe because it may add new
21794824e7fdSDimitry Andric   // symbols to the symbol table, invalidating the current iterator.
21801fd87a68SDimitry Andric   SmallVector<Symbol *, 0> syms;
2181bdd1243dSDimitry Andric   for (Symbol *sym : symtab.getSymbols())
218204eeddc0SDimitry Andric     if (!sym->isPlaceholder() && pat->match(sym->getName()))
21830b57cec5SDimitry Andric       syms.push_back(sym);
21840b57cec5SDimitry Andric 
21850b57cec5SDimitry Andric   for (Symbol *sym : syms)
2186349cc55cSDimitry Andric     handleUndefined(sym, "--undefined-glob");
21870b57cec5SDimitry Andric }
21880b57cec5SDimitry Andric 
handleLibcall(StringRef name)21890b57cec5SDimitry Andric static void handleLibcall(StringRef name) {
2190bdd1243dSDimitry Andric   Symbol *sym = symtab.find(name);
21910fca6ea1SDimitry Andric   if (sym && sym->isLazy() && isa<BitcodeFile>(sym->file)) {
21920fca6ea1SDimitry Andric     if (!config->whyExtract.empty())
21930fca6ea1SDimitry Andric       ctx.whyExtractRecords.emplace_back("<libcall>", sym->file, *sym);
21944824e7fdSDimitry Andric     sym->extract();
21950b57cec5SDimitry Andric   }
21960fca6ea1SDimitry Andric }
21970b57cec5SDimitry Andric 
writeArchiveStats()219881ad6265SDimitry Andric static void writeArchiveStats() {
219981ad6265SDimitry Andric   if (config->printArchiveStats.empty())
220081ad6265SDimitry Andric     return;
220181ad6265SDimitry Andric 
220281ad6265SDimitry Andric   std::error_code ec;
220306c3fb27SDimitry Andric   raw_fd_ostream os = ctx.openAuxiliaryFile(config->printArchiveStats, ec);
220481ad6265SDimitry Andric   if (ec) {
220581ad6265SDimitry Andric     error("--print-archive-stats=: cannot open " + config->printArchiveStats +
220681ad6265SDimitry Andric           ": " + ec.message());
220781ad6265SDimitry Andric     return;
220881ad6265SDimitry Andric   }
220981ad6265SDimitry Andric 
221081ad6265SDimitry Andric   os << "members\textracted\tarchive\n";
221181ad6265SDimitry Andric 
221281ad6265SDimitry Andric   SmallVector<StringRef, 0> archives;
221381ad6265SDimitry Andric   DenseMap<CachedHashStringRef, unsigned> all, extracted;
2214bdd1243dSDimitry Andric   for (ELFFileBase *file : ctx.objectFiles)
221581ad6265SDimitry Andric     if (file->archiveName.size())
221681ad6265SDimitry Andric       ++extracted[CachedHashStringRef(file->archiveName)];
2217bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.bitcodeFiles)
221881ad6265SDimitry Andric     if (file->archiveName.size())
221981ad6265SDimitry Andric       ++extracted[CachedHashStringRef(file->archiveName)];
2220bdd1243dSDimitry Andric   for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) {
222181ad6265SDimitry Andric     unsigned &v = extracted[CachedHashString(f.first)];
222281ad6265SDimitry Andric     os << f.second << '\t' << v << '\t' << f.first << '\n';
222381ad6265SDimitry Andric     // If the archive occurs multiple times, other instances have a count of 0.
222481ad6265SDimitry Andric     v = 0;
222581ad6265SDimitry Andric   }
222681ad6265SDimitry Andric }
222781ad6265SDimitry Andric 
writeWhyExtract()222881ad6265SDimitry Andric static void writeWhyExtract() {
222981ad6265SDimitry Andric   if (config->whyExtract.empty())
223081ad6265SDimitry Andric     return;
223181ad6265SDimitry Andric 
223281ad6265SDimitry Andric   std::error_code ec;
223306c3fb27SDimitry Andric   raw_fd_ostream os = ctx.openAuxiliaryFile(config->whyExtract, ec);
223481ad6265SDimitry Andric   if (ec) {
223581ad6265SDimitry Andric     error("cannot open --why-extract= file " + config->whyExtract + ": " +
223681ad6265SDimitry Andric           ec.message());
223781ad6265SDimitry Andric     return;
223881ad6265SDimitry Andric   }
223981ad6265SDimitry Andric 
224081ad6265SDimitry Andric   os << "reference\textracted\tsymbol\n";
2241bdd1243dSDimitry Andric   for (auto &entry : ctx.whyExtractRecords) {
224281ad6265SDimitry Andric     os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t'
224381ad6265SDimitry Andric        << toString(std::get<2>(entry)) << '\n';
224481ad6265SDimitry Andric   }
224581ad6265SDimitry Andric }
224681ad6265SDimitry Andric 
reportBackrefs()224781ad6265SDimitry Andric static void reportBackrefs() {
2248bdd1243dSDimitry Andric   for (auto &ref : ctx.backwardReferences) {
224981ad6265SDimitry Andric     const Symbol &sym = *ref.first;
225081ad6265SDimitry Andric     std::string to = toString(ref.second.second);
225181ad6265SDimitry Andric     // Some libraries have known problems and can cause noise. Filter them out
225281ad6265SDimitry Andric     // with --warn-backrefs-exclude=. The value may look like (for --start-lib)
225381ad6265SDimitry Andric     // *.o or (archive member) *.a(*.o).
225481ad6265SDimitry Andric     bool exclude = false;
225581ad6265SDimitry Andric     for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
225681ad6265SDimitry Andric       if (pat.match(to)) {
225781ad6265SDimitry Andric         exclude = true;
225881ad6265SDimitry Andric         break;
225981ad6265SDimitry Andric       }
226081ad6265SDimitry Andric     if (!exclude)
226181ad6265SDimitry Andric       warn("backward reference detected: " + sym.getName() + " in " +
226281ad6265SDimitry Andric            toString(ref.second.first) + " refers to " + to);
226381ad6265SDimitry Andric   }
226481ad6265SDimitry Andric }
226581ad6265SDimitry Andric 
2266e8d8bef9SDimitry Andric // Handle --dependency-file=<path>. If that option is given, lld creates a
2267e8d8bef9SDimitry Andric // file at a given path with the following contents:
2268e8d8bef9SDimitry Andric //
2269e8d8bef9SDimitry Andric //   <output-file>: <input-file> ...
2270e8d8bef9SDimitry Andric //
2271e8d8bef9SDimitry Andric //   <input-file>:
2272e8d8bef9SDimitry Andric //
2273e8d8bef9SDimitry Andric // where <output-file> is a pathname of an output file and <input-file>
2274e8d8bef9SDimitry Andric // ... is a list of pathnames of all input files. `make` command can read a
2275e8d8bef9SDimitry Andric // file in the above format and interpret it as a dependency info. We write
2276e8d8bef9SDimitry Andric // phony targets for every <input-file> to avoid an error when that file is
2277e8d8bef9SDimitry Andric // removed.
2278e8d8bef9SDimitry Andric //
2279e8d8bef9SDimitry Andric // This option is useful if you want to make your final executable to depend
2280e8d8bef9SDimitry Andric // on all input files including system libraries. Here is why.
2281e8d8bef9SDimitry Andric //
2282e8d8bef9SDimitry Andric // When you write a Makefile, you usually write it so that the final
2283e8d8bef9SDimitry Andric // executable depends on all user-generated object files. Normally, you
2284e8d8bef9SDimitry Andric // don't make your executable to depend on system libraries (such as libc)
2285e8d8bef9SDimitry Andric // because you don't know the exact paths of libraries, even though system
2286e8d8bef9SDimitry Andric // libraries that are linked to your executable statically are technically a
2287e8d8bef9SDimitry Andric // part of your program. By using --dependency-file option, you can make
2288e8d8bef9SDimitry Andric // lld to dump dependency info so that you can maintain exact dependencies
2289e8d8bef9SDimitry Andric // easily.
writeDependencyFile()2290e8d8bef9SDimitry Andric static void writeDependencyFile() {
2291e8d8bef9SDimitry Andric   std::error_code ec;
229206c3fb27SDimitry Andric   raw_fd_ostream os = ctx.openAuxiliaryFile(config->dependencyFile, ec);
2293e8d8bef9SDimitry Andric   if (ec) {
2294e8d8bef9SDimitry Andric     error("cannot open " + config->dependencyFile + ": " + ec.message());
2295e8d8bef9SDimitry Andric     return;
2296e8d8bef9SDimitry Andric   }
2297e8d8bef9SDimitry Andric 
2298e8d8bef9SDimitry Andric   // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
2299e8d8bef9SDimitry Andric   // * A space is escaped by a backslash which itself must be escaped.
2300e8d8bef9SDimitry Andric   // * A hash sign is escaped by a single backslash.
2301e8d8bef9SDimitry Andric   // * $ is escapes as $$.
2302e8d8bef9SDimitry Andric   auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
2303e8d8bef9SDimitry Andric     llvm::SmallString<256> nativePath;
2304e8d8bef9SDimitry Andric     llvm::sys::path::native(filename.str(), nativePath);
2305e8d8bef9SDimitry Andric     llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
2306e8d8bef9SDimitry Andric     for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
2307e8d8bef9SDimitry Andric       if (nativePath[i] == '#') {
2308e8d8bef9SDimitry Andric         os << '\\';
2309e8d8bef9SDimitry Andric       } else if (nativePath[i] == ' ') {
2310e8d8bef9SDimitry Andric         os << '\\';
2311e8d8bef9SDimitry Andric         unsigned j = i;
2312e8d8bef9SDimitry Andric         while (j > 0 && nativePath[--j] == '\\')
2313e8d8bef9SDimitry Andric           os << '\\';
2314e8d8bef9SDimitry Andric       } else if (nativePath[i] == '$') {
2315e8d8bef9SDimitry Andric         os << '$';
2316e8d8bef9SDimitry Andric       }
2317e8d8bef9SDimitry Andric       os << nativePath[i];
2318e8d8bef9SDimitry Andric     }
2319e8d8bef9SDimitry Andric   };
2320e8d8bef9SDimitry Andric 
2321e8d8bef9SDimitry Andric   os << config->outputFile << ":";
2322e8d8bef9SDimitry Andric   for (StringRef path : config->dependencyFiles) {
2323e8d8bef9SDimitry Andric     os << " \\\n ";
2324e8d8bef9SDimitry Andric     printFilename(os, path);
2325e8d8bef9SDimitry Andric   }
2326e8d8bef9SDimitry Andric   os << "\n";
2327e8d8bef9SDimitry Andric 
2328e8d8bef9SDimitry Andric   for (StringRef path : config->dependencyFiles) {
2329e8d8bef9SDimitry Andric     os << "\n";
2330e8d8bef9SDimitry Andric     printFilename(os, path);
2331e8d8bef9SDimitry Andric     os << ":\n";
2332e8d8bef9SDimitry Andric   }
2333e8d8bef9SDimitry Andric }
2334e8d8bef9SDimitry Andric 
23350b57cec5SDimitry Andric // Replaces common symbols with defined symbols reside in .bss sections.
23360b57cec5SDimitry Andric // This function is called after all symbol names are resolved. As a
23370b57cec5SDimitry Andric // result, the passes after the symbol resolution won't see any
23380b57cec5SDimitry Andric // symbols of type CommonSymbol.
replaceCommonSymbols()23390b57cec5SDimitry Andric static void replaceCommonSymbols() {
2340e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Replace common symbols");
2341bdd1243dSDimitry Andric   for (ELFFileBase *file : ctx.objectFiles) {
23420eae32dcSDimitry Andric     if (!file->hasCommonSyms)
23430eae32dcSDimitry Andric       continue;
23440eae32dcSDimitry Andric     for (Symbol *sym : file->getGlobalSymbols()) {
23450b57cec5SDimitry Andric       auto *s = dyn_cast<CommonSymbol>(sym);
23460b57cec5SDimitry Andric       if (!s)
2347480093f4SDimitry Andric         continue;
23480b57cec5SDimitry Andric 
23490b57cec5SDimitry Andric       auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
23500b57cec5SDimitry Andric       bss->file = s->file;
2351bdd1243dSDimitry Andric       ctx.inputSections.push_back(bss);
2352bdd1243dSDimitry Andric       Defined(s->file, StringRef(), s->binding, s->stOther, s->type,
2353bdd1243dSDimitry Andric               /*value=*/0, s->size, bss)
2354bdd1243dSDimitry Andric           .overwrite(*s);
2355480093f4SDimitry Andric     }
23560b57cec5SDimitry Andric   }
23570eae32dcSDimitry Andric }
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric // The section referred to by `s` is considered address-significant. Set the
23600b57cec5SDimitry Andric // keepUnique flag on the section if appropriate.
markAddrsig(Symbol * s)23610b57cec5SDimitry Andric static void markAddrsig(Symbol *s) {
23620b57cec5SDimitry Andric   if (auto *d = dyn_cast_or_null<Defined>(s))
23630b57cec5SDimitry Andric     if (d->section)
23640b57cec5SDimitry Andric       // We don't need to keep text sections unique under --icf=all even if they
23650b57cec5SDimitry Andric       // are address-significant.
23660b57cec5SDimitry Andric       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
23670b57cec5SDimitry Andric         d->section->keepUnique = true;
23680b57cec5SDimitry Andric }
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric // Record sections that define symbols mentioned in --keep-unique <symbol>
23710b57cec5SDimitry Andric // and symbols referred to by address-significance tables. These sections are
23720b57cec5SDimitry Andric // ineligible for ICF.
23730b57cec5SDimitry Andric template <class ELFT>
findKeepUniqueSections(opt::InputArgList & args)23740b57cec5SDimitry Andric static void findKeepUniqueSections(opt::InputArgList &args) {
23750b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_keep_unique)) {
23760b57cec5SDimitry Andric     StringRef name = arg->getValue();
2377bdd1243dSDimitry Andric     auto *d = dyn_cast_or_null<Defined>(symtab.find(name));
23780b57cec5SDimitry Andric     if (!d || !d->section) {
23790b57cec5SDimitry Andric       warn("could not find symbol " + name + " to keep unique");
23800b57cec5SDimitry Andric       continue;
23810b57cec5SDimitry Andric     }
23820b57cec5SDimitry Andric     d->section->keepUnique = true;
23830b57cec5SDimitry Andric   }
23840b57cec5SDimitry Andric 
23850b57cec5SDimitry Andric   // --icf=all --ignore-data-address-equality means that we can ignore
23860b57cec5SDimitry Andric   // the dynsym and address-significance tables entirely.
23870b57cec5SDimitry Andric   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
23880b57cec5SDimitry Andric     return;
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   // Symbols in the dynsym could be address-significant in other executables
23910b57cec5SDimitry Andric   // or DSOs, so we conservatively mark them as address-significant.
2392bdd1243dSDimitry Andric   for (Symbol *sym : symtab.getSymbols())
23930b57cec5SDimitry Andric     if (sym->includeInDynsym())
23940b57cec5SDimitry Andric       markAddrsig(sym);
23950b57cec5SDimitry Andric 
23960b57cec5SDimitry Andric   // Visit the address-significance table in each object file and mark each
23970b57cec5SDimitry Andric   // referenced symbol as address-significant.
2398bdd1243dSDimitry Andric   for (InputFile *f : ctx.objectFiles) {
23990b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(f);
24000b57cec5SDimitry Andric     ArrayRef<Symbol *> syms = obj->getSymbols();
24010b57cec5SDimitry Andric     if (obj->addrsigSec) {
24020b57cec5SDimitry Andric       ArrayRef<uint8_t> contents =
2403e8d8bef9SDimitry Andric           check(obj->getObj().getSectionContents(*obj->addrsigSec));
24040b57cec5SDimitry Andric       const uint8_t *cur = contents.begin();
24050b57cec5SDimitry Andric       while (cur != contents.end()) {
24060b57cec5SDimitry Andric         unsigned size;
24075f757f3fSDimitry Andric         const char *err = nullptr;
24080b57cec5SDimitry Andric         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
24090b57cec5SDimitry Andric         if (err)
24100b57cec5SDimitry Andric           fatal(toString(f) + ": could not decode addrsig section: " + err);
24110b57cec5SDimitry Andric         markAddrsig(syms[symIndex]);
24120b57cec5SDimitry Andric         cur += size;
24130b57cec5SDimitry Andric       }
24140b57cec5SDimitry Andric     } else {
24150b57cec5SDimitry Andric       // If an object file does not have an address-significance table,
24160b57cec5SDimitry Andric       // conservatively mark all of its symbols as address-significant.
24170b57cec5SDimitry Andric       for (Symbol *s : syms)
24180b57cec5SDimitry Andric         markAddrsig(s);
24190b57cec5SDimitry Andric     }
24200b57cec5SDimitry Andric   }
24210b57cec5SDimitry Andric }
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric // This function reads a symbol partition specification section. These sections
24240b57cec5SDimitry Andric // are used to control which partition a symbol is allocated to. See
24250b57cec5SDimitry Andric // https://lld.llvm.org/Partitions.html for more details on partitions.
24260b57cec5SDimitry Andric template <typename ELFT>
readSymbolPartitionSection(InputSectionBase * s)24270b57cec5SDimitry Andric static void readSymbolPartitionSection(InputSectionBase *s) {
24280b57cec5SDimitry Andric   // Read the relocation that refers to the partition's entry point symbol.
24290b57cec5SDimitry Andric   Symbol *sym;
2430349cc55cSDimitry Andric   const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
2431349cc55cSDimitry Andric   if (rels.areRelocsRel())
24320fca6ea1SDimitry Andric     sym = &s->file->getRelocTargetSym(rels.rels[0]);
24330b57cec5SDimitry Andric   else
24340fca6ea1SDimitry Andric     sym = &s->file->getRelocTargetSym(rels.relas[0]);
24350b57cec5SDimitry Andric   if (!isa<Defined>(sym) || !sym->includeInDynsym())
24360b57cec5SDimitry Andric     return;
24370b57cec5SDimitry Andric 
2438bdd1243dSDimitry Andric   StringRef partName = reinterpret_cast<const char *>(s->content().data());
24390b57cec5SDimitry Andric   for (Partition &part : partitions) {
24400b57cec5SDimitry Andric     if (part.name == partName) {
24410b57cec5SDimitry Andric       sym->partition = part.getNumber();
24420b57cec5SDimitry Andric       return;
24430b57cec5SDimitry Andric     }
24440b57cec5SDimitry Andric   }
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric   // Forbid partitions from being used on incompatible targets, and forbid them
24470b57cec5SDimitry Andric   // from being used together with various linker features that assume a single
24480b57cec5SDimitry Andric   // set of output sections.
24490b57cec5SDimitry Andric   if (script->hasSectionsCommand)
24500b57cec5SDimitry Andric     error(toString(s->file) +
24510b57cec5SDimitry Andric           ": partitions cannot be used with the SECTIONS command");
24520b57cec5SDimitry Andric   if (script->hasPhdrsCommands())
24530b57cec5SDimitry Andric     error(toString(s->file) +
24540b57cec5SDimitry Andric           ": partitions cannot be used with the PHDRS command");
24550b57cec5SDimitry Andric   if (!config->sectionStartMap.empty())
24560b57cec5SDimitry Andric     error(toString(s->file) + ": partitions cannot be used with "
24570b57cec5SDimitry Andric                               "--section-start, -Ttext, -Tdata or -Tbss");
24580b57cec5SDimitry Andric   if (config->emachine == EM_MIPS)
24590b57cec5SDimitry Andric     error(toString(s->file) + ": partitions cannot be used on this target");
24600b57cec5SDimitry Andric 
24610b57cec5SDimitry Andric   // Impose a limit of no more than 254 partitions. This limit comes from the
24620b57cec5SDimitry Andric   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
24630b57cec5SDimitry Andric   // the amount of space devoted to the partition number in RankFlags.
24640b57cec5SDimitry Andric   if (partitions.size() == 254)
24650b57cec5SDimitry Andric     fatal("may not have more than 254 partitions");
24660b57cec5SDimitry Andric 
24670b57cec5SDimitry Andric   partitions.emplace_back();
24680b57cec5SDimitry Andric   Partition &newPart = partitions.back();
24690b57cec5SDimitry Andric   newPart.name = partName;
24700b57cec5SDimitry Andric   sym->partition = newPart.getNumber();
24710b57cec5SDimitry Andric }
24720b57cec5SDimitry Andric 
markBuffersAsDontNeed(bool skipLinkedOutput)247304eeddc0SDimitry Andric static void markBuffersAsDontNeed(bool skipLinkedOutput) {
247404eeddc0SDimitry Andric   // With --thinlto-index-only, all buffers are nearly unused from now on
247504eeddc0SDimitry Andric   // (except symbol/section names used by infrequent passes). Mark input file
247604eeddc0SDimitry Andric   // buffers as MADV_DONTNEED so that these pages can be reused by the expensive
247704eeddc0SDimitry Andric   // thin link, saving memory.
247804eeddc0SDimitry Andric   if (skipLinkedOutput) {
2479bdd1243dSDimitry Andric     for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))
248004eeddc0SDimitry Andric       mb.dontNeedIfMmap();
248104eeddc0SDimitry Andric     return;
248204eeddc0SDimitry Andric   }
248304eeddc0SDimitry Andric 
248404eeddc0SDimitry Andric   // Otherwise, just mark MemoryBuffers backing BitcodeFiles.
248504eeddc0SDimitry Andric   DenseSet<const char *> bufs;
2486bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.bitcodeFiles)
248704eeddc0SDimitry Andric     bufs.insert(file->mb.getBufferStart());
2488bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.lazyBitcodeFiles)
248904eeddc0SDimitry Andric     bufs.insert(file->mb.getBufferStart());
2490bdd1243dSDimitry Andric   for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))
249104eeddc0SDimitry Andric     if (bufs.count(mb.getBufferStart()))
249204eeddc0SDimitry Andric       mb.dontNeedIfMmap();
249304eeddc0SDimitry Andric }
249404eeddc0SDimitry Andric 
24950b57cec5SDimitry Andric // This function is where all the optimizations of link-time
24960b57cec5SDimitry Andric // optimization takes place. When LTO is in use, some input files are
24970b57cec5SDimitry Andric // not in native object file format but in the LLVM bitcode format.
24980b57cec5SDimitry Andric // This function compiles bitcode files into a few big native files
24990b57cec5SDimitry Andric // using LLVM functions and replaces bitcode symbols with the results.
25000b57cec5SDimitry Andric // Because all bitcode files that the program consists of are passed to
25010b57cec5SDimitry Andric // the compiler at once, it can do a whole-program optimization.
250204eeddc0SDimitry Andric template <class ELFT>
compileBitcodeFiles(bool skipLinkedOutput)250304eeddc0SDimitry Andric void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) {
25045ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("LTO");
25050b57cec5SDimitry Andric   // Compile bitcode files and replace bitcode symbols.
25060b57cec5SDimitry Andric   lto.reset(new BitcodeCompiler);
2507bdd1243dSDimitry Andric   for (BitcodeFile *file : ctx.bitcodeFiles)
25080b57cec5SDimitry Andric     lto->add(*file);
25090b57cec5SDimitry Andric 
2510bdd1243dSDimitry Andric   if (!ctx.bitcodeFiles.empty())
251104eeddc0SDimitry Andric     markBuffersAsDontNeed(skipLinkedOutput);
251204eeddc0SDimitry Andric 
25130b57cec5SDimitry Andric   for (InputFile *file : lto->compile()) {
25140b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(file);
25150b57cec5SDimitry Andric     obj->parse(/*ignoreComdats=*/true);
25165ffd83dbSDimitry Andric 
25175ffd83dbSDimitry Andric     // Parse '@' in symbol names for non-relocatable output.
25185ffd83dbSDimitry Andric     if (!config->relocatable)
25190b57cec5SDimitry Andric       for (Symbol *sym : obj->getGlobalSymbols())
252004eeddc0SDimitry Andric         if (sym->hasVersionSuffix)
25210b57cec5SDimitry Andric           sym->parseSymbolVersion();
2522bdd1243dSDimitry Andric     ctx.objectFiles.push_back(obj);
25230b57cec5SDimitry Andric   }
25240b57cec5SDimitry Andric }
25250b57cec5SDimitry Andric 
25260b57cec5SDimitry Andric // The --wrap option is a feature to rename symbols so that you can write
2527349cc55cSDimitry Andric // wrappers for existing functions. If you pass `--wrap=foo`, all
2528e8d8bef9SDimitry Andric // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
2529e8d8bef9SDimitry Andric // expected to write `__wrap_foo` function as a wrapper). The original
2530e8d8bef9SDimitry Andric // symbol becomes accessible as `__real_foo`, so you can call that from your
25310b57cec5SDimitry Andric // wrapper.
25320b57cec5SDimitry Andric //
2533349cc55cSDimitry Andric // This data structure is instantiated for each --wrap option.
25340b57cec5SDimitry Andric struct WrappedSymbol {
25350b57cec5SDimitry Andric   Symbol *sym;
25360b57cec5SDimitry Andric   Symbol *real;
25370b57cec5SDimitry Andric   Symbol *wrap;
25380b57cec5SDimitry Andric };
25390b57cec5SDimitry Andric 
2540349cc55cSDimitry Andric // Handles --wrap option.
25410b57cec5SDimitry Andric //
25420b57cec5SDimitry Andric // This function instantiates wrapper symbols. At this point, they seem
25430b57cec5SDimitry Andric // like they are not being used at all, so we explicitly set some flags so
25440b57cec5SDimitry Andric // that LTO won't eliminate them.
addWrappedSymbols(opt::InputArgList & args)25450b57cec5SDimitry Andric static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
25460b57cec5SDimitry Andric   std::vector<WrappedSymbol> v;
25470b57cec5SDimitry Andric   DenseSet<StringRef> seen;
25480b57cec5SDimitry Andric 
25490b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wrap)) {
25500b57cec5SDimitry Andric     StringRef name = arg->getValue();
25510b57cec5SDimitry Andric     if (!seen.insert(name).second)
25520b57cec5SDimitry Andric       continue;
25530b57cec5SDimitry Andric 
2554bdd1243dSDimitry Andric     Symbol *sym = symtab.find(name);
25550b57cec5SDimitry Andric     if (!sym)
25560b57cec5SDimitry Andric       continue;
25570b57cec5SDimitry Andric 
2558fe6060f1SDimitry Andric     Symbol *wrap =
25590fca6ea1SDimitry Andric         symtab.addUnusedUndefined(saver().save("__wrap_" + name), sym->binding);
2560bdd1243dSDimitry Andric 
2561bdd1243dSDimitry Andric     // If __real_ is referenced, pull in the symbol if it is lazy. Do this after
2562bdd1243dSDimitry Andric     // processing __wrap_ as that may have referenced __real_.
2563bdd1243dSDimitry Andric     StringRef realName = saver().save("__real_" + name);
25640fca6ea1SDimitry Andric     if (Symbol *real = symtab.find(realName)) {
25650fca6ea1SDimitry Andric       symtab.addUnusedUndefined(name, sym->binding);
25660fca6ea1SDimitry Andric       // Update sym's binding, which will replace real's later in
25670fca6ea1SDimitry Andric       // SymbolTable::wrap.
25680fca6ea1SDimitry Andric       sym->binding = real->binding;
25690fca6ea1SDimitry Andric     }
2570bdd1243dSDimitry Andric 
25710fca6ea1SDimitry Andric     Symbol *real = symtab.addUnusedUndefined(realName);
25720b57cec5SDimitry Andric     v.push_back({sym, real, wrap});
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric     // We want to tell LTO not to inline symbols to be overwritten
25750b57cec5SDimitry Andric     // because LTO doesn't know the final symbol contents after renaming.
257681ad6265SDimitry Andric     real->scriptDefined = true;
257781ad6265SDimitry Andric     sym->scriptDefined = true;
25780b57cec5SDimitry Andric 
257981ad6265SDimitry Andric     // If a symbol is referenced in any object file, bitcode file or shared
258081ad6265SDimitry Andric     // object, mark its redirection target (foo for __real_foo and __wrap_foo
258181ad6265SDimitry Andric     // for foo) as referenced after redirection, which will be used to tell LTO
258281ad6265SDimitry Andric     // to not eliminate the redirection target. If the object file defining the
258381ad6265SDimitry Andric     // symbol also references it, we cannot easily distinguish the case from
258481ad6265SDimitry Andric     // cases where the symbol is not referenced. Retain the redirection target
258581ad6265SDimitry Andric     // in this case because we choose to wrap symbol references regardless of
258681ad6265SDimitry Andric     // whether the symbol is defined
2587e8d8bef9SDimitry Andric     // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
258881ad6265SDimitry Andric     if (real->referenced || real->isDefined())
258981ad6265SDimitry Andric       sym->referencedAfterWrap = true;
2590e8d8bef9SDimitry Andric     if (sym->referenced || sym->isDefined())
259181ad6265SDimitry Andric       wrap->referencedAfterWrap = true;
25920b57cec5SDimitry Andric   }
25930b57cec5SDimitry Andric   return v;
25940b57cec5SDimitry Andric }
25950b57cec5SDimitry Andric 
combineVersionedSymbol(Symbol & sym,DenseMap<Symbol *,Symbol * > & map)2596bdd1243dSDimitry Andric static void combineVersionedSymbol(Symbol &sym,
2597bdd1243dSDimitry Andric                                    DenseMap<Symbol *, Symbol *> &map) {
2598bdd1243dSDimitry Andric   const char *suffix1 = sym.getVersionSuffix();
2599bdd1243dSDimitry Andric   if (suffix1[0] != '@' || suffix1[1] == '@')
2600bdd1243dSDimitry Andric     return;
2601bdd1243dSDimitry Andric 
2602bdd1243dSDimitry Andric   // Check the existing symbol foo. We have two special cases to handle:
2603bdd1243dSDimitry Andric   //
2604bdd1243dSDimitry Andric   // * There is a definition of foo@v1 and foo@@v1.
2605bdd1243dSDimitry Andric   // * There is a definition of foo@v1 and foo.
2606bdd1243dSDimitry Andric   Defined *sym2 = dyn_cast_or_null<Defined>(symtab.find(sym.getName()));
2607bdd1243dSDimitry Andric   if (!sym2)
2608bdd1243dSDimitry Andric     return;
2609bdd1243dSDimitry Andric   const char *suffix2 = sym2->getVersionSuffix();
2610bdd1243dSDimitry Andric   if (suffix2[0] == '@' && suffix2[1] == '@' &&
2611bdd1243dSDimitry Andric       strcmp(suffix1 + 1, suffix2 + 2) == 0) {
2612bdd1243dSDimitry Andric     // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
2613bdd1243dSDimitry Andric     map.try_emplace(&sym, sym2);
2614bdd1243dSDimitry Andric     // If both foo@v1 and foo@@v1 are defined and non-weak, report a
2615bdd1243dSDimitry Andric     // duplicate definition error.
2616bdd1243dSDimitry Andric     if (sym.isDefined()) {
2617bdd1243dSDimitry Andric       sym2->checkDuplicate(cast<Defined>(sym));
2618bdd1243dSDimitry Andric       sym2->resolve(cast<Defined>(sym));
2619bdd1243dSDimitry Andric     } else if (sym.isUndefined()) {
2620bdd1243dSDimitry Andric       sym2->resolve(cast<Undefined>(sym));
2621bdd1243dSDimitry Andric     } else {
2622bdd1243dSDimitry Andric       sym2->resolve(cast<SharedSymbol>(sym));
2623bdd1243dSDimitry Andric     }
2624bdd1243dSDimitry Andric     // Eliminate foo@v1 from the symbol table.
2625bdd1243dSDimitry Andric     sym.symbolKind = Symbol::PlaceholderKind;
2626bdd1243dSDimitry Andric     sym.isUsedInRegularObj = false;
2627bdd1243dSDimitry Andric   } else if (auto *sym1 = dyn_cast<Defined>(&sym)) {
2628bdd1243dSDimitry Andric     if (sym2->versionId > VER_NDX_GLOBAL
2629bdd1243dSDimitry Andric             ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1
2630bdd1243dSDimitry Andric             : sym1->section == sym2->section && sym1->value == sym2->value) {
2631bdd1243dSDimitry Andric       // Due to an assembler design flaw, if foo is defined, .symver foo,
2632bdd1243dSDimitry Andric       // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2633bdd1243dSDimitry Andric       // different version, GNU ld makes foo@v1 canonical and eliminates
2634bdd1243dSDimitry Andric       // foo. Emulate its behavior, otherwise we would have foo or foo@@v1
2635bdd1243dSDimitry Andric       // beside foo@v1. foo@v1 and foo combining does not apply if they are
2636bdd1243dSDimitry Andric       // not defined in the same place.
2637bdd1243dSDimitry Andric       map.try_emplace(sym2, &sym);
2638bdd1243dSDimitry Andric       sym2->symbolKind = Symbol::PlaceholderKind;
2639bdd1243dSDimitry Andric       sym2->isUsedInRegularObj = false;
2640bdd1243dSDimitry Andric     }
2641bdd1243dSDimitry Andric   }
2642bdd1243dSDimitry Andric }
2643bdd1243dSDimitry Andric 
2644349cc55cSDimitry Andric // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
26450b57cec5SDimitry Andric //
26460b57cec5SDimitry Andric // When this function is executed, only InputFiles and symbol table
26470b57cec5SDimitry Andric // contain pointers to symbol objects. We visit them to replace pointers,
26480b57cec5SDimitry Andric // so that wrapped symbols are swapped as instructed by the command line.
redirectSymbols(ArrayRef<WrappedSymbol> wrapped)2649e8d8bef9SDimitry Andric static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) {
2650e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Redirect symbols");
26510b57cec5SDimitry Andric   DenseMap<Symbol *, Symbol *> map;
26520b57cec5SDimitry Andric   for (const WrappedSymbol &w : wrapped) {
26530b57cec5SDimitry Andric     map[w.sym] = w.wrap;
26540b57cec5SDimitry Andric     map[w.real] = w.sym;
26550b57cec5SDimitry Andric   }
2656e8d8bef9SDimitry Andric 
2657bdd1243dSDimitry Andric   // If there are version definitions (versionDefinitions.size() > 2), enumerate
2658bdd1243dSDimitry Andric   // symbols with a non-default version (foo@v1) and check whether it should be
2659bdd1243dSDimitry Andric   // combined with foo or foo@@v1.
2660bdd1243dSDimitry Andric   if (config->versionDefinitions.size() > 2)
2661bdd1243dSDimitry Andric     for (Symbol *sym : symtab.getSymbols())
2662bdd1243dSDimitry Andric       if (sym->hasVersionSuffix)
2663bdd1243dSDimitry Andric         combineVersionedSymbol(*sym, map);
2664e8d8bef9SDimitry Andric 
2665e8d8bef9SDimitry Andric   if (map.empty())
2666e8d8bef9SDimitry Andric     return;
26670b57cec5SDimitry Andric 
26680b57cec5SDimitry Andric   // Update pointers in input files.
2669bdd1243dSDimitry Andric   parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) {
26700eae32dcSDimitry Andric     for (Symbol *&sym : file->getMutableGlobalSymbols())
26710eae32dcSDimitry Andric       if (Symbol *s = map.lookup(sym))
26720eae32dcSDimitry Andric         sym = s;
26730b57cec5SDimitry Andric   });
26740b57cec5SDimitry Andric 
26750b57cec5SDimitry Andric   // Update pointers in the symbol table.
26760b57cec5SDimitry Andric   for (const WrappedSymbol &w : wrapped)
2677bdd1243dSDimitry Andric     symtab.wrap(w.sym, w.real, w.wrap);
26780b57cec5SDimitry Andric }
26790b57cec5SDimitry Andric 
reportMissingFeature(StringRef config,const Twine & report)26800fca6ea1SDimitry Andric static void reportMissingFeature(StringRef config, const Twine &report) {
26810eae32dcSDimitry Andric   if (config == "error")
26820eae32dcSDimitry Andric     error(report);
26830eae32dcSDimitry Andric   else if (config == "warning")
26840eae32dcSDimitry Andric     warn(report);
26850eae32dcSDimitry Andric }
26860fca6ea1SDimitry Andric 
checkAndReportMissingFeature(StringRef config,uint32_t features,uint32_t mask,const Twine & report)26870fca6ea1SDimitry Andric static void checkAndReportMissingFeature(StringRef config, uint32_t features,
26880fca6ea1SDimitry Andric                                          uint32_t mask, const Twine &report) {
26890fca6ea1SDimitry Andric   if (!(features & mask))
26900fca6ea1SDimitry Andric     reportMissingFeature(config, report);
26910eae32dcSDimitry Andric }
26920eae32dcSDimitry Andric 
2693bdd1243dSDimitry Andric // To enable CET (x86's hardware-assisted control flow enforcement), each
26940b57cec5SDimitry Andric // source file must be compiled with -fcf-protection. Object files compiled
26950b57cec5SDimitry Andric // with the flag contain feature flags indicating that they are compatible
26960b57cec5SDimitry Andric // with CET. We enable the feature only when all object files are compatible
26970b57cec5SDimitry Andric // with CET.
26980b57cec5SDimitry Andric //
26990b57cec5SDimitry Andric // This is also the case with AARCH64's BTI and PAC which use the similar
27000b57cec5SDimitry Andric // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
27010fca6ea1SDimitry Andric //
27020fca6ea1SDimitry Andric // For AArch64 PAuth-enabled object files, the core info of all of them must
27030fca6ea1SDimitry Andric // match. Missing info for some object files with matching info for remaining
27040fca6ea1SDimitry Andric // ones can be allowed (see -z pauth-report).
readSecurityNotes()27050fca6ea1SDimitry Andric static void readSecurityNotes() {
27060b57cec5SDimitry Andric   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
27070b57cec5SDimitry Andric       config->emachine != EM_AARCH64)
27080fca6ea1SDimitry Andric     return;
27090b57cec5SDimitry Andric 
27100fca6ea1SDimitry Andric   config->andFeatures = -1;
27110fca6ea1SDimitry Andric 
27120fca6ea1SDimitry Andric   StringRef referenceFileName;
27130fca6ea1SDimitry Andric   if (config->emachine == EM_AARCH64) {
27140fca6ea1SDimitry Andric     auto it = llvm::find_if(ctx.objectFiles, [](const ELFFileBase *f) {
27150fca6ea1SDimitry Andric       return !f->aarch64PauthAbiCoreInfo.empty();
27160fca6ea1SDimitry Andric     });
27170fca6ea1SDimitry Andric     if (it != ctx.objectFiles.end()) {
27180fca6ea1SDimitry Andric       ctx.aarch64PauthAbiCoreInfo = (*it)->aarch64PauthAbiCoreInfo;
27190fca6ea1SDimitry Andric       referenceFileName = (*it)->getName();
27200fca6ea1SDimitry Andric     }
27210fca6ea1SDimitry Andric   }
27220fca6ea1SDimitry Andric 
2723bdd1243dSDimitry Andric   for (ELFFileBase *f : ctx.objectFiles) {
27241fd87a68SDimitry Andric     uint32_t features = f->andFeatures;
27250eae32dcSDimitry Andric 
27260eae32dcSDimitry Andric     checkAndReportMissingFeature(
27270eae32dcSDimitry Andric         config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI,
27280eae32dcSDimitry Andric         toString(f) + ": -z bti-report: file does not have "
27290eae32dcSDimitry Andric                       "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
27300eae32dcSDimitry Andric 
27310eae32dcSDimitry Andric     checkAndReportMissingFeature(
27320fca6ea1SDimitry Andric         config->zGcsReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_GCS,
27330fca6ea1SDimitry Andric         toString(f) + ": -z gcs-report: file does not have "
27340fca6ea1SDimitry Andric                       "GNU_PROPERTY_AARCH64_FEATURE_1_GCS property");
27350fca6ea1SDimitry Andric 
27360fca6ea1SDimitry Andric     checkAndReportMissingFeature(
27370eae32dcSDimitry Andric         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT,
27380eae32dcSDimitry Andric         toString(f) + ": -z cet-report: file does not have "
27390eae32dcSDimitry Andric                       "GNU_PROPERTY_X86_FEATURE_1_IBT property");
27400eae32dcSDimitry Andric 
27410eae32dcSDimitry Andric     checkAndReportMissingFeature(
27420eae32dcSDimitry Andric         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK,
27430eae32dcSDimitry Andric         toString(f) + ": -z cet-report: file does not have "
27440eae32dcSDimitry Andric                       "GNU_PROPERTY_X86_FEATURE_1_SHSTK property");
27450eae32dcSDimitry Andric 
27465ffd83dbSDimitry Andric     if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
27470eae32dcSDimitry Andric       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
27480eae32dcSDimitry Andric       if (config->zBtiReport == "none")
27495ffd83dbSDimitry Andric         warn(toString(f) + ": -z force-bti: file does not have "
27505ffd83dbSDimitry Andric                            "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2751480093f4SDimitry Andric     } else if (config->zForceIbt &&
2752480093f4SDimitry Andric                !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
27530eae32dcSDimitry Andric       if (config->zCetReport == "none")
2754480093f4SDimitry Andric         warn(toString(f) + ": -z force-ibt: file does not have "
2755480093f4SDimitry Andric                            "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2756480093f4SDimitry Andric       features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
2757480093f4SDimitry Andric     }
27585ffd83dbSDimitry Andric     if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
27595ffd83dbSDimitry Andric       warn(toString(f) + ": -z pac-plt: file does not have "
27605ffd83dbSDimitry Andric                          "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
27615ffd83dbSDimitry Andric       features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
27625ffd83dbSDimitry Andric     }
27630fca6ea1SDimitry Andric     config->andFeatures &= features;
27640fca6ea1SDimitry Andric 
27650fca6ea1SDimitry Andric     if (ctx.aarch64PauthAbiCoreInfo.empty())
27660fca6ea1SDimitry Andric       continue;
27670fca6ea1SDimitry Andric 
27680fca6ea1SDimitry Andric     if (f->aarch64PauthAbiCoreInfo.empty()) {
27690fca6ea1SDimitry Andric       reportMissingFeature(config->zPauthReport,
27700fca6ea1SDimitry Andric                            toString(f) +
27710fca6ea1SDimitry Andric                                ": -z pauth-report: file does not have AArch64 "
27720fca6ea1SDimitry Andric                                "PAuth core info while '" +
27730fca6ea1SDimitry Andric                                referenceFileName + "' has one");
27740fca6ea1SDimitry Andric       continue;
27750fca6ea1SDimitry Andric     }
27760fca6ea1SDimitry Andric 
27770fca6ea1SDimitry Andric     if (ctx.aarch64PauthAbiCoreInfo != f->aarch64PauthAbiCoreInfo)
27780fca6ea1SDimitry Andric       errorOrWarn("incompatible values of AArch64 PAuth core info found\n>>> " +
27790fca6ea1SDimitry Andric                   referenceFileName + ": 0x" +
27800fca6ea1SDimitry Andric                   toHex(ctx.aarch64PauthAbiCoreInfo, /*LowerCase=*/true) +
27810fca6ea1SDimitry Andric                   "\n>>> " + toString(f) + ": 0x" +
27820fca6ea1SDimitry Andric                   toHex(f->aarch64PauthAbiCoreInfo, /*LowerCase=*/true));
27830b57cec5SDimitry Andric   }
27840b57cec5SDimitry Andric 
2785480093f4SDimitry Andric   // Force enable Shadow Stack.
2786480093f4SDimitry Andric   if (config->zShstk)
27870fca6ea1SDimitry Andric     config->andFeatures |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
27880b57cec5SDimitry Andric 
27890fca6ea1SDimitry Andric   // Force enable/disable GCS
27900fca6ea1SDimitry Andric   if (config->zGcs == GcsPolicy::Always)
27910fca6ea1SDimitry Andric     config->andFeatures |= GNU_PROPERTY_AARCH64_FEATURE_1_GCS;
27920fca6ea1SDimitry Andric   else if (config->zGcs == GcsPolicy::Never)
27930fca6ea1SDimitry Andric     config->andFeatures &= ~GNU_PROPERTY_AARCH64_FEATURE_1_GCS;
27940b57cec5SDimitry Andric }
27950b57cec5SDimitry Andric 
initSectionsAndLocalSyms(ELFFileBase * file,bool ignoreComdats)2796bdd1243dSDimitry Andric static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) {
2797bdd1243dSDimitry Andric   switch (file->ekind) {
279881ad6265SDimitry Andric   case ELF32LEKind:
2799bdd1243dSDimitry Andric     cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
280081ad6265SDimitry Andric     break;
280181ad6265SDimitry Andric   case ELF32BEKind:
2802bdd1243dSDimitry Andric     cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
280381ad6265SDimitry Andric     break;
280481ad6265SDimitry Andric   case ELF64LEKind:
2805bdd1243dSDimitry Andric     cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
280681ad6265SDimitry Andric     break;
280781ad6265SDimitry Andric   case ELF64BEKind:
2808bdd1243dSDimitry Andric     cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
280981ad6265SDimitry Andric     break;
281081ad6265SDimitry Andric   default:
281181ad6265SDimitry Andric     llvm_unreachable("");
281281ad6265SDimitry Andric   }
281381ad6265SDimitry Andric }
281481ad6265SDimitry Andric 
postParseObjectFile(ELFFileBase * file)281581ad6265SDimitry Andric static void postParseObjectFile(ELFFileBase *file) {
2816bdd1243dSDimitry Andric   switch (file->ekind) {
281781ad6265SDimitry Andric   case ELF32LEKind:
281881ad6265SDimitry Andric     cast<ObjFile<ELF32LE>>(file)->postParse();
281981ad6265SDimitry Andric     break;
282081ad6265SDimitry Andric   case ELF32BEKind:
282181ad6265SDimitry Andric     cast<ObjFile<ELF32BE>>(file)->postParse();
282281ad6265SDimitry Andric     break;
282381ad6265SDimitry Andric   case ELF64LEKind:
282481ad6265SDimitry Andric     cast<ObjFile<ELF64LE>>(file)->postParse();
282581ad6265SDimitry Andric     break;
282681ad6265SDimitry Andric   case ELF64BEKind:
282781ad6265SDimitry Andric     cast<ObjFile<ELF64BE>>(file)->postParse();
282881ad6265SDimitry Andric     break;
282981ad6265SDimitry Andric   default:
283081ad6265SDimitry Andric     llvm_unreachable("");
283181ad6265SDimitry Andric   }
283281ad6265SDimitry Andric }
283381ad6265SDimitry Andric 
28340b57cec5SDimitry Andric // Do actual linking. Note that when this function is called,
28350b57cec5SDimitry Andric // all linker scripts have already been parsed.
link(opt::InputArgList & args)28360fca6ea1SDimitry Andric template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
28375ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric   // Handle --trace-symbol.
28400b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_trace_symbol))
2841bdd1243dSDimitry Andric     symtab.insert(arg->getValue())->traced = true;
28420b57cec5SDimitry Andric 
28437a6dacacSDimitry Andric   ctx.internalFile = createInternalFile("<internal>");
28447a6dacacSDimitry Andric 
28455ffd83dbSDimitry Andric   // Handle -u/--undefined before input files. If both a.a and b.so define foo,
28464824e7fdSDimitry Andric   // -u foo a.a b.so will extract a.a.
28475ffd83dbSDimitry Andric   for (StringRef name : config->undefined)
28480fca6ea1SDimitry Andric     symtab.addUnusedUndefined(name)->referenced = true;
28495ffd83dbSDimitry Andric 
28500fca6ea1SDimitry Andric   parseFiles(files, armCmseImpLib);
28510b57cec5SDimitry Andric 
28520fca6ea1SDimitry Andric   // Create dynamic sections for dynamic linking and static PIE.
28530fca6ea1SDimitry Andric   config->hasDynSymTab = !ctx.sharedFiles.empty() || config->isPic;
28540b57cec5SDimitry Andric 
28550b57cec5SDimitry Andric   // If an entry symbol is in a static archive, pull out that file now.
2856bdd1243dSDimitry Andric   if (Symbol *sym = symtab.find(config->entry))
2857349cc55cSDimitry Andric     handleUndefined(sym, "--entry");
28580b57cec5SDimitry Andric 
28590b57cec5SDimitry Andric   // Handle the `--undefined-glob <pattern>` options.
28600b57cec5SDimitry Andric   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
28610b57cec5SDimitry Andric     handleUndefinedGlob(pat);
28620b57cec5SDimitry Andric 
28630fca6ea1SDimitry Andric   // After potential archive member extraction involving ENTRY and
28640fca6ea1SDimitry Andric   // -u/--undefined-glob, check whether PROVIDE symbols should be defined (the
28650fca6ea1SDimitry Andric   // RHS may refer to definitions in just extracted object files).
28660fca6ea1SDimitry Andric   script->addScriptReferencedSymbolsToSymTable();
28670fca6ea1SDimitry Andric 
28680fca6ea1SDimitry Andric   // Prevent LTO from removing any definition referenced by -u.
28690fca6ea1SDimitry Andric   for (StringRef name : config->undefined)
28700fca6ea1SDimitry Andric     if (Defined *sym = dyn_cast_or_null<Defined>(symtab.find(name)))
28710fca6ea1SDimitry Andric       sym->isUsedInRegularObj = true;
28720fca6ea1SDimitry Andric 
2873480093f4SDimitry Andric   // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2874bdd1243dSDimitry Andric   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->init)))
2875480093f4SDimitry Andric     sym->isUsedInRegularObj = true;
2876bdd1243dSDimitry Andric   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->fini)))
2877480093f4SDimitry Andric     sym->isUsedInRegularObj = true;
2878480093f4SDimitry Andric 
28790b57cec5SDimitry Andric   // If any of our inputs are bitcode files, the LTO code generator may create
28800b57cec5SDimitry Andric   // references to certain library functions that might not be explicit in the
28810b57cec5SDimitry Andric   // bitcode file's symbol table. If any of those library functions are defined
28820b57cec5SDimitry Andric   // in a bitcode file in an archive member, we need to arrange to use LTO to
28830b57cec5SDimitry Andric   // compile those archive members by adding them to the link beforehand.
28840b57cec5SDimitry Andric   //
28850b57cec5SDimitry Andric   // However, adding all libcall symbols to the link can have undesired
28860b57cec5SDimitry Andric   // consequences. For example, the libgcc implementation of
28870b57cec5SDimitry Andric   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
28880b57cec5SDimitry Andric   // that aborts the program if the Linux kernel does not support 64-bit
28890b57cec5SDimitry Andric   // atomics, which would prevent the program from running even if it does not
28900b57cec5SDimitry Andric   // use 64-bit atomics.
28910b57cec5SDimitry Andric   //
28920b57cec5SDimitry Andric   // Therefore, we only add libcall symbols to the link before LTO if we have
28930b57cec5SDimitry Andric   // to, i.e. if the symbol's definition is in bitcode. Any other required
28940b57cec5SDimitry Andric   // libcall symbols will be added to the link after LTO when we add the LTO
28950b57cec5SDimitry Andric   // object file to the link.
28960fca6ea1SDimitry Andric   if (!ctx.bitcodeFiles.empty()) {
28970fca6ea1SDimitry Andric     llvm::Triple TT(ctx.bitcodeFiles.front()->obj->getTargetTriple());
28980fca6ea1SDimitry Andric     for (auto *s : lto::LTO::getRuntimeLibcallSymbols(TT))
28990b57cec5SDimitry Andric       handleLibcall(s);
29000fca6ea1SDimitry Andric   }
29010b57cec5SDimitry Andric 
290281ad6265SDimitry Andric   // Archive members defining __wrap symbols may be extracted.
290381ad6265SDimitry Andric   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
290481ad6265SDimitry Andric 
290581ad6265SDimitry Andric   // No more lazy bitcode can be extracted at this point. Do post parse work
290681ad6265SDimitry Andric   // like checking duplicate symbols.
2907bdd1243dSDimitry Andric   parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {
2908bdd1243dSDimitry Andric     initSectionsAndLocalSyms(file, /*ignoreComdats=*/false);
2909bdd1243dSDimitry Andric   });
2910bdd1243dSDimitry Andric   parallelForEach(ctx.objectFiles, postParseObjectFile);
2911bdd1243dSDimitry Andric   parallelForEach(ctx.bitcodeFiles,
291281ad6265SDimitry Andric                   [](BitcodeFile *file) { file->postParse(); });
2913bdd1243dSDimitry Andric   for (auto &it : ctx.nonPrevailingSyms) {
291481ad6265SDimitry Andric     Symbol &sym = *it.first;
2915bdd1243dSDimitry Andric     Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type,
2916bdd1243dSDimitry Andric               it.second)
2917bdd1243dSDimitry Andric         .overwrite(sym);
291881ad6265SDimitry Andric     cast<Undefined>(sym).nonPrevailing = true;
291981ad6265SDimitry Andric   }
2920bdd1243dSDimitry Andric   ctx.nonPrevailingSyms.clear();
2921bdd1243dSDimitry Andric   for (const DuplicateSymbol &d : ctx.duplicates)
292281ad6265SDimitry Andric     reportDuplicate(*d.sym, d.file, d.section, d.value);
2923bdd1243dSDimitry Andric   ctx.duplicates.clear();
292481ad6265SDimitry Andric 
29250b57cec5SDimitry Andric   // Return if there were name resolution errors.
29260b57cec5SDimitry Andric   if (errorCount())
29270b57cec5SDimitry Andric     return;
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric   // We want to declare linker script's symbols early,
29300b57cec5SDimitry Andric   // so that we can version them.
29310b57cec5SDimitry Andric   // They also might be exported if referenced by DSOs.
29320b57cec5SDimitry Andric   script->declareSymbols();
29330b57cec5SDimitry Andric 
2934e8d8bef9SDimitry Andric   // Handle --exclude-libs. This is before scanVersionScript() due to a
2935e8d8bef9SDimitry Andric   // workaround for Android ndk: for a defined versioned symbol in an archive
2936e8d8bef9SDimitry Andric   // without a version node in the version script, Android does not expect a
2937e8d8bef9SDimitry Andric   // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2938e8d8bef9SDimitry Andric   // GNU ld errors in this case.
29390b57cec5SDimitry Andric   if (args.hasArg(OPT_exclude_libs))
29400b57cec5SDimitry Andric     excludeLibs(args);
29410b57cec5SDimitry Andric 
29420b57cec5SDimitry Andric   // Create elfHeader early. We need a dummy section in
29430b57cec5SDimitry Andric   // addReservedSymbols to mark the created symbols as not absolute.
29440b57cec5SDimitry Andric   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric   // We need to create some reserved symbols such as _end. Create them.
29470b57cec5SDimitry Andric   if (!config->relocatable)
29480b57cec5SDimitry Andric     addReservedSymbols();
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   // Apply version scripts.
29510b57cec5SDimitry Andric   //
29520b57cec5SDimitry Andric   // For a relocatable output, version scripts don't make sense, and
29530b57cec5SDimitry Andric   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
29540b57cec5SDimitry Andric   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2955e8d8bef9SDimitry Andric   if (!config->relocatable) {
2956e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Process symbol versions");
2957bdd1243dSDimitry Andric     symtab.scanVersionScript();
2958e8d8bef9SDimitry Andric   }
29590b57cec5SDimitry Andric 
296004eeddc0SDimitry Andric   // Skip the normal linked output if some LTO options are specified.
296104eeddc0SDimitry Andric   //
296204eeddc0SDimitry Andric   // For --thinlto-index-only, index file creation is performed in
296304eeddc0SDimitry Andric   // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and
296404eeddc0SDimitry Andric   // --plugin-opt=emit-asm create output files in bitcode or assembly code,
296504eeddc0SDimitry Andric   // respectively. When only certain thinLTO modules are specified for
296604eeddc0SDimitry Andric   // compilation, the intermediate object file are the expected output.
296704eeddc0SDimitry Andric   const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM ||
296804eeddc0SDimitry Andric                                 config->ltoEmitAsm ||
296904eeddc0SDimitry Andric                                 !config->thinLTOModulesToCompile.empty();
297004eeddc0SDimitry Andric 
29715f757f3fSDimitry Andric   // Handle --lto-validate-all-vtables-have-type-infos.
29725f757f3fSDimitry Andric   if (config->ltoValidateAllVtablesHaveTypeInfos)
29730fca6ea1SDimitry Andric     ltoValidateAllVtablesHaveTypeInfos<ELFT>(args);
29745f757f3fSDimitry Andric 
29750b57cec5SDimitry Andric   // Do link-time optimization if given files are LLVM bitcode files.
29760b57cec5SDimitry Andric   // This compiles bitcode files into real object files.
29770b57cec5SDimitry Andric   //
29780b57cec5SDimitry Andric   // With this the symbol table should be complete. After this, no new names
29790b57cec5SDimitry Andric   // except a few linker-synthesized ones will be added to the symbol table.
2980bdd1243dSDimitry Andric   const size_t numObjsBeforeLTO = ctx.objectFiles.size();
29810fca6ea1SDimitry Andric   const size_t numInputFilesBeforeLTO = ctx.driver.files.size();
29820fca6ea1SDimitry Andric   compileBitcodeFiles<ELFT>(skipLinkedOutput);
298304eeddc0SDimitry Andric 
298481ad6265SDimitry Andric   // Symbol resolution finished. Report backward reference problems,
298581ad6265SDimitry Andric   // --print-archive-stats=, and --why-extract=.
298604eeddc0SDimitry Andric   reportBackrefs();
298781ad6265SDimitry Andric   writeArchiveStats();
298881ad6265SDimitry Andric   writeWhyExtract();
298904eeddc0SDimitry Andric   if (errorCount())
299004eeddc0SDimitry Andric     return;
299104eeddc0SDimitry Andric 
299204eeddc0SDimitry Andric   // Bail out if normal linked output is skipped due to LTO.
299304eeddc0SDimitry Andric   if (skipLinkedOutput)
299404eeddc0SDimitry Andric     return;
29955ffd83dbSDimitry Andric 
299681ad6265SDimitry Andric   // compileBitcodeFiles may have produced lto.tmp object files. After this, no
299781ad6265SDimitry Andric   // more file will be added.
2998bdd1243dSDimitry Andric   auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO);
2999bdd1243dSDimitry Andric   parallelForEach(newObjectFiles, [](ELFFileBase *file) {
3000bdd1243dSDimitry Andric     initSectionsAndLocalSyms(file, /*ignoreComdats=*/true);
3001bdd1243dSDimitry Andric   });
300281ad6265SDimitry Andric   parallelForEach(newObjectFiles, postParseObjectFile);
3003bdd1243dSDimitry Andric   for (const DuplicateSymbol &d : ctx.duplicates)
300481ad6265SDimitry Andric     reportDuplicate(*d.sym, d.file, d.section, d.value);
300581ad6265SDimitry Andric 
30060fca6ea1SDimitry Andric   // ELF dependent libraries may have introduced new input files after LTO has
30070fca6ea1SDimitry Andric   // completed. This is an error if the files haven't already been parsed, since
30080fca6ea1SDimitry Andric   // changing the symbol table could break the semantic assumptions of LTO.
30090fca6ea1SDimitry Andric   auto newInputFiles = ArrayRef(ctx.driver.files).slice(numInputFilesBeforeLTO);
30100fca6ea1SDimitry Andric   if (!newInputFiles.empty()) {
30110fca6ea1SDimitry Andric     DenseSet<StringRef> oldFilenames;
30120fca6ea1SDimitry Andric     for (InputFile *f :
30130fca6ea1SDimitry Andric          ArrayRef(ctx.driver.files).slice(0, numInputFilesBeforeLTO))
30140fca6ea1SDimitry Andric       oldFilenames.insert(f->getName());
30150fca6ea1SDimitry Andric     for (InputFile *newFile : newInputFiles)
30160fca6ea1SDimitry Andric       if (!oldFilenames.contains(newFile->getName()))
30170fca6ea1SDimitry Andric         errorOrWarn("input file '" + newFile->getName() + "' added after LTO");
30180fca6ea1SDimitry Andric   }
30190fca6ea1SDimitry Andric 
3020e8d8bef9SDimitry Andric   // Handle --exclude-libs again because lto.tmp may reference additional
3021e8d8bef9SDimitry Andric   // libcalls symbols defined in an excluded archive. This may override
3022e8d8bef9SDimitry Andric   // versionId set by scanVersionScript().
3023e8d8bef9SDimitry Andric   if (args.hasArg(OPT_exclude_libs))
3024e8d8bef9SDimitry Andric     excludeLibs(args);
3025e8d8bef9SDimitry Andric 
302606c3fb27SDimitry Andric   // Record [__acle_se_<sym>, <sym>] pairs for later processing.
302706c3fb27SDimitry Andric   processArmCmseSymbols();
302806c3fb27SDimitry Andric 
3029349cc55cSDimitry Andric   // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
3030e8d8bef9SDimitry Andric   redirectSymbols(wrapped);
30310b57cec5SDimitry Andric 
303204eeddc0SDimitry Andric   // Replace common symbols with regular symbols.
303304eeddc0SDimitry Andric   replaceCommonSymbols();
303404eeddc0SDimitry Andric 
3035e8d8bef9SDimitry Andric   {
3036e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Aggregate sections");
30370b57cec5SDimitry Andric     // Now that we have a complete list of input files.
30380b57cec5SDimitry Andric     // Beyond this point, no new files are added.
30390b57cec5SDimitry Andric     // Aggregate all input sections into one place.
3040bdd1243dSDimitry Andric     for (InputFile *f : ctx.objectFiles) {
3041bdd1243dSDimitry Andric       for (InputSectionBase *s : f->getSections()) {
3042bdd1243dSDimitry Andric         if (!s || s == &InputSection::discarded)
3043bdd1243dSDimitry Andric           continue;
3044bdd1243dSDimitry Andric         if (LLVM_UNLIKELY(isa<EhInputSection>(s)))
3045bdd1243dSDimitry Andric           ctx.ehInputSections.push_back(cast<EhInputSection>(s));
3046bdd1243dSDimitry Andric         else
3047bdd1243dSDimitry Andric           ctx.inputSections.push_back(s);
3048bdd1243dSDimitry Andric       }
3049bdd1243dSDimitry Andric     }
3050bdd1243dSDimitry Andric     for (BinaryFile *f : ctx.binaryFiles)
30510b57cec5SDimitry Andric       for (InputSectionBase *s : f->getSections())
3052bdd1243dSDimitry Andric         ctx.inputSections.push_back(cast<InputSection>(s));
3053e8d8bef9SDimitry Andric   }
30540b57cec5SDimitry Andric 
3055e8d8bef9SDimitry Andric   {
3056e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Strip sections");
3057bdd1243dSDimitry Andric     if (ctx.hasSympart.load(std::memory_order_relaxed)) {
3058bdd1243dSDimitry Andric       llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
305981ad6265SDimitry Andric         if (s->type != SHT_LLVM_SYMPART)
306081ad6265SDimitry Andric           return false;
30610fca6ea1SDimitry Andric         readSymbolPartitionSection<ELFT>(s);
30620b57cec5SDimitry Andric         return true;
306381ad6265SDimitry Andric       });
30640b57cec5SDimitry Andric     }
30650b57cec5SDimitry Andric     // We do not want to emit debug sections if --strip-all
3066349cc55cSDimitry Andric     // or --strip-debug are given.
306781ad6265SDimitry Andric     if (config->strip != StripPolicy::None) {
3068bdd1243dSDimitry Andric       llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
3069d65cd7a5SDimitry Andric         if (isDebugSection(*s))
3070d65cd7a5SDimitry Andric           return true;
3071d65cd7a5SDimitry Andric         if (auto *isec = dyn_cast<InputSection>(s))
3072d65cd7a5SDimitry Andric           if (InputSectionBase *rel = isec->getRelocatedSection())
3073d65cd7a5SDimitry Andric             if (isDebugSection(*rel))
3074d65cd7a5SDimitry Andric               return true;
3075d65cd7a5SDimitry Andric 
3076d65cd7a5SDimitry Andric         return false;
30770b57cec5SDimitry Andric       });
3078e8d8bef9SDimitry Andric     }
307981ad6265SDimitry Andric   }
3080e8d8bef9SDimitry Andric 
3081e8d8bef9SDimitry Andric   // Since we now have a complete set of input files, we can create
3082e8d8bef9SDimitry Andric   // a .d file to record build dependencies.
3083e8d8bef9SDimitry Andric   if (!config->dependencyFile.empty())
3084e8d8bef9SDimitry Andric     writeDependencyFile();
30850b57cec5SDimitry Andric 
30860b57cec5SDimitry Andric   // Now that the number of partitions is fixed, save a pointer to the main
30870b57cec5SDimitry Andric   // partition.
30880b57cec5SDimitry Andric   mainPart = &partitions[0];
30890b57cec5SDimitry Andric 
30900b57cec5SDimitry Andric   // Read .note.gnu.property sections from input object files which
30910b57cec5SDimitry Andric   // contain a hint to tweak linker's and loader's behaviors.
30920fca6ea1SDimitry Andric   readSecurityNotes();
30930b57cec5SDimitry Andric 
30940b57cec5SDimitry Andric   // The Target instance handles target-specific stuff, such as applying
30950b57cec5SDimitry Andric   // relocations or writing a PLT section. It also contains target-dependent
30960b57cec5SDimitry Andric   // values such as a default image base address.
30970b57cec5SDimitry Andric   target = getTarget();
30980b57cec5SDimitry Andric 
30990b57cec5SDimitry Andric   config->eflags = target->calcEFlags();
31000b57cec5SDimitry Andric   // maxPageSize (sometimes called abi page size) is the maximum page size that
31010b57cec5SDimitry Andric   // the output can be run on. For example if the OS can use 4k or 64k page
31020b57cec5SDimitry Andric   // sizes then maxPageSize must be 64k for the output to be useable on both.
31030b57cec5SDimitry Andric   // All important alignment decisions must use this value.
31040b57cec5SDimitry Andric   config->maxPageSize = getMaxPageSize(args);
31050b57cec5SDimitry Andric   // commonPageSize is the most common page size that the output will be run on.
31060b57cec5SDimitry Andric   // For example if an OS can use 4k or 64k page sizes and 4k is more common
31070b57cec5SDimitry Andric   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
31080b57cec5SDimitry Andric   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
31090b57cec5SDimitry Andric   // is limited to writing trap instructions on the last executable segment.
31100b57cec5SDimitry Andric   config->commonPageSize = getCommonPageSize(args);
31110b57cec5SDimitry Andric 
31120b57cec5SDimitry Andric   config->imageBase = getImageBase(args);
31130b57cec5SDimitry Andric 
311485868e8aSDimitry Andric   // This adds a .comment section containing a version string.
31150b57cec5SDimitry Andric   if (!config->relocatable)
3116bdd1243dSDimitry Andric     ctx.inputSections.push_back(createCommentSection());
31170b57cec5SDimitry Andric 
311885868e8aSDimitry Andric   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
31190fca6ea1SDimitry Andric   splitSections<ELFT>();
312085868e8aSDimitry Andric 
312185868e8aSDimitry Andric   // Garbage collection and removal of shared symbols from unused shared objects.
31220fca6ea1SDimitry Andric   markLive<ELFT>();
312385868e8aSDimitry Andric 
312485868e8aSDimitry Andric   // Make copies of any input sections that need to be copied into each
312585868e8aSDimitry Andric   // partition.
312685868e8aSDimitry Andric   copySectionsIntoPartitions();
312785868e8aSDimitry Andric 
31285f757f3fSDimitry Andric   if (canHaveMemtagGlobals()) {
31295f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Process memory tagged symbols");
31305f757f3fSDimitry Andric     createTaggedSymbols(ctx.objectFiles);
31315f757f3fSDimitry Andric   }
31325f757f3fSDimitry Andric 
313385868e8aSDimitry Andric   // Create synthesized sections such as .got and .plt. This is called before
313485868e8aSDimitry Andric   // processSectionCommands() so that they can be placed by SECTIONS commands.
31350fca6ea1SDimitry Andric   createSyntheticSections<ELFT>();
313685868e8aSDimitry Andric 
313785868e8aSDimitry Andric   // Some input sections that are used for exception handling need to be moved
313885868e8aSDimitry Andric   // into synthetic sections. Do that now so that they aren't assigned to
313985868e8aSDimitry Andric   // output sections in the usual way.
314085868e8aSDimitry Andric   if (!config->relocatable)
314185868e8aSDimitry Andric     combineEhSections();
314285868e8aSDimitry Andric 
3143bdd1243dSDimitry Andric   // Merge .riscv.attributes sections.
3144bdd1243dSDimitry Andric   if (config->emachine == EM_RISCV)
3145bdd1243dSDimitry Andric     mergeRISCVAttributesSections();
3146bdd1243dSDimitry Andric 
3147e8d8bef9SDimitry Andric   {
3148e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Assign sections");
3149e8d8bef9SDimitry Andric 
315085868e8aSDimitry Andric     // Create output sections described by SECTIONS commands.
315185868e8aSDimitry Andric     script->processSectionCommands();
315285868e8aSDimitry Andric 
3153e8d8bef9SDimitry Andric     // Linker scripts control how input sections are assigned to output
3154e8d8bef9SDimitry Andric     // sections. Input sections that were not handled by scripts are called
3155e8d8bef9SDimitry Andric     // "orphans", and they are assigned to output sections by the default rule.
3156e8d8bef9SDimitry Andric     // Process that.
315785868e8aSDimitry Andric     script->addOrphanSections();
3158e8d8bef9SDimitry Andric   }
3159e8d8bef9SDimitry Andric 
3160e8d8bef9SDimitry Andric   {
3161e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Merge/finalize input sections");
316285868e8aSDimitry Andric 
316385868e8aSDimitry Andric     // Migrate InputSectionDescription::sectionBases to sections. This includes
316485868e8aSDimitry Andric     // merging MergeInputSections into a single MergeSyntheticSection. From this
316585868e8aSDimitry Andric     // point onwards InputSectionDescription::sections should be used instead of
316685868e8aSDimitry Andric     // sectionBases.
31674824e7fdSDimitry Andric     for (SectionCommand *cmd : script->sectionCommands)
316881ad6265SDimitry Andric       if (auto *osd = dyn_cast<OutputDesc>(cmd))
31690fca6ea1SDimitry Andric         osd->osec.finalizeInputSections(&script.s);
3170e8d8bef9SDimitry Andric   }
317185868e8aSDimitry Andric 
317285868e8aSDimitry Andric   // Two input sections with different output sections should not be folded.
317385868e8aSDimitry Andric   // ICF runs after processSectionCommands() so that we know the output sections.
31740b57cec5SDimitry Andric   if (config->icf != ICFLevel::None) {
31750fca6ea1SDimitry Andric     findKeepUniqueSections<ELFT>(args);
31760fca6ea1SDimitry Andric     doIcf<ELFT>();
31770b57cec5SDimitry Andric   }
31780b57cec5SDimitry Andric 
31790b57cec5SDimitry Andric   // Read the callgraph now that we know what was gced or icfed
31805f757f3fSDimitry Andric   if (config->callGraphProfileSort != CGProfileSortKind::None) {
31810b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
3182bdd1243dSDimitry Andric       if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
31830b57cec5SDimitry Andric         readCallGraph(*buffer);
31840fca6ea1SDimitry Andric     readCallGraphsFromObjectFiles<ELFT>();
31850b57cec5SDimitry Andric   }
31860b57cec5SDimitry Andric 
31870b57cec5SDimitry Andric   // Write the result to the file.
31880fca6ea1SDimitry Andric   writeResult<ELFT>();
31890b57cec5SDimitry Andric }
3190