xref: /freebsd/contrib/llvm-project/lld/ELF/Driver.cpp (revision 04eeddc0aa8e0a417a16eaf9d7d095207f4a8623)
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
180b57cec5SDimitry Andric // usually explicitly specified by the compiler 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"
300b57cec5SDimitry Andric #include "LinkerScript.h"
310b57cec5SDimitry Andric #include "MarkLive.h"
320b57cec5SDimitry Andric #include "OutputSections.h"
330b57cec5SDimitry Andric #include "ScriptParser.h"
340b57cec5SDimitry Andric #include "SymbolTable.h"
350b57cec5SDimitry Andric #include "Symbols.h"
360b57cec5SDimitry Andric #include "SyntheticSections.h"
370b57cec5SDimitry Andric #include "Target.h"
380b57cec5SDimitry Andric #include "Writer.h"
390b57cec5SDimitry Andric #include "lld/Common/Args.h"
400b57cec5SDimitry Andric #include "lld/Common/Driver.h"
410b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
420b57cec5SDimitry Andric #include "lld/Common/Filesystem.h"
430b57cec5SDimitry Andric #include "lld/Common/Memory.h"
440b57cec5SDimitry Andric #include "lld/Common/Strings.h"
450b57cec5SDimitry Andric #include "lld/Common/TargetOptionsCommandFlags.h"
460b57cec5SDimitry Andric #include "lld/Common/Version.h"
470b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
480b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
490b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
50e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
5185868e8aSDimitry Andric #include "llvm/LTO/LTO.h"
52e8d8bef9SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h"
530b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
540b57cec5SDimitry Andric #include "llvm/Support/Compression.h"
550b57cec5SDimitry Andric #include "llvm/Support/GlobPattern.h"
560b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
575ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h"
580b57cec5SDimitry Andric #include "llvm/Support/Path.h"
590b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h"
600b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
615ffd83dbSDimitry Andric #include "llvm/Support/TimeProfiler.h"
620b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
630b57cec5SDimitry Andric #include <cstdlib>
640b57cec5SDimitry Andric #include <utility>
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric using namespace llvm;
670b57cec5SDimitry Andric using namespace llvm::ELF;
680b57cec5SDimitry Andric using namespace llvm::object;
690b57cec5SDimitry Andric using namespace llvm::sys;
700b57cec5SDimitry Andric using namespace llvm::support;
715ffd83dbSDimitry Andric using namespace lld;
725ffd83dbSDimitry Andric using namespace lld::elf;
730b57cec5SDimitry Andric 
740eae32dcSDimitry Andric std::unique_ptr<Configuration> elf::config;
750eae32dcSDimitry Andric std::unique_ptr<LinkerDriver> elf::driver;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args);
780b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args);
790b57cec5SDimitry Andric 
80*04eeddc0SDimitry Andric bool elf::link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
81*04eeddc0SDimitry Andric                llvm::raw_ostream &stderrOS, bool exitEarly,
82*04eeddc0SDimitry Andric                bool disableOutput) {
83*04eeddc0SDimitry Andric   // This driver-specific context will be freed later by lldMain().
84*04eeddc0SDimitry Andric   auto *ctx = new CommonLinkerContext;
85480093f4SDimitry Andric 
86*04eeddc0SDimitry Andric   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
87*04eeddc0SDimitry Andric   ctx->e.cleanupCallback = []() {
880b57cec5SDimitry Andric     inputSections.clear();
890b57cec5SDimitry Andric     outputSections.clear();
90*04eeddc0SDimitry Andric     memoryBuffers.clear();
915ffd83dbSDimitry Andric     archiveFiles.clear();
920b57cec5SDimitry Andric     binaryFiles.clear();
930b57cec5SDimitry Andric     bitcodeFiles.clear();
940eae32dcSDimitry Andric     lazyBitcodeFiles.clear();
950b57cec5SDimitry Andric     objectFiles.clear();
960b57cec5SDimitry Andric     sharedFiles.clear();
975ffd83dbSDimitry Andric     backwardReferences.clear();
98349cc55cSDimitry Andric     whyExtract.clear();
99*04eeddc0SDimitry Andric     symAux.clear();
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric     tar = nullptr;
102*04eeddc0SDimitry Andric     in.reset();
1030b57cec5SDimitry Andric 
104*04eeddc0SDimitry Andric     partitions.clear();
105*04eeddc0SDimitry Andric     partitions.emplace_back();
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric     SharedFile::vernauxNum = 0;
108e8d8bef9SDimitry Andric   };
109*04eeddc0SDimitry Andric   ctx->e.logName = args::getFilenameWithoutExe(args[0]);
110*04eeddc0SDimitry Andric   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use "
111e8d8bef9SDimitry Andric                                  "-error-limit=0 to see all errors)";
112e8d8bef9SDimitry Andric 
1130eae32dcSDimitry Andric   config = std::make_unique<Configuration>();
1140eae32dcSDimitry Andric   driver = std::make_unique<LinkerDriver>();
1150eae32dcSDimitry Andric   script = std::make_unique<LinkerScript>();
1160eae32dcSDimitry Andric   symtab = std::make_unique<SymbolTable>();
117e8d8bef9SDimitry Andric 
118*04eeddc0SDimitry Andric   partitions.clear();
119*04eeddc0SDimitry Andric   partitions.emplace_back();
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   config->progName = args[0];
1220b57cec5SDimitry Andric 
123e8d8bef9SDimitry Andric   driver->linkerMain(args);
1240b57cec5SDimitry Andric 
125*04eeddc0SDimitry Andric   return errorCount() == 0;
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric // Parses a linker -m option.
1290b57cec5SDimitry Andric static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
1300b57cec5SDimitry Andric   uint8_t osabi = 0;
1310b57cec5SDimitry Andric   StringRef s = emul;
1320b57cec5SDimitry Andric   if (s.endswith("_fbsd")) {
1330b57cec5SDimitry Andric     s = s.drop_back(5);
1340b57cec5SDimitry Andric     osabi = ELFOSABI_FREEBSD;
1350b57cec5SDimitry Andric   }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   std::pair<ELFKind, uint16_t> ret =
1380b57cec5SDimitry Andric       StringSwitch<std::pair<ELFKind, uint16_t>>(s)
139fe6060f1SDimitry Andric           .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
140fe6060f1SDimitry Andric           .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})
1410b57cec5SDimitry Andric           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
1420b57cec5SDimitry Andric           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
1430b57cec5SDimitry Andric           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
1440b57cec5SDimitry Andric           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
1450b57cec5SDimitry Andric           .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
1460b57cec5SDimitry Andric           .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
147e8d8bef9SDimitry Andric           .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})
1480b57cec5SDimitry Andric           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
1490b57cec5SDimitry Andric           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
1500b57cec5SDimitry Andric           .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
1510b57cec5SDimitry Andric           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
1520b57cec5SDimitry Andric           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
1530b57cec5SDimitry Andric           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
1540b57cec5SDimitry Andric           .Case("elf_i386", {ELF32LEKind, EM_386})
1550b57cec5SDimitry Andric           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
1565ffd83dbSDimitry Andric           .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
157e8d8bef9SDimitry Andric           .Case("msp430elf", {ELF32LEKind, EM_MSP430})
1580b57cec5SDimitry Andric           .Default({ELFNoneKind, EM_NONE});
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   if (ret.first == ELFNoneKind)
1610b57cec5SDimitry Andric     error("unknown emulation: " + emul);
162e8d8bef9SDimitry Andric   if (ret.second == EM_MSP430)
163e8d8bef9SDimitry Andric     osabi = ELFOSABI_STANDALONE;
1640b57cec5SDimitry Andric   return std::make_tuple(ret.first, ret.second, osabi);
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric // Returns slices of MB by parsing MB as an archive file.
1680b57cec5SDimitry Andric // Each slice consists of a member file in the archive.
1690b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
1700b57cec5SDimitry Andric     MemoryBufferRef mb) {
1710b57cec5SDimitry Andric   std::unique_ptr<Archive> file =
1720b57cec5SDimitry Andric       CHECK(Archive::create(mb),
1730b57cec5SDimitry Andric             mb.getBufferIdentifier() + ": failed to parse archive");
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
1760b57cec5SDimitry Andric   Error err = Error::success();
1770b57cec5SDimitry Andric   bool addToTar = file->isThin() && tar;
178480093f4SDimitry Andric   for (const Archive::Child &c : file->children(err)) {
1790b57cec5SDimitry Andric     MemoryBufferRef mbref =
1800b57cec5SDimitry Andric         CHECK(c.getMemoryBufferRef(),
1810b57cec5SDimitry Andric               mb.getBufferIdentifier() +
1820b57cec5SDimitry Andric                   ": could not get the buffer for a child of the archive");
1830b57cec5SDimitry Andric     if (addToTar)
1840b57cec5SDimitry Andric       tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
1850b57cec5SDimitry Andric     v.push_back(std::make_pair(mbref, c.getChildOffset()));
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric   if (err)
1880b57cec5SDimitry Andric     fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
1890b57cec5SDimitry Andric           toString(std::move(err)));
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   // Take ownership of memory buffers created for members of thin archives.
1920b57cec5SDimitry Andric   for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
1930b57cec5SDimitry Andric     make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   return v;
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric // Opens a file and create a file object. Path has to be resolved already.
1990b57cec5SDimitry Andric void LinkerDriver::addFile(StringRef path, bool withLOption) {
2000b57cec5SDimitry Andric   using namespace sys::fs;
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   Optional<MemoryBufferRef> buffer = readFile(path);
2030b57cec5SDimitry Andric   if (!buffer.hasValue())
2040b57cec5SDimitry Andric     return;
2050b57cec5SDimitry Andric   MemoryBufferRef mbref = *buffer;
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   if (config->formatBinary) {
2080b57cec5SDimitry Andric     files.push_back(make<BinaryFile>(mbref));
2090b57cec5SDimitry Andric     return;
2100b57cec5SDimitry Andric   }
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   switch (identify_magic(mbref.getBuffer())) {
2130b57cec5SDimitry Andric   case file_magic::unknown:
2140b57cec5SDimitry Andric     readLinkerScript(mbref);
2150b57cec5SDimitry Andric     return;
2160b57cec5SDimitry Andric   case file_magic::archive: {
2170b57cec5SDimitry Andric     if (inWholeArchive) {
2180b57cec5SDimitry Andric       for (const auto &p : getArchiveMembers(mbref))
2190b57cec5SDimitry Andric         files.push_back(createObjectFile(p.first, path, p.second));
2200b57cec5SDimitry Andric       return;
2210b57cec5SDimitry Andric     }
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric     std::unique_ptr<Archive> file =
2240b57cec5SDimitry Andric         CHECK(Archive::create(mbref), path + ": failed to parse archive");
2250b57cec5SDimitry Andric 
226*04eeddc0SDimitry Andric     // If an archive file has no symbol table, it may be intentional (used as a
227*04eeddc0SDimitry Andric     // group of lazy object files where the symbol table is not useful), or the
228*04eeddc0SDimitry Andric     // user is attempting LTO and using a default ar command that doesn't
229*04eeddc0SDimitry Andric     // understand the LLVM bitcode file. Treat the archive as a group of lazy
230*04eeddc0SDimitry Andric     // object files.
2310b57cec5SDimitry Andric     if (!file->isEmpty() && !file->hasSymbolTable()) {
2320b57cec5SDimitry Andric       for (const std::pair<MemoryBufferRef, uint64_t> &p :
233*04eeddc0SDimitry Andric            getArchiveMembers(mbref)) {
234*04eeddc0SDimitry Andric         auto magic = identify_magic(p.first.getBuffer());
235*04eeddc0SDimitry Andric         if (magic == file_magic::bitcode ||
236*04eeddc0SDimitry Andric             magic == file_magic::elf_relocatable)
2370eae32dcSDimitry Andric           files.push_back(createLazyFile(p.first, path, p.second));
238*04eeddc0SDimitry Andric         else
239*04eeddc0SDimitry Andric           error(path + ": archive member '" + p.first.getBufferIdentifier() +
240*04eeddc0SDimitry Andric                 "' is neither ET_REL nor LLVM bitcode");
241*04eeddc0SDimitry Andric       }
2420b57cec5SDimitry Andric       return;
2430b57cec5SDimitry Andric     }
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric     // Handle the regular case.
2460b57cec5SDimitry Andric     files.push_back(make<ArchiveFile>(std::move(file)));
2470b57cec5SDimitry Andric     return;
2480b57cec5SDimitry Andric   }
2490b57cec5SDimitry Andric   case file_magic::elf_shared_object:
2500b57cec5SDimitry Andric     if (config->isStatic || config->relocatable) {
2510b57cec5SDimitry Andric       error("attempted static link of dynamic object " + path);
2520b57cec5SDimitry Andric       return;
2530b57cec5SDimitry Andric     }
2540b57cec5SDimitry Andric 
255349cc55cSDimitry Andric     // Shared objects are identified by soname. soname is (if specified)
256349cc55cSDimitry Andric     // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
257349cc55cSDimitry Andric     // the directory part is ignored. Note that path may be a temporary and
258349cc55cSDimitry Andric     // cannot be stored into SharedFile::soName.
259349cc55cSDimitry Andric     path = mbref.getBufferIdentifier();
2600b57cec5SDimitry Andric     files.push_back(
2610b57cec5SDimitry Andric         make<SharedFile>(mbref, withLOption ? path::filename(path) : path));
2620b57cec5SDimitry Andric     return;
2630b57cec5SDimitry Andric   case file_magic::bitcode:
2640b57cec5SDimitry Andric   case file_magic::elf_relocatable:
2650b57cec5SDimitry Andric     if (inLib)
2660eae32dcSDimitry Andric       files.push_back(createLazyFile(mbref, "", 0));
2670b57cec5SDimitry Andric     else
2680b57cec5SDimitry Andric       files.push_back(createObjectFile(mbref));
2690b57cec5SDimitry Andric     break;
2700b57cec5SDimitry Andric   default:
2710b57cec5SDimitry Andric     error(path + ": unknown file type");
2720b57cec5SDimitry Andric   }
2730b57cec5SDimitry Andric }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric // Add a given library by searching it from input search paths.
2760b57cec5SDimitry Andric void LinkerDriver::addLibrary(StringRef name) {
2770b57cec5SDimitry Andric   if (Optional<std::string> path = searchLibrary(name))
2780b57cec5SDimitry Andric     addFile(*path, /*withLOption=*/true);
2790b57cec5SDimitry Andric   else
280e8d8bef9SDimitry Andric     error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
2810b57cec5SDimitry Andric }
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric // This function is called on startup. We need this for LTO since
2840b57cec5SDimitry Andric // LTO calls LLVM functions to compile bitcode files to native code.
2850b57cec5SDimitry Andric // Technically this can be delayed until we read bitcode files, but
2860b57cec5SDimitry Andric // we don't bother to do lazily because the initialization is fast.
2870b57cec5SDimitry Andric static void initLLVM() {
2880b57cec5SDimitry Andric   InitializeAllTargets();
2890b57cec5SDimitry Andric   InitializeAllTargetMCs();
2900b57cec5SDimitry Andric   InitializeAllAsmPrinters();
2910b57cec5SDimitry Andric   InitializeAllAsmParsers();
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric // Some command line options or some combinations of them are not allowed.
2950b57cec5SDimitry Andric // This function checks for such errors.
2960b57cec5SDimitry Andric static void checkOptions() {
2970b57cec5SDimitry Andric   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
2980b57cec5SDimitry Andric   // table which is a relatively new feature.
2990b57cec5SDimitry Andric   if (config->emachine == EM_MIPS && config->gnuHash)
3000b57cec5SDimitry Andric     error("the .gnu.hash section is not compatible with the MIPS target");
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
3030b57cec5SDimitry Andric     error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
3040b57cec5SDimitry Andric 
30585868e8aSDimitry Andric   if (config->fixCortexA8 && config->emachine != EM_ARM)
30685868e8aSDimitry Andric     error("--fix-cortex-a8 is only supported on ARM targets");
30785868e8aSDimitry Andric 
3080b57cec5SDimitry Andric   if (config->tocOptimize && config->emachine != EM_PPC64)
309e8d8bef9SDimitry Andric     error("--toc-optimize is only supported on PowerPC64 targets");
310e8d8bef9SDimitry Andric 
311e8d8bef9SDimitry Andric   if (config->pcRelOptimize && config->emachine != EM_PPC64)
312e8d8bef9SDimitry Andric     error("--pcrel-optimize is only supported on PowerPC64 targets");
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   if (config->pie && config->shared)
3150b57cec5SDimitry Andric     error("-shared and -pie may not be used together");
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric   if (!config->shared && !config->filterList.empty())
3180b57cec5SDimitry Andric     error("-F may not be used without -shared");
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric   if (!config->shared && !config->auxiliaryList.empty())
3210b57cec5SDimitry Andric     error("-f may not be used without -shared");
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   if (!config->relocatable && !config->defineCommon)
3240b57cec5SDimitry Andric     error("-no-define-common not supported in non relocatable output");
3250b57cec5SDimitry Andric 
32685868e8aSDimitry Andric   if (config->strip == StripPolicy::All && config->emitRelocs)
32785868e8aSDimitry Andric     error("--strip-all and --emit-relocs may not be used together");
32885868e8aSDimitry Andric 
3290b57cec5SDimitry Andric   if (config->zText && config->zIfuncNoplt)
3300b57cec5SDimitry Andric     error("-z text and -z ifunc-noplt may not be used together");
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   if (config->relocatable) {
3330b57cec5SDimitry Andric     if (config->shared)
3340b57cec5SDimitry Andric       error("-r and -shared may not be used together");
3350b57cec5SDimitry Andric     if (config->gdbIndex)
3360b57cec5SDimitry Andric       error("-r and --gdb-index may not be used together");
3370b57cec5SDimitry Andric     if (config->icf != ICFLevel::None)
3380b57cec5SDimitry Andric       error("-r and --icf may not be used together");
3390b57cec5SDimitry Andric     if (config->pie)
3400b57cec5SDimitry Andric       error("-r and -pie may not be used together");
34185868e8aSDimitry Andric     if (config->exportDynamic)
34285868e8aSDimitry Andric       error("-r and --export-dynamic may not be used together");
3430b57cec5SDimitry Andric   }
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   if (config->executeOnly) {
3460b57cec5SDimitry Andric     if (config->emachine != EM_AARCH64)
347349cc55cSDimitry Andric       error("--execute-only is only supported on AArch64 targets");
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric     if (config->singleRoRx && !script->hasSectionsCommand)
350349cc55cSDimitry Andric       error("--execute-only and --no-rosegment cannot be used together");
3510b57cec5SDimitry Andric   }
3520b57cec5SDimitry Andric 
353480093f4SDimitry Andric   if (config->zRetpolineplt && config->zForceIbt)
354480093f4SDimitry Andric     error("-z force-ibt may not be used with -z retpolineplt");
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   if (config->emachine != EM_AARCH64) {
3575ffd83dbSDimitry Andric     if (config->zPacPlt)
358480093f4SDimitry Andric       error("-z pac-plt only supported on AArch64");
3595ffd83dbSDimitry Andric     if (config->zForceBti)
360480093f4SDimitry Andric       error("-z force-bti only supported on AArch64");
3610eae32dcSDimitry Andric     if (config->zBtiReport != "none")
3620eae32dcSDimitry Andric       error("-z bti-report only supported on AArch64");
3630b57cec5SDimitry Andric   }
3640eae32dcSDimitry Andric 
3650eae32dcSDimitry Andric   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
3660eae32dcSDimitry Andric       config->zCetReport != "none")
3670eae32dcSDimitry Andric     error("-z cet-report only supported on X86 and X86_64");
3680b57cec5SDimitry Andric }
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric static const char *getReproduceOption(opt::InputArgList &args) {
3710b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_reproduce))
3720b57cec5SDimitry Andric     return arg->getValue();
3730b57cec5SDimitry Andric   return getenv("LLD_REPRODUCE");
3740b57cec5SDimitry Andric }
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric static bool hasZOption(opt::InputArgList &args, StringRef key) {
3770b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_z))
3780b57cec5SDimitry Andric     if (key == arg->getValue())
3790b57cec5SDimitry Andric       return true;
3800b57cec5SDimitry Andric   return false;
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
3840b57cec5SDimitry Andric                      bool Default) {
3850b57cec5SDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
3860b57cec5SDimitry Andric     if (k1 == arg->getValue())
3870b57cec5SDimitry Andric       return true;
3880b57cec5SDimitry Andric     if (k2 == arg->getValue())
3890b57cec5SDimitry Andric       return false;
3900b57cec5SDimitry Andric   }
3910b57cec5SDimitry Andric   return Default;
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric 
39485868e8aSDimitry Andric static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
39585868e8aSDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
39685868e8aSDimitry Andric     StringRef v = arg->getValue();
39785868e8aSDimitry Andric     if (v == "noseparate-code")
39885868e8aSDimitry Andric       return SeparateSegmentKind::None;
39985868e8aSDimitry Andric     if (v == "separate-code")
40085868e8aSDimitry Andric       return SeparateSegmentKind::Code;
40185868e8aSDimitry Andric     if (v == "separate-loadable-segments")
40285868e8aSDimitry Andric       return SeparateSegmentKind::Loadable;
40385868e8aSDimitry Andric   }
40485868e8aSDimitry Andric   return SeparateSegmentKind::None;
40585868e8aSDimitry Andric }
40685868e8aSDimitry Andric 
407480093f4SDimitry Andric static GnuStackKind getZGnuStack(opt::InputArgList &args) {
408480093f4SDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
409480093f4SDimitry Andric     if (StringRef("execstack") == arg->getValue())
410480093f4SDimitry Andric       return GnuStackKind::Exec;
411480093f4SDimitry Andric     if (StringRef("noexecstack") == arg->getValue())
412480093f4SDimitry Andric       return GnuStackKind::NoExec;
413480093f4SDimitry Andric     if (StringRef("nognustack") == arg->getValue())
414480093f4SDimitry Andric       return GnuStackKind::None;
415480093f4SDimitry Andric   }
416480093f4SDimitry Andric 
417480093f4SDimitry Andric   return GnuStackKind::NoExec;
418480093f4SDimitry Andric }
419480093f4SDimitry Andric 
4205ffd83dbSDimitry Andric static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
4215ffd83dbSDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
4225ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
4235ffd83dbSDimitry Andric     if (kv.first == "start-stop-visibility") {
4245ffd83dbSDimitry Andric       if (kv.second == "default")
4255ffd83dbSDimitry Andric         return STV_DEFAULT;
4265ffd83dbSDimitry Andric       else if (kv.second == "internal")
4275ffd83dbSDimitry Andric         return STV_INTERNAL;
4285ffd83dbSDimitry Andric       else if (kv.second == "hidden")
4295ffd83dbSDimitry Andric         return STV_HIDDEN;
4305ffd83dbSDimitry Andric       else if (kv.second == "protected")
4315ffd83dbSDimitry Andric         return STV_PROTECTED;
4325ffd83dbSDimitry Andric       error("unknown -z start-stop-visibility= value: " + StringRef(kv.second));
4335ffd83dbSDimitry Andric     }
4345ffd83dbSDimitry Andric   }
4355ffd83dbSDimitry Andric   return STV_PROTECTED;
4365ffd83dbSDimitry Andric }
4375ffd83dbSDimitry Andric 
4380b57cec5SDimitry Andric static bool isKnownZFlag(StringRef s) {
4390b57cec5SDimitry Andric   return s == "combreloc" || s == "copyreloc" || s == "defs" ||
440480093f4SDimitry Andric          s == "execstack" || s == "force-bti" || s == "force-ibt" ||
441480093f4SDimitry Andric          s == "global" || s == "hazardplt" || s == "ifunc-noplt" ||
442480093f4SDimitry Andric          s == "initfirst" || s == "interpose" ||
4430b57cec5SDimitry Andric          s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
44485868e8aSDimitry Andric          s == "separate-code" || s == "separate-loadable-segments" ||
445fe6060f1SDimitry Andric          s == "start-stop-gc" || s == "nocombreloc" || s == "nocopyreloc" ||
446fe6060f1SDimitry Andric          s == "nodefaultlib" || s == "nodelete" || s == "nodlopen" ||
447fe6060f1SDimitry Andric          s == "noexecstack" || s == "nognustack" ||
448fe6060f1SDimitry Andric          s == "nokeep-text-section-prefix" || s == "norelro" ||
449fe6060f1SDimitry Andric          s == "noseparate-code" || s == "nostart-stop-gc" || s == "notext" ||
4505ffd83dbSDimitry Andric          s == "now" || s == "origin" || s == "pac-plt" || s == "rel" ||
4515ffd83dbSDimitry Andric          s == "rela" || s == "relro" || s == "retpolineplt" ||
4525ffd83dbSDimitry Andric          s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" ||
4535ffd83dbSDimitry Andric          s == "wxneeded" || s.startswith("common-page-size=") ||
4540eae32dcSDimitry Andric          s.startswith("bti-report=") || s.startswith("cet-report=") ||
4555ffd83dbSDimitry Andric          s.startswith("dead-reloc-in-nonalloc=") ||
4565ffd83dbSDimitry Andric          s.startswith("max-page-size=") || s.startswith("stack-size=") ||
4575ffd83dbSDimitry Andric          s.startswith("start-stop-visibility=");
4580b57cec5SDimitry Andric }
4590b57cec5SDimitry Andric 
4604824e7fdSDimitry Andric // Report a warning for an unknown -z option.
4610b57cec5SDimitry Andric static void checkZOptions(opt::InputArgList &args) {
4620b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_z))
4630b57cec5SDimitry Andric     if (!isKnownZFlag(arg->getValue()))
4644824e7fdSDimitry Andric       warn("unknown -z value: " + StringRef(arg->getValue()));
4650b57cec5SDimitry Andric }
4660b57cec5SDimitry Andric 
467e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
4680b57cec5SDimitry Andric   ELFOptTable parser;
4690b57cec5SDimitry Andric   opt::InputArgList args = parser.parse(argsArr.slice(1));
4700b57cec5SDimitry Andric 
4714824e7fdSDimitry Andric   // Interpret the flags early because error()/warn() depend on them.
4720b57cec5SDimitry Andric   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
4734824e7fdSDimitry Andric   errorHandler().fatalWarnings =
4744824e7fdSDimitry Andric       args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
4750b57cec5SDimitry Andric   checkZOptions(args);
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   // Handle -help
4780b57cec5SDimitry Andric   if (args.hasArg(OPT_help)) {
4790b57cec5SDimitry Andric     printHelp();
4800b57cec5SDimitry Andric     return;
4810b57cec5SDimitry Andric   }
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   // Handle -v or -version.
4840b57cec5SDimitry Andric   //
4850b57cec5SDimitry Andric   // A note about "compatible with GNU linkers" message: this is a hack for
486349cc55cSDimitry Andric   // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
487349cc55cSDimitry Andric   // a GNU compatible linker. See
488349cc55cSDimitry Andric   // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
4890b57cec5SDimitry Andric   //
4900b57cec5SDimitry Andric   // This is somewhat ugly hack, but in reality, we had no choice other
4910b57cec5SDimitry Andric   // than doing this. Considering the very long release cycle of Libtool,
4920b57cec5SDimitry Andric   // it is not easy to improve it to recognize LLD as a GNU compatible
4930b57cec5SDimitry Andric   // linker in a timely manner. Even if we can make it, there are still a
4940b57cec5SDimitry Andric   // lot of "configure" scripts out there that are generated by old version
4950b57cec5SDimitry Andric   // of Libtool. We cannot convince every software developer to migrate to
4960b57cec5SDimitry Andric   // the latest version and re-generate scripts. So we have this hack.
4970b57cec5SDimitry Andric   if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
4980b57cec5SDimitry Andric     message(getLLDVersion() + " (compatible with GNU linkers)");
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   if (const char *path = getReproduceOption(args)) {
5010b57cec5SDimitry Andric     // Note that --reproduce is a debug option so you can ignore it
5020b57cec5SDimitry Andric     // if you are trying to understand the whole picture of the code.
5030b57cec5SDimitry Andric     Expected<std::unique_ptr<TarWriter>> errOrWriter =
5040b57cec5SDimitry Andric         TarWriter::create(path, path::stem(path));
5050b57cec5SDimitry Andric     if (errOrWriter) {
5060b57cec5SDimitry Andric       tar = std::move(*errOrWriter);
5070b57cec5SDimitry Andric       tar->append("response.txt", createResponseFile(args));
5080b57cec5SDimitry Andric       tar->append("version.txt", getLLDVersion() + "\n");
509e8d8bef9SDimitry Andric       StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
510e8d8bef9SDimitry Andric       if (!ltoSampleProfile.empty())
511e8d8bef9SDimitry Andric         readFile(ltoSampleProfile);
5120b57cec5SDimitry Andric     } else {
5130b57cec5SDimitry Andric       error("--reproduce: " + toString(errOrWriter.takeError()));
5140b57cec5SDimitry Andric     }
5150b57cec5SDimitry Andric   }
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   readConfigs(args);
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   // The behavior of -v or --version is a bit strange, but this is
5200b57cec5SDimitry Andric   // needed for compatibility with GNU linkers.
5210b57cec5SDimitry Andric   if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
5220b57cec5SDimitry Andric     return;
5230b57cec5SDimitry Andric   if (args.hasArg(OPT_version))
5240b57cec5SDimitry Andric     return;
5250b57cec5SDimitry Andric 
5265ffd83dbSDimitry Andric   // Initialize time trace profiler.
5275ffd83dbSDimitry Andric   if (config->timeTraceEnabled)
5285ffd83dbSDimitry Andric     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
5295ffd83dbSDimitry Andric 
5305ffd83dbSDimitry Andric   {
5315ffd83dbSDimitry Andric     llvm::TimeTraceScope timeScope("ExecuteLinker");
5325ffd83dbSDimitry Andric 
5330b57cec5SDimitry Andric     initLLVM();
5340b57cec5SDimitry Andric     createFiles(args);
5350b57cec5SDimitry Andric     if (errorCount())
5360b57cec5SDimitry Andric       return;
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric     inferMachineType();
5390b57cec5SDimitry Andric     setConfigs(args);
5400b57cec5SDimitry Andric     checkOptions();
5410b57cec5SDimitry Andric     if (errorCount())
5420b57cec5SDimitry Andric       return;
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric     // The Target instance handles target-specific stuff, such as applying
5450b57cec5SDimitry Andric     // relocations or writing a PLT section. It also contains target-dependent
5460b57cec5SDimitry Andric     // values such as a default image base address.
5470b57cec5SDimitry Andric     target = getTarget();
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric     switch (config->ekind) {
5500b57cec5SDimitry Andric     case ELF32LEKind:
5510b57cec5SDimitry Andric       link<ELF32LE>(args);
5525ffd83dbSDimitry Andric       break;
5530b57cec5SDimitry Andric     case ELF32BEKind:
5540b57cec5SDimitry Andric       link<ELF32BE>(args);
5555ffd83dbSDimitry Andric       break;
5560b57cec5SDimitry Andric     case ELF64LEKind:
5570b57cec5SDimitry Andric       link<ELF64LE>(args);
5585ffd83dbSDimitry Andric       break;
5590b57cec5SDimitry Andric     case ELF64BEKind:
5600b57cec5SDimitry Andric       link<ELF64BE>(args);
5615ffd83dbSDimitry Andric       break;
5620b57cec5SDimitry Andric     default:
5630b57cec5SDimitry Andric       llvm_unreachable("unknown Config->EKind");
5640b57cec5SDimitry Andric     }
5650b57cec5SDimitry Andric   }
5660b57cec5SDimitry Andric 
5675ffd83dbSDimitry Andric   if (config->timeTraceEnabled) {
568349cc55cSDimitry Andric     checkError(timeTraceProfilerWrite(
569349cc55cSDimitry Andric         args.getLastArgValue(OPT_time_trace_file_eq).str(),
570349cc55cSDimitry Andric         config->outputFile));
5715ffd83dbSDimitry Andric     timeTraceProfilerCleanup();
5725ffd83dbSDimitry Andric   }
5735ffd83dbSDimitry Andric }
5745ffd83dbSDimitry Andric 
5750b57cec5SDimitry Andric static std::string getRpath(opt::InputArgList &args) {
5760b57cec5SDimitry Andric   std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
5770b57cec5SDimitry Andric   return llvm::join(v.begin(), v.end(), ":");
5780b57cec5SDimitry Andric }
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric // Determines what we should do if there are remaining unresolved
5810b57cec5SDimitry Andric // symbols after the name resolution.
582e8d8bef9SDimitry Andric static void setUnresolvedSymbolPolicy(opt::InputArgList &args) {
5830b57cec5SDimitry Andric   UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
5840b57cec5SDimitry Andric                                               OPT_warn_unresolved_symbols, true)
5850b57cec5SDimitry Andric                                      ? UnresolvedPolicy::ReportError
5860b57cec5SDimitry Andric                                      : UnresolvedPolicy::Warn;
587349cc55cSDimitry Andric   // -shared implies --unresolved-symbols=ignore-all because missing
588e8d8bef9SDimitry Andric   // symbols are likely to be resolved at runtime.
589e8d8bef9SDimitry Andric   bool diagRegular = !config->shared, diagShlib = !config->shared;
5900b57cec5SDimitry Andric 
591e8d8bef9SDimitry Andric   for (const opt::Arg *arg : args) {
5920b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
5930b57cec5SDimitry Andric     case OPT_unresolved_symbols: {
5940b57cec5SDimitry Andric       StringRef s = arg->getValue();
595e8d8bef9SDimitry Andric       if (s == "ignore-all") {
596e8d8bef9SDimitry Andric         diagRegular = false;
597e8d8bef9SDimitry Andric         diagShlib = false;
598e8d8bef9SDimitry Andric       } else if (s == "ignore-in-object-files") {
599e8d8bef9SDimitry Andric         diagRegular = false;
600e8d8bef9SDimitry Andric         diagShlib = true;
601e8d8bef9SDimitry Andric       } else if (s == "ignore-in-shared-libs") {
602e8d8bef9SDimitry Andric         diagRegular = true;
603e8d8bef9SDimitry Andric         diagShlib = false;
604e8d8bef9SDimitry Andric       } else if (s == "report-all") {
605e8d8bef9SDimitry Andric         diagRegular = true;
606e8d8bef9SDimitry Andric         diagShlib = true;
607e8d8bef9SDimitry Andric       } else {
6080b57cec5SDimitry Andric         error("unknown --unresolved-symbols value: " + s);
609e8d8bef9SDimitry Andric       }
610e8d8bef9SDimitry Andric       break;
6110b57cec5SDimitry Andric     }
6120b57cec5SDimitry Andric     case OPT_no_undefined:
613e8d8bef9SDimitry Andric       diagRegular = true;
614e8d8bef9SDimitry Andric       break;
6150b57cec5SDimitry Andric     case OPT_z:
6160b57cec5SDimitry Andric       if (StringRef(arg->getValue()) == "defs")
617e8d8bef9SDimitry Andric         diagRegular = true;
618e8d8bef9SDimitry Andric       else if (StringRef(arg->getValue()) == "undefs")
619e8d8bef9SDimitry Andric         diagRegular = false;
620e8d8bef9SDimitry Andric       break;
621e8d8bef9SDimitry Andric     case OPT_allow_shlib_undefined:
622e8d8bef9SDimitry Andric       diagShlib = false;
623e8d8bef9SDimitry Andric       break;
624e8d8bef9SDimitry Andric     case OPT_no_allow_shlib_undefined:
625e8d8bef9SDimitry Andric       diagShlib = true;
626e8d8bef9SDimitry Andric       break;
6270b57cec5SDimitry Andric     }
6280b57cec5SDimitry Andric   }
6290b57cec5SDimitry Andric 
630e8d8bef9SDimitry Andric   config->unresolvedSymbols =
631e8d8bef9SDimitry Andric       diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;
632e8d8bef9SDimitry Andric   config->unresolvedSymbolsInShlib =
633e8d8bef9SDimitry Andric       diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;
6340b57cec5SDimitry Andric }
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric static Target2Policy getTarget2(opt::InputArgList &args) {
6370b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
6380b57cec5SDimitry Andric   if (s == "rel")
6390b57cec5SDimitry Andric     return Target2Policy::Rel;
6400b57cec5SDimitry Andric   if (s == "abs")
6410b57cec5SDimitry Andric     return Target2Policy::Abs;
6420b57cec5SDimitry Andric   if (s == "got-rel")
6430b57cec5SDimitry Andric     return Target2Policy::GotRel;
6440b57cec5SDimitry Andric   error("unknown --target2 option: " + s);
6450b57cec5SDimitry Andric   return Target2Policy::GotRel;
6460b57cec5SDimitry Andric }
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric static bool isOutputFormatBinary(opt::InputArgList &args) {
6490b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_oformat, "elf");
6500b57cec5SDimitry Andric   if (s == "binary")
6510b57cec5SDimitry Andric     return true;
6520b57cec5SDimitry Andric   if (!s.startswith("elf"))
6530b57cec5SDimitry Andric     error("unknown --oformat value: " + s);
6540b57cec5SDimitry Andric   return false;
6550b57cec5SDimitry Andric }
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric static DiscardPolicy getDiscard(opt::InputArgList &args) {
6580b57cec5SDimitry Andric   auto *arg =
6590b57cec5SDimitry Andric       args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
6600b57cec5SDimitry Andric   if (!arg)
6610b57cec5SDimitry Andric     return DiscardPolicy::Default;
6620b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_discard_all)
6630b57cec5SDimitry Andric     return DiscardPolicy::All;
6640b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_discard_locals)
6650b57cec5SDimitry Andric     return DiscardPolicy::Locals;
6660b57cec5SDimitry Andric   return DiscardPolicy::None;
6670b57cec5SDimitry Andric }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric static StringRef getDynamicLinker(opt::InputArgList &args) {
6700b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
67155e4f9d5SDimitry Andric   if (!arg)
6720b57cec5SDimitry Andric     return "";
67355e4f9d5SDimitry Andric   if (arg->getOption().getID() == OPT_no_dynamic_linker) {
67455e4f9d5SDimitry Andric     // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
67555e4f9d5SDimitry Andric     config->noDynamicLinker = true;
67655e4f9d5SDimitry Andric     return "";
67755e4f9d5SDimitry Andric   }
6780b57cec5SDimitry Andric   return arg->getValue();
6790b57cec5SDimitry Andric }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric static ICFLevel getICF(opt::InputArgList &args) {
6820b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
6830b57cec5SDimitry Andric   if (!arg || arg->getOption().getID() == OPT_icf_none)
6840b57cec5SDimitry Andric     return ICFLevel::None;
6850b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_icf_safe)
6860b57cec5SDimitry Andric     return ICFLevel::Safe;
6870b57cec5SDimitry Andric   return ICFLevel::All;
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric static StripPolicy getStrip(opt::InputArgList &args) {
6910b57cec5SDimitry Andric   if (args.hasArg(OPT_relocatable))
6920b57cec5SDimitry Andric     return StripPolicy::None;
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
6950b57cec5SDimitry Andric   if (!arg)
6960b57cec5SDimitry Andric     return StripPolicy::None;
6970b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_strip_all)
6980b57cec5SDimitry Andric     return StripPolicy::All;
6990b57cec5SDimitry Andric   return StripPolicy::Debug;
7000b57cec5SDimitry Andric }
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
7030b57cec5SDimitry Andric                                     const opt::Arg &arg) {
7040b57cec5SDimitry Andric   uint64_t va = 0;
7050b57cec5SDimitry Andric   if (s.startswith("0x"))
7060b57cec5SDimitry Andric     s = s.drop_front(2);
7070b57cec5SDimitry Andric   if (!to_integer(s, va, 16))
7080b57cec5SDimitry Andric     error("invalid argument: " + arg.getAsString(args));
7090b57cec5SDimitry Andric   return va;
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
7130b57cec5SDimitry Andric   StringMap<uint64_t> ret;
7140b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_section_start)) {
7150b57cec5SDimitry Andric     StringRef name;
7160b57cec5SDimitry Andric     StringRef addr;
7170b57cec5SDimitry Andric     std::tie(name, addr) = StringRef(arg->getValue()).split('=');
7180b57cec5SDimitry Andric     ret[name] = parseSectionAddress(addr, args, *arg);
7190b57cec5SDimitry Andric   }
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Ttext))
7220b57cec5SDimitry Andric     ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
7230b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Tdata))
7240b57cec5SDimitry Andric     ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
7250b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Tbss))
7260b57cec5SDimitry Andric     ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
7270b57cec5SDimitry Andric   return ret;
7280b57cec5SDimitry Andric }
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric static SortSectionPolicy getSortSection(opt::InputArgList &args) {
7310b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_sort_section);
7320b57cec5SDimitry Andric   if (s == "alignment")
7330b57cec5SDimitry Andric     return SortSectionPolicy::Alignment;
7340b57cec5SDimitry Andric   if (s == "name")
7350b57cec5SDimitry Andric     return SortSectionPolicy::Name;
7360b57cec5SDimitry Andric   if (!s.empty())
7370b57cec5SDimitry Andric     error("unknown --sort-section rule: " + s);
7380b57cec5SDimitry Andric   return SortSectionPolicy::Default;
7390b57cec5SDimitry Andric }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
7420b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
7430b57cec5SDimitry Andric   if (s == "warn")
7440b57cec5SDimitry Andric     return OrphanHandlingPolicy::Warn;
7450b57cec5SDimitry Andric   if (s == "error")
7460b57cec5SDimitry Andric     return OrphanHandlingPolicy::Error;
7470b57cec5SDimitry Andric   if (s != "place")
7480b57cec5SDimitry Andric     error("unknown --orphan-handling mode: " + s);
7490b57cec5SDimitry Andric   return OrphanHandlingPolicy::Place;
7500b57cec5SDimitry Andric }
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric // Parse --build-id or --build-id=<style>. We handle "tree" as a
7530b57cec5SDimitry Andric // synonym for "sha1" because all our hash functions including
754349cc55cSDimitry Andric // --build-id=sha1 are actually tree hashes for performance reasons.
7550b57cec5SDimitry Andric static std::pair<BuildIdKind, std::vector<uint8_t>>
7560b57cec5SDimitry Andric getBuildId(opt::InputArgList &args) {
7570b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
7580b57cec5SDimitry Andric   if (!arg)
7590b57cec5SDimitry Andric     return {BuildIdKind::None, {}};
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_build_id)
7620b57cec5SDimitry Andric     return {BuildIdKind::Fast, {}};
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   StringRef s = arg->getValue();
7650b57cec5SDimitry Andric   if (s == "fast")
7660b57cec5SDimitry Andric     return {BuildIdKind::Fast, {}};
7670b57cec5SDimitry Andric   if (s == "md5")
7680b57cec5SDimitry Andric     return {BuildIdKind::Md5, {}};
7690b57cec5SDimitry Andric   if (s == "sha1" || s == "tree")
7700b57cec5SDimitry Andric     return {BuildIdKind::Sha1, {}};
7710b57cec5SDimitry Andric   if (s == "uuid")
7720b57cec5SDimitry Andric     return {BuildIdKind::Uuid, {}};
7730b57cec5SDimitry Andric   if (s.startswith("0x"))
7740b57cec5SDimitry Andric     return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   if (s != "none")
7770b57cec5SDimitry Andric     error("unknown --build-id style: " + s);
7780b57cec5SDimitry Andric   return {BuildIdKind::None, {}};
7790b57cec5SDimitry Andric }
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
7820b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
7830b57cec5SDimitry Andric   if (s == "android")
7840b57cec5SDimitry Andric     return {true, false};
7850b57cec5SDimitry Andric   if (s == "relr")
7860b57cec5SDimitry Andric     return {false, true};
7870b57cec5SDimitry Andric   if (s == "android+relr")
7880b57cec5SDimitry Andric     return {true, true};
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric   if (s != "none")
791349cc55cSDimitry Andric     error("unknown --pack-dyn-relocs format: " + s);
7920b57cec5SDimitry Andric   return {false, false};
7930b57cec5SDimitry Andric }
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric static void readCallGraph(MemoryBufferRef mb) {
7960b57cec5SDimitry Andric   // Build a map from symbol name to section
7970b57cec5SDimitry Andric   DenseMap<StringRef, Symbol *> map;
7980eae32dcSDimitry Andric   for (ELFFileBase *file : objectFiles)
7990b57cec5SDimitry Andric     for (Symbol *sym : file->getSymbols())
8000b57cec5SDimitry Andric       map[sym->getName()] = sym;
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric   auto findSection = [&](StringRef name) -> InputSectionBase * {
8030b57cec5SDimitry Andric     Symbol *sym = map.lookup(name);
8040b57cec5SDimitry Andric     if (!sym) {
8050b57cec5SDimitry Andric       if (config->warnSymbolOrdering)
8060b57cec5SDimitry Andric         warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
8070b57cec5SDimitry Andric       return nullptr;
8080b57cec5SDimitry Andric     }
8090b57cec5SDimitry Andric     maybeWarnUnorderableSymbol(sym);
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric     if (Defined *dr = dyn_cast_or_null<Defined>(sym))
8120b57cec5SDimitry Andric       return dyn_cast_or_null<InputSectionBase>(dr->section);
8130b57cec5SDimitry Andric     return nullptr;
8140b57cec5SDimitry Andric   };
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   for (StringRef line : args::getLines(mb)) {
8170b57cec5SDimitry Andric     SmallVector<StringRef, 3> fields;
8180b57cec5SDimitry Andric     line.split(fields, ' ');
8190b57cec5SDimitry Andric     uint64_t count;
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric     if (fields.size() != 3 || !to_integer(fields[2], count)) {
8220b57cec5SDimitry Andric       error(mb.getBufferIdentifier() + ": parse error");
8230b57cec5SDimitry Andric       return;
8240b57cec5SDimitry Andric     }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric     if (InputSectionBase *from = findSection(fields[0]))
8270b57cec5SDimitry Andric       if (InputSectionBase *to = findSection(fields[1]))
8280b57cec5SDimitry Andric         config->callGraphProfile[std::make_pair(from, to)] += count;
8290b57cec5SDimitry Andric   }
8300b57cec5SDimitry Andric }
8310b57cec5SDimitry Andric 
832fe6060f1SDimitry Andric // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
833fe6060f1SDimitry Andric // true and populates cgProfile and symbolIndices.
834fe6060f1SDimitry Andric template <class ELFT>
835fe6060f1SDimitry Andric static bool
836fe6060f1SDimitry Andric processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices,
837fe6060f1SDimitry Andric                             ArrayRef<typename ELFT::CGProfile> &cgProfile,
838fe6060f1SDimitry Andric                             ObjFile<ELFT> *inputObj) {
839fe6060f1SDimitry Andric   if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
840fe6060f1SDimitry Andric     return false;
841fe6060f1SDimitry Andric 
8420eae32dcSDimitry Andric   ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
8430eae32dcSDimitry Andric       inputObj->template getELFShdrs<ELFT>();
8440eae32dcSDimitry Andric   symbolIndices.clear();
8450eae32dcSDimitry Andric   const ELFFile<ELFT> &obj = inputObj->getObj();
846fe6060f1SDimitry Andric   cgProfile =
847fe6060f1SDimitry Andric       check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(
848fe6060f1SDimitry Andric           objSections[inputObj->cgProfileSectionIndex]));
849fe6060f1SDimitry Andric 
850fe6060f1SDimitry Andric   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
851fe6060f1SDimitry Andric     const Elf_Shdr_Impl<ELFT> &sec = objSections[i];
852fe6060f1SDimitry Andric     if (sec.sh_info == inputObj->cgProfileSectionIndex) {
853fe6060f1SDimitry Andric       if (sec.sh_type == SHT_RELA) {
854fe6060f1SDimitry Andric         ArrayRef<typename ELFT::Rela> relas =
855fe6060f1SDimitry Andric             CHECK(obj.relas(sec), "could not retrieve cg profile rela section");
856fe6060f1SDimitry Andric         for (const typename ELFT::Rela &rel : relas)
857fe6060f1SDimitry Andric           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
858fe6060f1SDimitry Andric         break;
859fe6060f1SDimitry Andric       }
860fe6060f1SDimitry Andric       if (sec.sh_type == SHT_REL) {
861fe6060f1SDimitry Andric         ArrayRef<typename ELFT::Rel> rels =
862fe6060f1SDimitry Andric             CHECK(obj.rels(sec), "could not retrieve cg profile rel section");
863fe6060f1SDimitry Andric         for (const typename ELFT::Rel &rel : rels)
864fe6060f1SDimitry Andric           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
865fe6060f1SDimitry Andric         break;
866fe6060f1SDimitry Andric       }
867fe6060f1SDimitry Andric     }
868fe6060f1SDimitry Andric   }
869fe6060f1SDimitry Andric   if (symbolIndices.empty())
870fe6060f1SDimitry Andric     warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");
871fe6060f1SDimitry Andric   return !symbolIndices.empty();
872fe6060f1SDimitry Andric }
873fe6060f1SDimitry Andric 
8740b57cec5SDimitry Andric template <class ELFT> static void readCallGraphsFromObjectFiles() {
875fe6060f1SDimitry Andric   SmallVector<uint32_t, 32> symbolIndices;
876fe6060f1SDimitry Andric   ArrayRef<typename ELFT::CGProfile> cgProfile;
8770b57cec5SDimitry Andric   for (auto file : objectFiles) {
8780b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(file);
879fe6060f1SDimitry Andric     if (!processCallGraphRelocations(symbolIndices, cgProfile, obj))
880fe6060f1SDimitry Andric       continue;
8810b57cec5SDimitry Andric 
882fe6060f1SDimitry Andric     if (symbolIndices.size() != cgProfile.size() * 2)
883fe6060f1SDimitry Andric       fatal("number of relocations doesn't match Weights");
884fe6060f1SDimitry Andric 
885fe6060f1SDimitry Andric     for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {
886fe6060f1SDimitry Andric       const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];
887fe6060f1SDimitry Andric       uint32_t fromIndex = symbolIndices[i * 2];
888fe6060f1SDimitry Andric       uint32_t toIndex = symbolIndices[i * 2 + 1];
889fe6060f1SDimitry Andric       auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
890fe6060f1SDimitry Andric       auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
8910b57cec5SDimitry Andric       if (!fromSym || !toSym)
8920b57cec5SDimitry Andric         continue;
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric       auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
8950b57cec5SDimitry Andric       auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
8960b57cec5SDimitry Andric       if (from && to)
8970b57cec5SDimitry Andric         config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
8980b57cec5SDimitry Andric     }
8990b57cec5SDimitry Andric   }
9000b57cec5SDimitry Andric }
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric static bool getCompressDebugSections(opt::InputArgList &args) {
9030b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
9040b57cec5SDimitry Andric   if (s == "none")
9050b57cec5SDimitry Andric     return false;
9060b57cec5SDimitry Andric   if (s != "zlib")
9070b57cec5SDimitry Andric     error("unknown --compress-debug-sections value: " + s);
9080b57cec5SDimitry Andric   if (!zlib::isAvailable())
9090b57cec5SDimitry Andric     error("--compress-debug-sections: zlib is not available");
9100b57cec5SDimitry Andric   return true;
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric 
91385868e8aSDimitry Andric static StringRef getAliasSpelling(opt::Arg *arg) {
91485868e8aSDimitry Andric   if (const opt::Arg *alias = arg->getAlias())
91585868e8aSDimitry Andric     return alias->getSpelling();
91685868e8aSDimitry Andric   return arg->getSpelling();
91785868e8aSDimitry Andric }
91885868e8aSDimitry Andric 
9190b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
9200b57cec5SDimitry Andric                                                         unsigned id) {
9210b57cec5SDimitry Andric   auto *arg = args.getLastArg(id);
9220b57cec5SDimitry Andric   if (!arg)
9230b57cec5SDimitry Andric     return {"", ""};
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric   StringRef s = arg->getValue();
9260b57cec5SDimitry Andric   std::pair<StringRef, StringRef> ret = s.split(';');
9270b57cec5SDimitry Andric   if (ret.second.empty())
92885868e8aSDimitry Andric     error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
9290b57cec5SDimitry Andric   return ret;
9300b57cec5SDimitry Andric }
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric // Parse the symbol ordering file and warn for any duplicate entries.
9330b57cec5SDimitry Andric static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
9340b57cec5SDimitry Andric   SetVector<StringRef> names;
9350b57cec5SDimitry Andric   for (StringRef s : args::getLines(mb))
9360b57cec5SDimitry Andric     if (!names.insert(s) && config->warnSymbolOrdering)
9370b57cec5SDimitry Andric       warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   return names.takeVector();
9400b57cec5SDimitry Andric }
9410b57cec5SDimitry Andric 
9425ffd83dbSDimitry Andric static bool getIsRela(opt::InputArgList &args) {
9435ffd83dbSDimitry Andric   // If -z rel or -z rela is specified, use the last option.
9445ffd83dbSDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
9455ffd83dbSDimitry Andric     StringRef s(arg->getValue());
9465ffd83dbSDimitry Andric     if (s == "rel")
9475ffd83dbSDimitry Andric       return false;
9485ffd83dbSDimitry Andric     if (s == "rela")
9495ffd83dbSDimitry Andric       return true;
9505ffd83dbSDimitry Andric   }
9515ffd83dbSDimitry Andric 
9525ffd83dbSDimitry Andric   // Otherwise use the psABI defined relocation entry format.
9535ffd83dbSDimitry Andric   uint16_t m = config->emachine;
9545ffd83dbSDimitry Andric   return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC ||
9555ffd83dbSDimitry Andric          m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64;
9565ffd83dbSDimitry Andric }
9575ffd83dbSDimitry Andric 
9580b57cec5SDimitry Andric static void parseClangOption(StringRef opt, const Twine &msg) {
9590b57cec5SDimitry Andric   std::string err;
9600b57cec5SDimitry Andric   raw_string_ostream os(err);
9610b57cec5SDimitry Andric 
9620b57cec5SDimitry Andric   const char *argv[] = {config->progName.data(), opt.data()};
9630b57cec5SDimitry Andric   if (cl::ParseCommandLineOptions(2, argv, "", &os))
9640b57cec5SDimitry Andric     return;
9650b57cec5SDimitry Andric   os.flush();
9660b57cec5SDimitry Andric   error(msg + ": " + StringRef(err).trim());
9670b57cec5SDimitry Andric }
9680b57cec5SDimitry Andric 
9690eae32dcSDimitry Andric // Checks the parameter of the bti-report and cet-report options.
9700eae32dcSDimitry Andric static bool isValidReportString(StringRef arg) {
9710eae32dcSDimitry Andric   return arg == "none" || arg == "warning" || arg == "error";
9720eae32dcSDimitry Andric }
9730eae32dcSDimitry Andric 
9740b57cec5SDimitry Andric // Initializes Config members by the command line options.
9750b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args) {
9760b57cec5SDimitry Andric   errorHandler().verbose = args.hasArg(OPT_verbose);
9770b57cec5SDimitry Andric   errorHandler().vsDiagnostics =
9780b57cec5SDimitry Andric       args.hasArg(OPT_visual_studio_diagnostics_format, false);
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   config->allowMultipleDefinition =
9810b57cec5SDimitry Andric       args.hasFlag(OPT_allow_multiple_definition,
9820b57cec5SDimitry Andric                    OPT_no_allow_multiple_definition, false) ||
9830b57cec5SDimitry Andric       hasZOption(args, "muldefs");
9840b57cec5SDimitry Andric   config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
9856e75b2fbSDimitry Andric   if (opt::Arg *arg =
9866e75b2fbSDimitry Andric           args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,
9876e75b2fbSDimitry Andric                           OPT_Bsymbolic_functions, OPT_Bsymbolic)) {
9886e75b2fbSDimitry Andric     if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
9896e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::NonWeakFunctions;
9906e75b2fbSDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic_functions))
9916e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::Functions;
992fe6060f1SDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic))
9936e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::All;
994fe6060f1SDimitry Andric   }
9950b57cec5SDimitry Andric   config->checkSections =
9960b57cec5SDimitry Andric       args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
9970b57cec5SDimitry Andric   config->chroot = args.getLastArgValue(OPT_chroot);
9980b57cec5SDimitry Andric   config->compressDebugSections = getCompressDebugSections(args);
999fe6060f1SDimitry Andric   config->cref = args.hasArg(OPT_cref);
10000b57cec5SDimitry Andric   config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
10010b57cec5SDimitry Andric                                       !args.hasArg(OPT_relocatable));
10025ffd83dbSDimitry Andric   config->optimizeBBJumps =
10035ffd83dbSDimitry Andric       args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
10040b57cec5SDimitry Andric   config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
1005e8d8bef9SDimitry Andric   config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
10060b57cec5SDimitry Andric   config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
10070b57cec5SDimitry Andric   config->disableVerify = args.hasArg(OPT_disable_verify);
10080b57cec5SDimitry Andric   config->discard = getDiscard(args);
10090b57cec5SDimitry Andric   config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
10100b57cec5SDimitry Andric   config->dynamicLinker = getDynamicLinker(args);
10110b57cec5SDimitry Andric   config->ehFrameHdr =
10120b57cec5SDimitry Andric       args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
10130b57cec5SDimitry Andric   config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
10140b57cec5SDimitry Andric   config->emitRelocs = args.hasArg(OPT_emit_relocs);
10150b57cec5SDimitry Andric   config->callGraphProfileSort = args.hasFlag(
10160b57cec5SDimitry Andric       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
10170b57cec5SDimitry Andric   config->enableNewDtags =
10180b57cec5SDimitry Andric       args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
10190b57cec5SDimitry Andric   config->entry = args.getLastArgValue(OPT_entry);
1020e8d8bef9SDimitry Andric 
1021e8d8bef9SDimitry Andric   errorHandler().errorHandlingScript =
1022e8d8bef9SDimitry Andric       args.getLastArgValue(OPT_error_handling_script);
1023e8d8bef9SDimitry Andric 
10240b57cec5SDimitry Andric   config->executeOnly =
10250b57cec5SDimitry Andric       args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
10260b57cec5SDimitry Andric   config->exportDynamic =
10270b57cec5SDimitry Andric       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
10280b57cec5SDimitry Andric   config->filterList = args::getStrings(args, OPT_filter);
10290b57cec5SDimitry Andric   config->fini = args.getLastArgValue(OPT_fini, "_fini");
10305ffd83dbSDimitry Andric   config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
10315ffd83dbSDimitry Andric                                      !args.hasArg(OPT_relocatable);
10325ffd83dbSDimitry Andric   config->fixCortexA8 =
10335ffd83dbSDimitry Andric       args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
1034e8d8bef9SDimitry Andric   config->fortranCommon =
1035e8d8bef9SDimitry Andric       args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, true);
10360b57cec5SDimitry Andric   config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
10370b57cec5SDimitry Andric   config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
10380b57cec5SDimitry Andric   config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
10390b57cec5SDimitry Andric   config->icf = getICF(args);
10400b57cec5SDimitry Andric   config->ignoreDataAddressEquality =
10410b57cec5SDimitry Andric       args.hasArg(OPT_ignore_data_address_equality);
10420b57cec5SDimitry Andric   config->ignoreFunctionAddressEquality =
10430b57cec5SDimitry Andric       args.hasArg(OPT_ignore_function_address_equality);
10440b57cec5SDimitry Andric   config->init = args.getLastArgValue(OPT_init, "_init");
10450b57cec5SDimitry Andric   config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
10460b57cec5SDimitry Andric   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
10470b57cec5SDimitry Andric   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1048349cc55cSDimitry Andric   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1049349cc55cSDimitry Andric                                             OPT_no_lto_pgo_warn_mismatch, true);
10500b57cec5SDimitry Andric   config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
10515ffd83dbSDimitry Andric   config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
1052e8d8bef9SDimitry Andric   config->ltoNewPassManager =
1053e8d8bef9SDimitry Andric       args.hasFlag(OPT_no_lto_legacy_pass_manager, OPT_lto_legacy_pass_manager,
1054e8d8bef9SDimitry Andric                    LLVM_ENABLE_NEW_PASS_MANAGER);
10550b57cec5SDimitry Andric   config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
10565ffd83dbSDimitry Andric   config->ltoWholeProgramVisibility =
1057e8d8bef9SDimitry Andric       args.hasFlag(OPT_lto_whole_program_visibility,
1058e8d8bef9SDimitry Andric                    OPT_no_lto_whole_program_visibility, false);
10590b57cec5SDimitry Andric   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
106085868e8aSDimitry Andric   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
10610b57cec5SDimitry Andric   config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
10620b57cec5SDimitry Andric   config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
10635ffd83dbSDimitry Andric   config->ltoBasicBlockSections =
1064e8d8bef9SDimitry Andric       args.getLastArgValue(OPT_lto_basic_block_sections);
10655ffd83dbSDimitry Andric   config->ltoUniqueBasicBlockSectionNames =
1066e8d8bef9SDimitry Andric       args.hasFlag(OPT_lto_unique_basic_block_section_names,
1067e8d8bef9SDimitry Andric                    OPT_no_lto_unique_basic_block_section_names, false);
10680b57cec5SDimitry Andric   config->mapFile = args.getLastArgValue(OPT_Map);
10690b57cec5SDimitry Andric   config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
10700b57cec5SDimitry Andric   config->mergeArmExidx =
10710b57cec5SDimitry Andric       args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
1072480093f4SDimitry Andric   config->mmapOutputFile =
1073480093f4SDimitry Andric       args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
10740b57cec5SDimitry Andric   config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
10750b57cec5SDimitry Andric   config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
10760b57cec5SDimitry Andric   config->nostdlib = args.hasArg(OPT_nostdlib);
10770b57cec5SDimitry Andric   config->oFormatBinary = isOutputFormatBinary(args);
10780b57cec5SDimitry Andric   config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
10790b57cec5SDimitry Andric   config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
1080e8d8bef9SDimitry Andric 
1081e8d8bef9SDimitry Andric   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1082e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {
1083e8d8bef9SDimitry Andric     auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());
1084e8d8bef9SDimitry Andric     if (!resultOrErr)
1085e8d8bef9SDimitry Andric       error(arg->getSpelling() + ": invalid argument '" + arg->getValue() +
1086e8d8bef9SDimitry Andric             "', only integer or 'auto' is supported");
1087e8d8bef9SDimitry Andric     else
1088e8d8bef9SDimitry Andric       config->optRemarksHotnessThreshold = *resultOrErr;
1089e8d8bef9SDimitry Andric   }
1090e8d8bef9SDimitry Andric 
10910b57cec5SDimitry Andric   config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
10920b57cec5SDimitry Andric   config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
10930b57cec5SDimitry Andric   config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
10940b57cec5SDimitry Andric   config->optimize = args::getInteger(args, OPT_O, 1);
10950b57cec5SDimitry Andric   config->orphanHandling = getOrphanHandling(args);
10960b57cec5SDimitry Andric   config->outputFile = args.getLastArgValue(OPT_o);
10970b57cec5SDimitry Andric   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
10980b57cec5SDimitry Andric   config->printIcfSections =
10990b57cec5SDimitry Andric       args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
11000b57cec5SDimitry Andric   config->printGcSections =
11010b57cec5SDimitry Andric       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
11025ffd83dbSDimitry Andric   config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
11030b57cec5SDimitry Andric   config->printSymbolOrder =
11040b57cec5SDimitry Andric       args.getLastArgValue(OPT_print_symbol_order);
1105349cc55cSDimitry Andric   config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true);
11060b57cec5SDimitry Andric   config->rpath = getRpath(args);
11070b57cec5SDimitry Andric   config->relocatable = args.hasArg(OPT_relocatable);
11080b57cec5SDimitry Andric   config->saveTemps = args.hasArg(OPT_save_temps);
11090b57cec5SDimitry Andric   config->searchPaths = args::getStrings(args, OPT_library_path);
11100b57cec5SDimitry Andric   config->sectionStartMap = getSectionStartMap(args);
11110b57cec5SDimitry Andric   config->shared = args.hasArg(OPT_shared);
11125ffd83dbSDimitry Andric   config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
11130b57cec5SDimitry Andric   config->soName = args.getLastArgValue(OPT_soname);
11140b57cec5SDimitry Andric   config->sortSection = getSortSection(args);
11150b57cec5SDimitry Andric   config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
11160b57cec5SDimitry Andric   config->strip = getStrip(args);
11170b57cec5SDimitry Andric   config->sysroot = args.getLastArgValue(OPT_sysroot);
11180b57cec5SDimitry Andric   config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
11190b57cec5SDimitry Andric   config->target2 = getTarget2(args);
11200b57cec5SDimitry Andric   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
11210b57cec5SDimitry Andric   config->thinLTOCachePolicy = CHECK(
11220b57cec5SDimitry Andric       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
11230b57cec5SDimitry Andric       "--thinlto-cache-policy: invalid cache policy");
112485868e8aSDimitry Andric   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
112585868e8aSDimitry Andric   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
112685868e8aSDimitry Andric                              args.hasArg(OPT_thinlto_index_only_eq);
112785868e8aSDimitry Andric   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
11280b57cec5SDimitry Andric   config->thinLTOObjectSuffixReplace =
112985868e8aSDimitry Andric       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
11300b57cec5SDimitry Andric   config->thinLTOPrefixReplace =
113185868e8aSDimitry Andric       getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
11325ffd83dbSDimitry Andric   config->thinLTOModulesToCompile =
11335ffd83dbSDimitry Andric       args::getStrings(args, OPT_thinlto_single_module_eq);
11345ffd83dbSDimitry Andric   config->timeTraceEnabled = args.hasArg(OPT_time_trace);
11355ffd83dbSDimitry Andric   config->timeTraceGranularity =
11365ffd83dbSDimitry Andric       args::getInteger(args, OPT_time_trace_granularity, 500);
11370b57cec5SDimitry Andric   config->trace = args.hasArg(OPT_trace);
11380b57cec5SDimitry Andric   config->undefined = args::getStrings(args, OPT_undefined);
11390b57cec5SDimitry Andric   config->undefinedVersion =
11400b57cec5SDimitry Andric       args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
11415ffd83dbSDimitry Andric   config->unique = args.hasArg(OPT_unique);
11420b57cec5SDimitry Andric   config->useAndroidRelrTags = args.hasFlag(
11430b57cec5SDimitry Andric       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
11440b57cec5SDimitry Andric   config->warnBackrefs =
11450b57cec5SDimitry Andric       args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
11460b57cec5SDimitry Andric   config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
11470b57cec5SDimitry Andric   config->warnSymbolOrdering =
11480b57cec5SDimitry Andric       args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1149349cc55cSDimitry Andric   config->whyExtract = args.getLastArgValue(OPT_why_extract);
11500b57cec5SDimitry Andric   config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
11510b57cec5SDimitry Andric   config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
11525ffd83dbSDimitry Andric   config->zForceBti = hasZOption(args, "force-bti");
1153480093f4SDimitry Andric   config->zForceIbt = hasZOption(args, "force-ibt");
11540b57cec5SDimitry Andric   config->zGlobal = hasZOption(args, "global");
1155480093f4SDimitry Andric   config->zGnustack = getZGnuStack(args);
11560b57cec5SDimitry Andric   config->zHazardplt = hasZOption(args, "hazardplt");
11570b57cec5SDimitry Andric   config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
11580b57cec5SDimitry Andric   config->zInitfirst = hasZOption(args, "initfirst");
11590b57cec5SDimitry Andric   config->zInterpose = hasZOption(args, "interpose");
11600b57cec5SDimitry Andric   config->zKeepTextSectionPrefix = getZFlag(
11610b57cec5SDimitry Andric       args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
11620b57cec5SDimitry Andric   config->zNodefaultlib = hasZOption(args, "nodefaultlib");
11630b57cec5SDimitry Andric   config->zNodelete = hasZOption(args, "nodelete");
11640b57cec5SDimitry Andric   config->zNodlopen = hasZOption(args, "nodlopen");
11650b57cec5SDimitry Andric   config->zNow = getZFlag(args, "now", "lazy", false);
11660b57cec5SDimitry Andric   config->zOrigin = hasZOption(args, "origin");
11675ffd83dbSDimitry Andric   config->zPacPlt = hasZOption(args, "pac-plt");
11680b57cec5SDimitry Andric   config->zRelro = getZFlag(args, "relro", "norelro", true);
11690b57cec5SDimitry Andric   config->zRetpolineplt = hasZOption(args, "retpolineplt");
11700b57cec5SDimitry Andric   config->zRodynamic = hasZOption(args, "rodynamic");
117185868e8aSDimitry Andric   config->zSeparate = getZSeparate(args);
1172480093f4SDimitry Andric   config->zShstk = hasZOption(args, "shstk");
11730b57cec5SDimitry Andric   config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1174fe6060f1SDimitry Andric   config->zStartStopGC =
1175fe6060f1SDimitry Andric       getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);
11765ffd83dbSDimitry Andric   config->zStartStopVisibility = getZStartStopVisibility(args);
11770b57cec5SDimitry Andric   config->zText = getZFlag(args, "text", "notext", true);
11780b57cec5SDimitry Andric   config->zWxneeded = hasZOption(args, "wxneeded");
1179e8d8bef9SDimitry Andric   setUnresolvedSymbolPolicy(args);
11804824e7fdSDimitry Andric   config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";
1181fe6060f1SDimitry Andric 
1182fe6060f1SDimitry Andric   if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {
1183fe6060f1SDimitry Andric     if (arg->getOption().matches(OPT_eb))
1184fe6060f1SDimitry Andric       config->optEB = true;
1185fe6060f1SDimitry Andric     else
1186fe6060f1SDimitry Andric       config->optEL = true;
1187fe6060f1SDimitry Andric   }
1188fe6060f1SDimitry Andric 
1189fe6060f1SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {
1190fe6060f1SDimitry Andric     constexpr StringRef errPrefix = "--shuffle-sections=: ";
1191fe6060f1SDimitry Andric     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
1192fe6060f1SDimitry Andric     if (kv.first.empty() || kv.second.empty()) {
1193fe6060f1SDimitry Andric       error(errPrefix + "expected <section_glob>=<seed>, but got '" +
1194fe6060f1SDimitry Andric             arg->getValue() + "'");
1195fe6060f1SDimitry Andric       continue;
1196fe6060f1SDimitry Andric     }
1197fe6060f1SDimitry Andric     // Signed so that <section_glob>=-1 is allowed.
1198fe6060f1SDimitry Andric     int64_t v;
1199fe6060f1SDimitry Andric     if (!to_integer(kv.second, v))
1200fe6060f1SDimitry Andric       error(errPrefix + "expected an integer, but got '" + kv.second + "'");
1201fe6060f1SDimitry Andric     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1202fe6060f1SDimitry Andric       config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v));
1203fe6060f1SDimitry Andric     else
1204fe6060f1SDimitry Andric       error(errPrefix + toString(pat.takeError()));
1205fe6060f1SDimitry Andric   }
12060b57cec5SDimitry Andric 
12070eae32dcSDimitry Andric   auto reports = {std::make_pair("bti-report", &config->zBtiReport),
12080eae32dcSDimitry Andric                   std::make_pair("cet-report", &config->zCetReport)};
12090eae32dcSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_z)) {
12100eae32dcSDimitry Andric     std::pair<StringRef, StringRef> option =
12110eae32dcSDimitry Andric         StringRef(arg->getValue()).split('=');
12120eae32dcSDimitry Andric     for (auto reportArg : reports) {
12130eae32dcSDimitry Andric       if (option.first != reportArg.first)
12140eae32dcSDimitry Andric         continue;
12150eae32dcSDimitry Andric       if (!isValidReportString(option.second)) {
12160eae32dcSDimitry Andric         error(Twine("-z ") + reportArg.first + "= parameter " + option.second +
12170eae32dcSDimitry Andric               " is not recognized");
12180eae32dcSDimitry Andric         continue;
12190eae32dcSDimitry Andric       }
12200eae32dcSDimitry Andric       *reportArg.second = option.second;
12210eae32dcSDimitry Andric     }
12220eae32dcSDimitry Andric   }
12230eae32dcSDimitry Andric 
12245ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_z)) {
12255ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> option =
12265ffd83dbSDimitry Andric         StringRef(arg->getValue()).split('=');
12275ffd83dbSDimitry Andric     if (option.first != "dead-reloc-in-nonalloc")
12285ffd83dbSDimitry Andric       continue;
12295ffd83dbSDimitry Andric     constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
12305ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> kv = option.second.split('=');
12315ffd83dbSDimitry Andric     if (kv.first.empty() || kv.second.empty()) {
12325ffd83dbSDimitry Andric       error(errPrefix + "expected <section_glob>=<value>");
12335ffd83dbSDimitry Andric       continue;
12345ffd83dbSDimitry Andric     }
12355ffd83dbSDimitry Andric     uint64_t v;
12365ffd83dbSDimitry Andric     if (!to_integer(kv.second, v))
12375ffd83dbSDimitry Andric       error(errPrefix + "expected a non-negative integer, but got '" +
12385ffd83dbSDimitry Andric             kv.second + "'");
12395ffd83dbSDimitry Andric     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
12405ffd83dbSDimitry Andric       config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
12415ffd83dbSDimitry Andric     else
12425ffd83dbSDimitry Andric       error(errPrefix + toString(pat.takeError()));
12435ffd83dbSDimitry Andric   }
12445ffd83dbSDimitry Andric 
1245e8d8bef9SDimitry Andric   cl::ResetAllOptionOccurrences();
1246e8d8bef9SDimitry Andric 
12470b57cec5SDimitry Andric   // Parse LTO options.
12480b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
1249*04eeddc0SDimitry Andric     parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
12500b57cec5SDimitry Andric                      arg->getSpelling());
12510b57cec5SDimitry Andric 
12525ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
12535ffd83dbSDimitry Andric     parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
12545ffd83dbSDimitry Andric 
12555ffd83dbSDimitry Andric   // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
12565ffd83dbSDimitry Andric   // relative path. Just ignore. If not ended with "lto-wrapper", consider it an
12575ffd83dbSDimitry Andric   // unsupported LLVMgold.so option and error.
12585ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq))
12595ffd83dbSDimitry Andric     if (!StringRef(arg->getValue()).endswith("lto-wrapper"))
12605ffd83dbSDimitry Andric       error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
12615ffd83dbSDimitry Andric             "'");
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   // Parse -mllvm options.
12640b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_mllvm))
12650b57cec5SDimitry Andric     parseClangOption(arg->getValue(), arg->getSpelling());
12660b57cec5SDimitry Andric 
12675ffd83dbSDimitry Andric   // --threads= takes a positive integer and provides the default value for
12685ffd83dbSDimitry Andric   // --thinlto-jobs=.
12695ffd83dbSDimitry Andric   if (auto *arg = args.getLastArg(OPT_threads)) {
12705ffd83dbSDimitry Andric     StringRef v(arg->getValue());
12715ffd83dbSDimitry Andric     unsigned threads = 0;
12725ffd83dbSDimitry Andric     if (!llvm::to_integer(v, threads, 0) || threads == 0)
12735ffd83dbSDimitry Andric       error(arg->getSpelling() + ": expected a positive integer, but got '" +
12745ffd83dbSDimitry Andric             arg->getValue() + "'");
12755ffd83dbSDimitry Andric     parallel::strategy = hardware_concurrency(threads);
12765ffd83dbSDimitry Andric     config->thinLTOJobs = v;
12775ffd83dbSDimitry Andric   }
12785ffd83dbSDimitry Andric   if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
12795ffd83dbSDimitry Andric     config->thinLTOJobs = arg->getValue();
12805ffd83dbSDimitry Andric 
12810b57cec5SDimitry Andric   if (config->ltoo > 3)
12820b57cec5SDimitry Andric     error("invalid optimization level for LTO: " + Twine(config->ltoo));
12830b57cec5SDimitry Andric   if (config->ltoPartitions == 0)
12840b57cec5SDimitry Andric     error("--lto-partitions: number of threads must be > 0");
12855ffd83dbSDimitry Andric   if (!get_threadpool_strategy(config->thinLTOJobs))
12865ffd83dbSDimitry Andric     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric   if (config->splitStackAdjustSize < 0)
12890b57cec5SDimitry Andric     error("--split-stack-adjust-size: size must be >= 0");
12900b57cec5SDimitry Andric 
1291480093f4SDimitry Andric   // The text segment is traditionally the first segment, whose address equals
1292480093f4SDimitry Andric   // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1293480093f4SDimitry Andric   // is an old-fashioned option that does not play well with lld's layout.
1294480093f4SDimitry Andric   // Suggest --image-base as a likely alternative.
1295480093f4SDimitry Andric   if (args.hasArg(OPT_Ttext_segment))
1296480093f4SDimitry Andric     error("-Ttext-segment is not supported. Use --image-base if you "
1297480093f4SDimitry Andric           "intend to set the base address");
1298480093f4SDimitry Andric 
12990b57cec5SDimitry Andric   // Parse ELF{32,64}{LE,BE} and CPU type.
13000b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_m)) {
13010b57cec5SDimitry Andric     StringRef s = arg->getValue();
13020b57cec5SDimitry Andric     std::tie(config->ekind, config->emachine, config->osabi) =
13030b57cec5SDimitry Andric         parseEmulation(s);
13040b57cec5SDimitry Andric     config->mipsN32Abi =
13050b57cec5SDimitry Andric         (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
13060b57cec5SDimitry Andric     config->emulation = s;
13070b57cec5SDimitry Andric   }
13080b57cec5SDimitry Andric 
1309349cc55cSDimitry Andric   // Parse --hash-style={sysv,gnu,both}.
13100b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_hash_style)) {
13110b57cec5SDimitry Andric     StringRef s = arg->getValue();
13120b57cec5SDimitry Andric     if (s == "sysv")
13130b57cec5SDimitry Andric       config->sysvHash = true;
13140b57cec5SDimitry Andric     else if (s == "gnu")
13150b57cec5SDimitry Andric       config->gnuHash = true;
13160b57cec5SDimitry Andric     else if (s == "both")
13170b57cec5SDimitry Andric       config->sysvHash = config->gnuHash = true;
13180b57cec5SDimitry Andric     else
1319349cc55cSDimitry Andric       error("unknown --hash-style: " + s);
13200b57cec5SDimitry Andric   }
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric   if (args.hasArg(OPT_print_map))
13230b57cec5SDimitry Andric     config->mapFile = "-";
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
13260b57cec5SDimitry Andric   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
13270b57cec5SDimitry Andric   // it.
13280b57cec5SDimitry Andric   if (config->nmagic || config->omagic)
13290b57cec5SDimitry Andric     config->zRelro = false;
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
13340b57cec5SDimitry Andric       getPackDynRelocs(args);
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
13370b57cec5SDimitry Andric     if (args.hasArg(OPT_call_graph_ordering_file))
13380b57cec5SDimitry Andric       error("--symbol-ordering-file and --call-graph-order-file "
13390b57cec5SDimitry Andric             "may not be used together");
13400b57cec5SDimitry Andric     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
13410b57cec5SDimitry Andric       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
13420b57cec5SDimitry Andric       // Also need to disable CallGraphProfileSort to prevent
13430b57cec5SDimitry Andric       // LLD order symbols with CGProfile
13440b57cec5SDimitry Andric       config->callGraphProfileSort = false;
13450b57cec5SDimitry Andric     }
13460b57cec5SDimitry Andric   }
13470b57cec5SDimitry Andric 
134885868e8aSDimitry Andric   assert(config->versionDefinitions.empty());
134985868e8aSDimitry Andric   config->versionDefinitions.push_back(
13506e75b2fbSDimitry Andric       {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});
13516e75b2fbSDimitry Andric   config->versionDefinitions.push_back(
13526e75b2fbSDimitry Andric       {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});
135385868e8aSDimitry Andric 
13540b57cec5SDimitry Andric   // If --retain-symbol-file is used, we'll keep only the symbols listed in
13550b57cec5SDimitry Andric   // the file and discard all others.
13560b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
13576e75b2fbSDimitry Andric     config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
135885868e8aSDimitry Andric         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
13590b57cec5SDimitry Andric     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
13600b57cec5SDimitry Andric       for (StringRef s : args::getLines(*buffer))
13616e75b2fbSDimitry Andric         config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
136285868e8aSDimitry Andric             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
13630b57cec5SDimitry Andric   }
13640b57cec5SDimitry Andric 
13655ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
13665ffd83dbSDimitry Andric     StringRef pattern(arg->getValue());
13675ffd83dbSDimitry Andric     if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
13685ffd83dbSDimitry Andric       config->warnBackrefsExclude.push_back(std::move(*pat));
13695ffd83dbSDimitry Andric     else
13705ffd83dbSDimitry Andric       error(arg->getSpelling() + ": " + toString(pat.takeError()));
13715ffd83dbSDimitry Andric   }
13725ffd83dbSDimitry Andric 
1373349cc55cSDimitry Andric   // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1374349cc55cSDimitry Andric   // which should be exported. For -shared, references to matched non-local
1375349cc55cSDimitry Andric   // STV_DEFAULT symbols are not bound to definitions within the shared object,
1376349cc55cSDimitry Andric   // even if other options express a symbolic intention: -Bsymbolic,
13775ffd83dbSDimitry Andric   // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
13780b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
13790b57cec5SDimitry Andric     config->dynamicList.push_back(
13805ffd83dbSDimitry Andric         {arg->getValue(), /*isExternCpp=*/false,
13815ffd83dbSDimitry Andric          /*hasWildcard=*/hasWildcard(arg->getValue())});
13820b57cec5SDimitry Andric 
1383349cc55cSDimitry Andric   // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1384349cc55cSDimitry Andric   // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1385349cc55cSDimitry Andric   // like semantics.
1386349cc55cSDimitry Andric   config->symbolic =
1387349cc55cSDimitry Andric       config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1388349cc55cSDimitry Andric   for (auto *arg :
1389349cc55cSDimitry Andric        args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))
1390349cc55cSDimitry Andric     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1391349cc55cSDimitry Andric       readDynamicList(*buffer);
1392349cc55cSDimitry Andric 
13930b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_version_script))
13940b57cec5SDimitry Andric     if (Optional<std::string> path = searchScript(arg->getValue())) {
13950b57cec5SDimitry Andric       if (Optional<MemoryBufferRef> buffer = readFile(*path))
13960b57cec5SDimitry Andric         readVersionScript(*buffer);
13970b57cec5SDimitry Andric     } else {
13980b57cec5SDimitry Andric       error(Twine("cannot find version script ") + arg->getValue());
13990b57cec5SDimitry Andric     }
14000b57cec5SDimitry Andric }
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric // Some Config members do not directly correspond to any particular
14030b57cec5SDimitry Andric // command line options, but computed based on other Config values.
14040b57cec5SDimitry Andric // This function initialize such members. See Config.h for the details
14050b57cec5SDimitry Andric // of these values.
14060b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args) {
14070b57cec5SDimitry Andric   ELFKind k = config->ekind;
14080b57cec5SDimitry Andric   uint16_t m = config->emachine;
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric   config->copyRelocs = (config->relocatable || config->emitRelocs);
14110b57cec5SDimitry Andric   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
14120b57cec5SDimitry Andric   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
14130b57cec5SDimitry Andric   config->endianness = config->isLE ? endianness::little : endianness::big;
14140b57cec5SDimitry Andric   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
14150b57cec5SDimitry Andric   config->isPic = config->pie || config->shared;
14160b57cec5SDimitry Andric   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
14170b57cec5SDimitry Andric   config->wordsize = config->is64 ? 8 : 4;
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   // ELF defines two different ways to store relocation addends as shown below:
14200b57cec5SDimitry Andric   //
14215ffd83dbSDimitry Andric   //  Rel: Addends are stored to the location where relocations are applied. It
14225ffd83dbSDimitry Andric   //  cannot pack the full range of addend values for all relocation types, but
14235ffd83dbSDimitry Andric   //  this only affects relocation types that we don't support emitting as
14245ffd83dbSDimitry Andric   //  dynamic relocations (see getDynRel).
14250b57cec5SDimitry Andric   //  Rela: Addends are stored as part of relocation entry.
14260b57cec5SDimitry Andric   //
14270b57cec5SDimitry Andric   // In other words, Rela makes it easy to read addends at the price of extra
14285ffd83dbSDimitry Andric   // 4 or 8 byte for each relocation entry.
14290b57cec5SDimitry Andric   //
14305ffd83dbSDimitry Andric   // We pick the format for dynamic relocations according to the psABI for each
14315ffd83dbSDimitry Andric   // processor, but a contrary choice can be made if the dynamic loader
14325ffd83dbSDimitry Andric   // supports.
14335ffd83dbSDimitry Andric   config->isRela = getIsRela(args);
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric   // If the output uses REL relocations we must store the dynamic relocation
14360b57cec5SDimitry Andric   // addends to the output sections. We also store addends for RELA relocations
14370b57cec5SDimitry Andric   // if --apply-dynamic-relocs is used.
14380b57cec5SDimitry Andric   // We default to not writing the addends when using RELA relocations since
14390b57cec5SDimitry Andric   // any standard conforming tool can find it in r_addend.
14400b57cec5SDimitry Andric   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
14410b57cec5SDimitry Andric                                       OPT_no_apply_dynamic_relocs, false) ||
14420b57cec5SDimitry Andric                          !config->isRela;
1443fe6060f1SDimitry Andric   // Validation of dynamic relocation addends is on by default for assertions
1444fe6060f1SDimitry Andric   // builds (for supported targets) and disabled otherwise. Ideally we would
1445fe6060f1SDimitry Andric   // enable the debug checks for all targets, but currently not all targets
1446fe6060f1SDimitry Andric   // have support for reading Elf_Rel addends, so we only enable for a subset.
1447fe6060f1SDimitry Andric #ifndef NDEBUG
1448fe6060f1SDimitry Andric   bool checkDynamicRelocsDefault = m == EM_ARM || m == EM_386 || m == EM_MIPS ||
1449fe6060f1SDimitry Andric                                    m == EM_X86_64 || m == EM_RISCV;
1450fe6060f1SDimitry Andric #else
1451fe6060f1SDimitry Andric   bool checkDynamicRelocsDefault = false;
1452fe6060f1SDimitry Andric #endif
1453fe6060f1SDimitry Andric   config->checkDynamicRelocs =
1454fe6060f1SDimitry Andric       args.hasFlag(OPT_check_dynamic_relocations,
1455fe6060f1SDimitry Andric                    OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);
14560b57cec5SDimitry Andric   config->tocOptimize =
14570b57cec5SDimitry Andric       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1458e8d8bef9SDimitry Andric   config->pcRelOptimize =
1459e8d8bef9SDimitry Andric       args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
14600b57cec5SDimitry Andric }
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric static bool isFormatBinary(StringRef s) {
14630b57cec5SDimitry Andric   if (s == "binary")
14640b57cec5SDimitry Andric     return true;
14650b57cec5SDimitry Andric   if (s == "elf" || s == "default")
14660b57cec5SDimitry Andric     return false;
1467349cc55cSDimitry Andric   error("unknown --format value: " + s +
14680b57cec5SDimitry Andric         " (supported formats: elf, default, binary)");
14690b57cec5SDimitry Andric   return false;
14700b57cec5SDimitry Andric }
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric void LinkerDriver::createFiles(opt::InputArgList &args) {
1473e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Load input files");
14740b57cec5SDimitry Andric   // For --{push,pop}-state.
14750b57cec5SDimitry Andric   std::vector<std::tuple<bool, bool, bool>> stack;
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   // Iterate over argv to process input files and positional arguments.
1478e8d8bef9SDimitry Andric   InputFile::isInGroup = false;
14790b57cec5SDimitry Andric   for (auto *arg : args) {
14800b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
14810b57cec5SDimitry Andric     case OPT_library:
14820b57cec5SDimitry Andric       addLibrary(arg->getValue());
14830b57cec5SDimitry Andric       break;
14840b57cec5SDimitry Andric     case OPT_INPUT:
14850b57cec5SDimitry Andric       addFile(arg->getValue(), /*withLOption=*/false);
14860b57cec5SDimitry Andric       break;
14870b57cec5SDimitry Andric     case OPT_defsym: {
14880b57cec5SDimitry Andric       StringRef from;
14890b57cec5SDimitry Andric       StringRef to;
14900b57cec5SDimitry Andric       std::tie(from, to) = StringRef(arg->getValue()).split('=');
14910b57cec5SDimitry Andric       if (from.empty() || to.empty())
1492349cc55cSDimitry Andric         error("--defsym: syntax error: " + StringRef(arg->getValue()));
14930b57cec5SDimitry Andric       else
1494349cc55cSDimitry Andric         readDefsym(from, MemoryBufferRef(to, "--defsym"));
14950b57cec5SDimitry Andric       break;
14960b57cec5SDimitry Andric     }
14970b57cec5SDimitry Andric     case OPT_script:
14980b57cec5SDimitry Andric       if (Optional<std::string> path = searchScript(arg->getValue())) {
14990b57cec5SDimitry Andric         if (Optional<MemoryBufferRef> mb = readFile(*path))
15000b57cec5SDimitry Andric           readLinkerScript(*mb);
15010b57cec5SDimitry Andric         break;
15020b57cec5SDimitry Andric       }
15030b57cec5SDimitry Andric       error(Twine("cannot find linker script ") + arg->getValue());
15040b57cec5SDimitry Andric       break;
15050b57cec5SDimitry Andric     case OPT_as_needed:
15060b57cec5SDimitry Andric       config->asNeeded = true;
15070b57cec5SDimitry Andric       break;
15080b57cec5SDimitry Andric     case OPT_format:
15090b57cec5SDimitry Andric       config->formatBinary = isFormatBinary(arg->getValue());
15100b57cec5SDimitry Andric       break;
15110b57cec5SDimitry Andric     case OPT_no_as_needed:
15120b57cec5SDimitry Andric       config->asNeeded = false;
15130b57cec5SDimitry Andric       break;
15140b57cec5SDimitry Andric     case OPT_Bstatic:
15150b57cec5SDimitry Andric     case OPT_omagic:
15160b57cec5SDimitry Andric     case OPT_nmagic:
15170b57cec5SDimitry Andric       config->isStatic = true;
15180b57cec5SDimitry Andric       break;
15190b57cec5SDimitry Andric     case OPT_Bdynamic:
15200b57cec5SDimitry Andric       config->isStatic = false;
15210b57cec5SDimitry Andric       break;
15220b57cec5SDimitry Andric     case OPT_whole_archive:
15230b57cec5SDimitry Andric       inWholeArchive = true;
15240b57cec5SDimitry Andric       break;
15250b57cec5SDimitry Andric     case OPT_no_whole_archive:
15260b57cec5SDimitry Andric       inWholeArchive = false;
15270b57cec5SDimitry Andric       break;
15280b57cec5SDimitry Andric     case OPT_just_symbols:
15290b57cec5SDimitry Andric       if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
15300b57cec5SDimitry Andric         files.push_back(createObjectFile(*mb));
15310b57cec5SDimitry Andric         files.back()->justSymbols = true;
15320b57cec5SDimitry Andric       }
15330b57cec5SDimitry Andric       break;
15340b57cec5SDimitry Andric     case OPT_start_group:
15350b57cec5SDimitry Andric       if (InputFile::isInGroup)
15360b57cec5SDimitry Andric         error("nested --start-group");
15370b57cec5SDimitry Andric       InputFile::isInGroup = true;
15380b57cec5SDimitry Andric       break;
15390b57cec5SDimitry Andric     case OPT_end_group:
15400b57cec5SDimitry Andric       if (!InputFile::isInGroup)
15410b57cec5SDimitry Andric         error("stray --end-group");
15420b57cec5SDimitry Andric       InputFile::isInGroup = false;
15430b57cec5SDimitry Andric       ++InputFile::nextGroupId;
15440b57cec5SDimitry Andric       break;
15450b57cec5SDimitry Andric     case OPT_start_lib:
15460b57cec5SDimitry Andric       if (inLib)
15470b57cec5SDimitry Andric         error("nested --start-lib");
15480b57cec5SDimitry Andric       if (InputFile::isInGroup)
15490b57cec5SDimitry Andric         error("may not nest --start-lib in --start-group");
15500b57cec5SDimitry Andric       inLib = true;
15510b57cec5SDimitry Andric       InputFile::isInGroup = true;
15520b57cec5SDimitry Andric       break;
15530b57cec5SDimitry Andric     case OPT_end_lib:
15540b57cec5SDimitry Andric       if (!inLib)
15550b57cec5SDimitry Andric         error("stray --end-lib");
15560b57cec5SDimitry Andric       inLib = false;
15570b57cec5SDimitry Andric       InputFile::isInGroup = false;
15580b57cec5SDimitry Andric       ++InputFile::nextGroupId;
15590b57cec5SDimitry Andric       break;
15600b57cec5SDimitry Andric     case OPT_push_state:
15610b57cec5SDimitry Andric       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
15620b57cec5SDimitry Andric       break;
15630b57cec5SDimitry Andric     case OPT_pop_state:
15640b57cec5SDimitry Andric       if (stack.empty()) {
15650b57cec5SDimitry Andric         error("unbalanced --push-state/--pop-state");
15660b57cec5SDimitry Andric         break;
15670b57cec5SDimitry Andric       }
15680b57cec5SDimitry Andric       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
15690b57cec5SDimitry Andric       stack.pop_back();
15700b57cec5SDimitry Andric       break;
15710b57cec5SDimitry Andric     }
15720b57cec5SDimitry Andric   }
15730b57cec5SDimitry Andric 
15740b57cec5SDimitry Andric   if (files.empty() && errorCount() == 0)
15750b57cec5SDimitry Andric     error("no input files");
15760b57cec5SDimitry Andric }
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric // If -m <machine_type> was not given, infer it from object files.
15790b57cec5SDimitry Andric void LinkerDriver::inferMachineType() {
15800b57cec5SDimitry Andric   if (config->ekind != ELFNoneKind)
15810b57cec5SDimitry Andric     return;
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric   for (InputFile *f : files) {
15840b57cec5SDimitry Andric     if (f->ekind == ELFNoneKind)
15850b57cec5SDimitry Andric       continue;
15860b57cec5SDimitry Andric     config->ekind = f->ekind;
15870b57cec5SDimitry Andric     config->emachine = f->emachine;
15880b57cec5SDimitry Andric     config->osabi = f->osabi;
15890b57cec5SDimitry Andric     config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
15900b57cec5SDimitry Andric     return;
15910b57cec5SDimitry Andric   }
15920b57cec5SDimitry Andric   error("target emulation unknown: -m or at least one .o file required");
15930b57cec5SDimitry Andric }
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric // Parse -z max-page-size=<value>. The default value is defined by
15960b57cec5SDimitry Andric // each target.
15970b57cec5SDimitry Andric static uint64_t getMaxPageSize(opt::InputArgList &args) {
15980b57cec5SDimitry Andric   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
15990b57cec5SDimitry Andric                                        target->defaultMaxPageSize);
16000b57cec5SDimitry Andric   if (!isPowerOf2_64(val))
16010b57cec5SDimitry Andric     error("max-page-size: value isn't a power of 2");
16020b57cec5SDimitry Andric   if (config->nmagic || config->omagic) {
16030b57cec5SDimitry Andric     if (val != target->defaultMaxPageSize)
16040b57cec5SDimitry Andric       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
16050b57cec5SDimitry Andric     return 1;
16060b57cec5SDimitry Andric   }
16070b57cec5SDimitry Andric   return val;
16080b57cec5SDimitry Andric }
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric // Parse -z common-page-size=<value>. The default value is defined by
16110b57cec5SDimitry Andric // each target.
16120b57cec5SDimitry Andric static uint64_t getCommonPageSize(opt::InputArgList &args) {
16130b57cec5SDimitry Andric   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
16140b57cec5SDimitry Andric                                        target->defaultCommonPageSize);
16150b57cec5SDimitry Andric   if (!isPowerOf2_64(val))
16160b57cec5SDimitry Andric     error("common-page-size: value isn't a power of 2");
16170b57cec5SDimitry Andric   if (config->nmagic || config->omagic) {
16180b57cec5SDimitry Andric     if (val != target->defaultCommonPageSize)
16190b57cec5SDimitry Andric       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
16200b57cec5SDimitry Andric     return 1;
16210b57cec5SDimitry Andric   }
16220b57cec5SDimitry Andric   // commonPageSize can't be larger than maxPageSize.
16230b57cec5SDimitry Andric   if (val > config->maxPageSize)
16240b57cec5SDimitry Andric     val = config->maxPageSize;
16250b57cec5SDimitry Andric   return val;
16260b57cec5SDimitry Andric }
16270b57cec5SDimitry Andric 
1628349cc55cSDimitry Andric // Parses --image-base option.
16290b57cec5SDimitry Andric static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
16300b57cec5SDimitry Andric   // Because we are using "Config->maxPageSize" here, this function has to be
16310b57cec5SDimitry Andric   // called after the variable is initialized.
16320b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_image_base);
16330b57cec5SDimitry Andric   if (!arg)
16340b57cec5SDimitry Andric     return None;
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric   StringRef s = arg->getValue();
16370b57cec5SDimitry Andric   uint64_t v;
16380b57cec5SDimitry Andric   if (!to_integer(s, v)) {
1639349cc55cSDimitry Andric     error("--image-base: number expected, but got " + s);
16400b57cec5SDimitry Andric     return 0;
16410b57cec5SDimitry Andric   }
16420b57cec5SDimitry Andric   if ((v % config->maxPageSize) != 0)
1643349cc55cSDimitry Andric     warn("--image-base: address isn't multiple of page size: " + s);
16440b57cec5SDimitry Andric   return v;
16450b57cec5SDimitry Andric }
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric // Parses `--exclude-libs=lib,lib,...`.
16480b57cec5SDimitry Andric // The library names may be delimited by commas or colons.
16490b57cec5SDimitry Andric static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
16500b57cec5SDimitry Andric   DenseSet<StringRef> ret;
16510b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_exclude_libs)) {
16520b57cec5SDimitry Andric     StringRef s = arg->getValue();
16530b57cec5SDimitry Andric     for (;;) {
16540b57cec5SDimitry Andric       size_t pos = s.find_first_of(",:");
16550b57cec5SDimitry Andric       if (pos == StringRef::npos)
16560b57cec5SDimitry Andric         break;
16570b57cec5SDimitry Andric       ret.insert(s.substr(0, pos));
16580b57cec5SDimitry Andric       s = s.substr(pos + 1);
16590b57cec5SDimitry Andric     }
16600b57cec5SDimitry Andric     ret.insert(s);
16610b57cec5SDimitry Andric   }
16620b57cec5SDimitry Andric   return ret;
16630b57cec5SDimitry Andric }
16640b57cec5SDimitry Andric 
1665349cc55cSDimitry Andric // Handles the --exclude-libs option. If a static library file is specified
1666349cc55cSDimitry Andric // by the --exclude-libs option, all public symbols from the archive become
16670b57cec5SDimitry Andric // private unless otherwise specified by version scripts or something.
16680b57cec5SDimitry Andric // A special library name "ALL" means all archive files.
16690b57cec5SDimitry Andric //
16700b57cec5SDimitry Andric // This is not a popular option, but some programs such as bionic libc use it.
16710b57cec5SDimitry Andric static void excludeLibs(opt::InputArgList &args) {
16720b57cec5SDimitry Andric   DenseSet<StringRef> libs = getExcludeLibs(args);
16730b57cec5SDimitry Andric   bool all = libs.count("ALL");
16740b57cec5SDimitry Andric 
16750b57cec5SDimitry Andric   auto visit = [&](InputFile *file) {
16760b57cec5SDimitry Andric     if (!file->archiveName.empty())
16770b57cec5SDimitry Andric       if (all || libs.count(path::filename(file->archiveName)))
16780b57cec5SDimitry Andric         for (Symbol *sym : file->getSymbols())
1679480093f4SDimitry Andric           if (!sym->isUndefined() && !sym->isLocal() && sym->file == file)
16800b57cec5SDimitry Andric             sym->versionId = VER_NDX_LOCAL;
16810b57cec5SDimitry Andric   };
16820b57cec5SDimitry Andric 
16830eae32dcSDimitry Andric   for (ELFFileBase *file : objectFiles)
16840b57cec5SDimitry Andric     visit(file);
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric   for (BitcodeFile *file : bitcodeFiles)
16870b57cec5SDimitry Andric     visit(file);
16880b57cec5SDimitry Andric }
16890b57cec5SDimitry Andric 
16905ffd83dbSDimitry Andric // Force Sym to be entered in the output.
1691349cc55cSDimitry Andric static void handleUndefined(Symbol *sym, const char *option) {
16920b57cec5SDimitry Andric   // Since a symbol may not be used inside the program, LTO may
16930b57cec5SDimitry Andric   // eliminate it. Mark the symbol as "used" to prevent it.
16940b57cec5SDimitry Andric   sym->isUsedInRegularObj = true;
16950b57cec5SDimitry Andric 
1696349cc55cSDimitry Andric   if (!sym->isLazy())
1697349cc55cSDimitry Andric     return;
16984824e7fdSDimitry Andric   sym->extract();
1699349cc55cSDimitry Andric   if (!config->whyExtract.empty())
1700349cc55cSDimitry Andric     whyExtract.emplace_back(option, sym->file, *sym);
17010b57cec5SDimitry Andric }
17020b57cec5SDimitry Andric 
1703480093f4SDimitry Andric // As an extension to GNU linkers, lld supports a variant of `-u`
17040b57cec5SDimitry Andric // which accepts wildcard patterns. All symbols that match a given
17050b57cec5SDimitry Andric // pattern are handled as if they were given by `-u`.
17060b57cec5SDimitry Andric static void handleUndefinedGlob(StringRef arg) {
17070b57cec5SDimitry Andric   Expected<GlobPattern> pat = GlobPattern::create(arg);
17080b57cec5SDimitry Andric   if (!pat) {
17090b57cec5SDimitry Andric     error("--undefined-glob: " + toString(pat.takeError()));
17100b57cec5SDimitry Andric     return;
17110b57cec5SDimitry Andric   }
17120b57cec5SDimitry Andric 
17134824e7fdSDimitry Andric   // Calling sym->extract() in the loop is not safe because it may add new
17144824e7fdSDimitry Andric   // symbols to the symbol table, invalidating the current iterator.
17150b57cec5SDimitry Andric   std::vector<Symbol *> syms;
17164824e7fdSDimitry Andric   for (Symbol *sym : symtab->symbols())
1717*04eeddc0SDimitry Andric     if (!sym->isPlaceholder() && pat->match(sym->getName()))
17180b57cec5SDimitry Andric       syms.push_back(sym);
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric   for (Symbol *sym : syms)
1721349cc55cSDimitry Andric     handleUndefined(sym, "--undefined-glob");
17220b57cec5SDimitry Andric }
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric static void handleLibcall(StringRef name) {
17250b57cec5SDimitry Andric   Symbol *sym = symtab->find(name);
17260b57cec5SDimitry Andric   if (!sym || !sym->isLazy())
17270b57cec5SDimitry Andric     return;
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric   MemoryBufferRef mb;
17300b57cec5SDimitry Andric   if (auto *lo = dyn_cast<LazyObject>(sym))
17310b57cec5SDimitry Andric     mb = lo->file->mb;
17320b57cec5SDimitry Andric   else
17330b57cec5SDimitry Andric     mb = cast<LazyArchive>(sym)->getMemberBuffer();
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric   if (isBitcode(mb))
17364824e7fdSDimitry Andric     sym->extract();
17370b57cec5SDimitry Andric }
17380b57cec5SDimitry Andric 
1739e8d8bef9SDimitry Andric // Handle --dependency-file=<path>. If that option is given, lld creates a
1740e8d8bef9SDimitry Andric // file at a given path with the following contents:
1741e8d8bef9SDimitry Andric //
1742e8d8bef9SDimitry Andric //   <output-file>: <input-file> ...
1743e8d8bef9SDimitry Andric //
1744e8d8bef9SDimitry Andric //   <input-file>:
1745e8d8bef9SDimitry Andric //
1746e8d8bef9SDimitry Andric // where <output-file> is a pathname of an output file and <input-file>
1747e8d8bef9SDimitry Andric // ... is a list of pathnames of all input files. `make` command can read a
1748e8d8bef9SDimitry Andric // file in the above format and interpret it as a dependency info. We write
1749e8d8bef9SDimitry Andric // phony targets for every <input-file> to avoid an error when that file is
1750e8d8bef9SDimitry Andric // removed.
1751e8d8bef9SDimitry Andric //
1752e8d8bef9SDimitry Andric // This option is useful if you want to make your final executable to depend
1753e8d8bef9SDimitry Andric // on all input files including system libraries. Here is why.
1754e8d8bef9SDimitry Andric //
1755e8d8bef9SDimitry Andric // When you write a Makefile, you usually write it so that the final
1756e8d8bef9SDimitry Andric // executable depends on all user-generated object files. Normally, you
1757e8d8bef9SDimitry Andric // don't make your executable to depend on system libraries (such as libc)
1758e8d8bef9SDimitry Andric // because you don't know the exact paths of libraries, even though system
1759e8d8bef9SDimitry Andric // libraries that are linked to your executable statically are technically a
1760e8d8bef9SDimitry Andric // part of your program. By using --dependency-file option, you can make
1761e8d8bef9SDimitry Andric // lld to dump dependency info so that you can maintain exact dependencies
1762e8d8bef9SDimitry Andric // easily.
1763e8d8bef9SDimitry Andric static void writeDependencyFile() {
1764e8d8bef9SDimitry Andric   std::error_code ec;
1765fe6060f1SDimitry Andric   raw_fd_ostream os(config->dependencyFile, ec, sys::fs::OF_None);
1766e8d8bef9SDimitry Andric   if (ec) {
1767e8d8bef9SDimitry Andric     error("cannot open " + config->dependencyFile + ": " + ec.message());
1768e8d8bef9SDimitry Andric     return;
1769e8d8bef9SDimitry Andric   }
1770e8d8bef9SDimitry Andric 
1771e8d8bef9SDimitry Andric   // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
1772e8d8bef9SDimitry Andric   // * A space is escaped by a backslash which itself must be escaped.
1773e8d8bef9SDimitry Andric   // * A hash sign is escaped by a single backslash.
1774e8d8bef9SDimitry Andric   // * $ is escapes as $$.
1775e8d8bef9SDimitry Andric   auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
1776e8d8bef9SDimitry Andric     llvm::SmallString<256> nativePath;
1777e8d8bef9SDimitry Andric     llvm::sys::path::native(filename.str(), nativePath);
1778e8d8bef9SDimitry Andric     llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
1779e8d8bef9SDimitry Andric     for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
1780e8d8bef9SDimitry Andric       if (nativePath[i] == '#') {
1781e8d8bef9SDimitry Andric         os << '\\';
1782e8d8bef9SDimitry Andric       } else if (nativePath[i] == ' ') {
1783e8d8bef9SDimitry Andric         os << '\\';
1784e8d8bef9SDimitry Andric         unsigned j = i;
1785e8d8bef9SDimitry Andric         while (j > 0 && nativePath[--j] == '\\')
1786e8d8bef9SDimitry Andric           os << '\\';
1787e8d8bef9SDimitry Andric       } else if (nativePath[i] == '$') {
1788e8d8bef9SDimitry Andric         os << '$';
1789e8d8bef9SDimitry Andric       }
1790e8d8bef9SDimitry Andric       os << nativePath[i];
1791e8d8bef9SDimitry Andric     }
1792e8d8bef9SDimitry Andric   };
1793e8d8bef9SDimitry Andric 
1794e8d8bef9SDimitry Andric   os << config->outputFile << ":";
1795e8d8bef9SDimitry Andric   for (StringRef path : config->dependencyFiles) {
1796e8d8bef9SDimitry Andric     os << " \\\n ";
1797e8d8bef9SDimitry Andric     printFilename(os, path);
1798e8d8bef9SDimitry Andric   }
1799e8d8bef9SDimitry Andric   os << "\n";
1800e8d8bef9SDimitry Andric 
1801e8d8bef9SDimitry Andric   for (StringRef path : config->dependencyFiles) {
1802e8d8bef9SDimitry Andric     os << "\n";
1803e8d8bef9SDimitry Andric     printFilename(os, path);
1804e8d8bef9SDimitry Andric     os << ":\n";
1805e8d8bef9SDimitry Andric   }
1806e8d8bef9SDimitry Andric }
1807e8d8bef9SDimitry Andric 
18080b57cec5SDimitry Andric // Replaces common symbols with defined symbols reside in .bss sections.
18090b57cec5SDimitry Andric // This function is called after all symbol names are resolved. As a
18100b57cec5SDimitry Andric // result, the passes after the symbol resolution won't see any
18110b57cec5SDimitry Andric // symbols of type CommonSymbol.
18120b57cec5SDimitry Andric static void replaceCommonSymbols() {
1813e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Replace common symbols");
18140eae32dcSDimitry Andric   for (ELFFileBase *file : objectFiles) {
18150eae32dcSDimitry Andric     if (!file->hasCommonSyms)
18160eae32dcSDimitry Andric       continue;
18170eae32dcSDimitry Andric     for (Symbol *sym : file->getGlobalSymbols()) {
18180b57cec5SDimitry Andric       auto *s = dyn_cast<CommonSymbol>(sym);
18190b57cec5SDimitry Andric       if (!s)
1820480093f4SDimitry Andric         continue;
18210b57cec5SDimitry Andric 
18220b57cec5SDimitry Andric       auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
18230b57cec5SDimitry Andric       bss->file = s->file;
18240b57cec5SDimitry Andric       bss->markDead();
18250b57cec5SDimitry Andric       inputSections.push_back(bss);
18260b57cec5SDimitry Andric       s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
18270b57cec5SDimitry Andric                          /*value=*/0, s->size, bss});
1828480093f4SDimitry Andric     }
18290b57cec5SDimitry Andric   }
18300eae32dcSDimitry Andric }
18310b57cec5SDimitry Andric 
18320b57cec5SDimitry Andric // If all references to a DSO happen to be weak, the DSO is not added
18330b57cec5SDimitry Andric // to DT_NEEDED. If that happens, we need to eliminate shared symbols
18340b57cec5SDimitry Andric // created from the DSO. Otherwise, they become dangling references
18350b57cec5SDimitry Andric // that point to a non-existent DSO.
18360b57cec5SDimitry Andric static void demoteSharedSymbols() {
1837e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Demote shared symbols");
1838480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols()) {
18390b57cec5SDimitry Andric     auto *s = dyn_cast<SharedSymbol>(sym);
1840*04eeddc0SDimitry Andric     if (!(s && !s->getFile().isNeeded) && !sym->isLazy())
1841480093f4SDimitry Andric       continue;
18420b57cec5SDimitry Andric 
1843349cc55cSDimitry Andric     bool used = sym->used;
1844349cc55cSDimitry Andric     sym->replace(
1845349cc55cSDimitry Andric         Undefined{nullptr, sym->getName(), STB_WEAK, sym->stOther, sym->type});
1846349cc55cSDimitry Andric     sym->used = used;
1847349cc55cSDimitry Andric     sym->versionId = VER_NDX_GLOBAL;
1848480093f4SDimitry Andric   }
18490b57cec5SDimitry Andric }
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric // The section referred to by `s` is considered address-significant. Set the
18520b57cec5SDimitry Andric // keepUnique flag on the section if appropriate.
18530b57cec5SDimitry Andric static void markAddrsig(Symbol *s) {
18540b57cec5SDimitry Andric   if (auto *d = dyn_cast_or_null<Defined>(s))
18550b57cec5SDimitry Andric     if (d->section)
18560b57cec5SDimitry Andric       // We don't need to keep text sections unique under --icf=all even if they
18570b57cec5SDimitry Andric       // are address-significant.
18580b57cec5SDimitry Andric       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
18590b57cec5SDimitry Andric         d->section->keepUnique = true;
18600b57cec5SDimitry Andric }
18610b57cec5SDimitry Andric 
18620b57cec5SDimitry Andric // Record sections that define symbols mentioned in --keep-unique <symbol>
18630b57cec5SDimitry Andric // and symbols referred to by address-significance tables. These sections are
18640b57cec5SDimitry Andric // ineligible for ICF.
18650b57cec5SDimitry Andric template <class ELFT>
18660b57cec5SDimitry Andric static void findKeepUniqueSections(opt::InputArgList &args) {
18670b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_keep_unique)) {
18680b57cec5SDimitry Andric     StringRef name = arg->getValue();
18690b57cec5SDimitry Andric     auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
18700b57cec5SDimitry Andric     if (!d || !d->section) {
18710b57cec5SDimitry Andric       warn("could not find symbol " + name + " to keep unique");
18720b57cec5SDimitry Andric       continue;
18730b57cec5SDimitry Andric     }
18740b57cec5SDimitry Andric     d->section->keepUnique = true;
18750b57cec5SDimitry Andric   }
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   // --icf=all --ignore-data-address-equality means that we can ignore
18780b57cec5SDimitry Andric   // the dynsym and address-significance tables entirely.
18790b57cec5SDimitry Andric   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
18800b57cec5SDimitry Andric     return;
18810b57cec5SDimitry Andric 
18820b57cec5SDimitry Andric   // Symbols in the dynsym could be address-significant in other executables
18830b57cec5SDimitry Andric   // or DSOs, so we conservatively mark them as address-significant.
1884480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols())
18850b57cec5SDimitry Andric     if (sym->includeInDynsym())
18860b57cec5SDimitry Andric       markAddrsig(sym);
18870b57cec5SDimitry Andric 
18880b57cec5SDimitry Andric   // Visit the address-significance table in each object file and mark each
18890b57cec5SDimitry Andric   // referenced symbol as address-significant.
18900b57cec5SDimitry Andric   for (InputFile *f : objectFiles) {
18910b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(f);
18920b57cec5SDimitry Andric     ArrayRef<Symbol *> syms = obj->getSymbols();
18930b57cec5SDimitry Andric     if (obj->addrsigSec) {
18940b57cec5SDimitry Andric       ArrayRef<uint8_t> contents =
1895e8d8bef9SDimitry Andric           check(obj->getObj().getSectionContents(*obj->addrsigSec));
18960b57cec5SDimitry Andric       const uint8_t *cur = contents.begin();
18970b57cec5SDimitry Andric       while (cur != contents.end()) {
18980b57cec5SDimitry Andric         unsigned size;
18990b57cec5SDimitry Andric         const char *err;
19000b57cec5SDimitry Andric         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
19010b57cec5SDimitry Andric         if (err)
19020b57cec5SDimitry Andric           fatal(toString(f) + ": could not decode addrsig section: " + err);
19030b57cec5SDimitry Andric         markAddrsig(syms[symIndex]);
19040b57cec5SDimitry Andric         cur += size;
19050b57cec5SDimitry Andric       }
19060b57cec5SDimitry Andric     } else {
19070b57cec5SDimitry Andric       // If an object file does not have an address-significance table,
19080b57cec5SDimitry Andric       // conservatively mark all of its symbols as address-significant.
19090b57cec5SDimitry Andric       for (Symbol *s : syms)
19100b57cec5SDimitry Andric         markAddrsig(s);
19110b57cec5SDimitry Andric     }
19120b57cec5SDimitry Andric   }
19130b57cec5SDimitry Andric }
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric // This function reads a symbol partition specification section. These sections
19160b57cec5SDimitry Andric // are used to control which partition a symbol is allocated to. See
19170b57cec5SDimitry Andric // https://lld.llvm.org/Partitions.html for more details on partitions.
19180b57cec5SDimitry Andric template <typename ELFT>
19190b57cec5SDimitry Andric static void readSymbolPartitionSection(InputSectionBase *s) {
19200b57cec5SDimitry Andric   // Read the relocation that refers to the partition's entry point symbol.
19210b57cec5SDimitry Andric   Symbol *sym;
1922349cc55cSDimitry Andric   const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
1923349cc55cSDimitry Andric   if (rels.areRelocsRel())
1924349cc55cSDimitry Andric     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]);
19250b57cec5SDimitry Andric   else
1926349cc55cSDimitry Andric     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]);
19270b57cec5SDimitry Andric   if (!isa<Defined>(sym) || !sym->includeInDynsym())
19280b57cec5SDimitry Andric     return;
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric   StringRef partName = reinterpret_cast<const char *>(s->data().data());
19310b57cec5SDimitry Andric   for (Partition &part : partitions) {
19320b57cec5SDimitry Andric     if (part.name == partName) {
19330b57cec5SDimitry Andric       sym->partition = part.getNumber();
19340b57cec5SDimitry Andric       return;
19350b57cec5SDimitry Andric     }
19360b57cec5SDimitry Andric   }
19370b57cec5SDimitry Andric 
19380b57cec5SDimitry Andric   // Forbid partitions from being used on incompatible targets, and forbid them
19390b57cec5SDimitry Andric   // from being used together with various linker features that assume a single
19400b57cec5SDimitry Andric   // set of output sections.
19410b57cec5SDimitry Andric   if (script->hasSectionsCommand)
19420b57cec5SDimitry Andric     error(toString(s->file) +
19430b57cec5SDimitry Andric           ": partitions cannot be used with the SECTIONS command");
19440b57cec5SDimitry Andric   if (script->hasPhdrsCommands())
19450b57cec5SDimitry Andric     error(toString(s->file) +
19460b57cec5SDimitry Andric           ": partitions cannot be used with the PHDRS command");
19470b57cec5SDimitry Andric   if (!config->sectionStartMap.empty())
19480b57cec5SDimitry Andric     error(toString(s->file) + ": partitions cannot be used with "
19490b57cec5SDimitry Andric                               "--section-start, -Ttext, -Tdata or -Tbss");
19500b57cec5SDimitry Andric   if (config->emachine == EM_MIPS)
19510b57cec5SDimitry Andric     error(toString(s->file) + ": partitions cannot be used on this target");
19520b57cec5SDimitry Andric 
19530b57cec5SDimitry Andric   // Impose a limit of no more than 254 partitions. This limit comes from the
19540b57cec5SDimitry Andric   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
19550b57cec5SDimitry Andric   // the amount of space devoted to the partition number in RankFlags.
19560b57cec5SDimitry Andric   if (partitions.size() == 254)
19570b57cec5SDimitry Andric     fatal("may not have more than 254 partitions");
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric   partitions.emplace_back();
19600b57cec5SDimitry Andric   Partition &newPart = partitions.back();
19610b57cec5SDimitry Andric   newPart.name = partName;
19620b57cec5SDimitry Andric   sym->partition = newPart.getNumber();
19630b57cec5SDimitry Andric }
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric static Symbol *addUndefined(StringRef name) {
19660b57cec5SDimitry Andric   return symtab->addSymbol(
19670b57cec5SDimitry Andric       Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
19680b57cec5SDimitry Andric }
19690b57cec5SDimitry Andric 
1970fe6060f1SDimitry Andric static Symbol *addUnusedUndefined(StringRef name,
1971fe6060f1SDimitry Andric                                   uint8_t binding = STB_GLOBAL) {
1972fe6060f1SDimitry Andric   Undefined sym{nullptr, name, binding, STV_DEFAULT, 0};
19735ffd83dbSDimitry Andric   sym.isUsedInRegularObj = false;
19745ffd83dbSDimitry Andric   return symtab->addSymbol(sym);
19755ffd83dbSDimitry Andric }
19765ffd83dbSDimitry Andric 
1977*04eeddc0SDimitry Andric static void markBuffersAsDontNeed(bool skipLinkedOutput) {
1978*04eeddc0SDimitry Andric   // With --thinlto-index-only, all buffers are nearly unused from now on
1979*04eeddc0SDimitry Andric   // (except symbol/section names used by infrequent passes). Mark input file
1980*04eeddc0SDimitry Andric   // buffers as MADV_DONTNEED so that these pages can be reused by the expensive
1981*04eeddc0SDimitry Andric   // thin link, saving memory.
1982*04eeddc0SDimitry Andric   if (skipLinkedOutput) {
1983*04eeddc0SDimitry Andric     for (MemoryBuffer &mb : llvm::make_pointee_range(memoryBuffers))
1984*04eeddc0SDimitry Andric       mb.dontNeedIfMmap();
1985*04eeddc0SDimitry Andric     return;
1986*04eeddc0SDimitry Andric   }
1987*04eeddc0SDimitry Andric 
1988*04eeddc0SDimitry Andric   // Otherwise, just mark MemoryBuffers backing BitcodeFiles.
1989*04eeddc0SDimitry Andric   DenseSet<const char *> bufs;
1990*04eeddc0SDimitry Andric   for (BitcodeFile *file : bitcodeFiles)
1991*04eeddc0SDimitry Andric     bufs.insert(file->mb.getBufferStart());
1992*04eeddc0SDimitry Andric   for (BitcodeFile *file : lazyBitcodeFiles)
1993*04eeddc0SDimitry Andric     bufs.insert(file->mb.getBufferStart());
1994*04eeddc0SDimitry Andric   for (MemoryBuffer &mb : llvm::make_pointee_range(memoryBuffers))
1995*04eeddc0SDimitry Andric     if (bufs.count(mb.getBufferStart()))
1996*04eeddc0SDimitry Andric       mb.dontNeedIfMmap();
1997*04eeddc0SDimitry Andric }
1998*04eeddc0SDimitry Andric 
19990b57cec5SDimitry Andric // This function is where all the optimizations of link-time
20000b57cec5SDimitry Andric // optimization takes place. When LTO is in use, some input files are
20010b57cec5SDimitry Andric // not in native object file format but in the LLVM bitcode format.
20020b57cec5SDimitry Andric // This function compiles bitcode files into a few big native files
20030b57cec5SDimitry Andric // using LLVM functions and replaces bitcode symbols with the results.
20040b57cec5SDimitry Andric // Because all bitcode files that the program consists of are passed to
20050b57cec5SDimitry Andric // the compiler at once, it can do a whole-program optimization.
2006*04eeddc0SDimitry Andric template <class ELFT>
2007*04eeddc0SDimitry Andric void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) {
20085ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("LTO");
20090b57cec5SDimitry Andric   // Compile bitcode files and replace bitcode symbols.
20100b57cec5SDimitry Andric   lto.reset(new BitcodeCompiler);
20110b57cec5SDimitry Andric   for (BitcodeFile *file : bitcodeFiles)
20120b57cec5SDimitry Andric     lto->add(*file);
20130b57cec5SDimitry Andric 
2014*04eeddc0SDimitry Andric   if (!bitcodeFiles.empty())
2015*04eeddc0SDimitry Andric     markBuffersAsDontNeed(skipLinkedOutput);
2016*04eeddc0SDimitry Andric 
20170b57cec5SDimitry Andric   for (InputFile *file : lto->compile()) {
20180b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(file);
20190b57cec5SDimitry Andric     obj->parse(/*ignoreComdats=*/true);
20205ffd83dbSDimitry Andric 
20215ffd83dbSDimitry Andric     // Parse '@' in symbol names for non-relocatable output.
20225ffd83dbSDimitry Andric     if (!config->relocatable)
20230b57cec5SDimitry Andric       for (Symbol *sym : obj->getGlobalSymbols())
2024*04eeddc0SDimitry Andric         if (sym->hasVersionSuffix)
20250b57cec5SDimitry Andric           sym->parseSymbolVersion();
20260eae32dcSDimitry Andric     objectFiles.push_back(obj);
20270b57cec5SDimitry Andric   }
20280b57cec5SDimitry Andric }
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric // The --wrap option is a feature to rename symbols so that you can write
2031349cc55cSDimitry Andric // wrappers for existing functions. If you pass `--wrap=foo`, all
2032e8d8bef9SDimitry Andric // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
2033e8d8bef9SDimitry Andric // expected to write `__wrap_foo` function as a wrapper). The original
2034e8d8bef9SDimitry Andric // symbol becomes accessible as `__real_foo`, so you can call that from your
20350b57cec5SDimitry Andric // wrapper.
20360b57cec5SDimitry Andric //
2037349cc55cSDimitry Andric // This data structure is instantiated for each --wrap option.
20380b57cec5SDimitry Andric struct WrappedSymbol {
20390b57cec5SDimitry Andric   Symbol *sym;
20400b57cec5SDimitry Andric   Symbol *real;
20410b57cec5SDimitry Andric   Symbol *wrap;
20420b57cec5SDimitry Andric };
20430b57cec5SDimitry Andric 
2044349cc55cSDimitry Andric // Handles --wrap option.
20450b57cec5SDimitry Andric //
20460b57cec5SDimitry Andric // This function instantiates wrapper symbols. At this point, they seem
20470b57cec5SDimitry Andric // like they are not being used at all, so we explicitly set some flags so
20480b57cec5SDimitry Andric // that LTO won't eliminate them.
20490b57cec5SDimitry Andric static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
20500b57cec5SDimitry Andric   std::vector<WrappedSymbol> v;
20510b57cec5SDimitry Andric   DenseSet<StringRef> seen;
20520b57cec5SDimitry Andric 
20530b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wrap)) {
20540b57cec5SDimitry Andric     StringRef name = arg->getValue();
20550b57cec5SDimitry Andric     if (!seen.insert(name).second)
20560b57cec5SDimitry Andric       continue;
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric     Symbol *sym = symtab->find(name);
20590b57cec5SDimitry Andric     if (!sym)
20600b57cec5SDimitry Andric       continue;
20610b57cec5SDimitry Andric 
2062*04eeddc0SDimitry Andric     Symbol *real = addUnusedUndefined(saver().save("__real_" + name));
2063fe6060f1SDimitry Andric     Symbol *wrap =
2064*04eeddc0SDimitry Andric         addUnusedUndefined(saver().save("__wrap_" + name), sym->binding);
20650b57cec5SDimitry Andric     v.push_back({sym, real, wrap});
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric     // We want to tell LTO not to inline symbols to be overwritten
20680b57cec5SDimitry Andric     // because LTO doesn't know the final symbol contents after renaming.
20690b57cec5SDimitry Andric     real->canInline = false;
20700b57cec5SDimitry Andric     sym->canInline = false;
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric     // Tell LTO not to eliminate these symbols.
20730b57cec5SDimitry Andric     sym->isUsedInRegularObj = true;
2074e8d8bef9SDimitry Andric     // If sym is referenced in any object file, bitcode file or shared object,
2075e8d8bef9SDimitry Andric     // retain wrap which is the redirection target of sym. If the object file
2076e8d8bef9SDimitry Andric     // defining sym has sym references, we cannot easily distinguish the case
2077e8d8bef9SDimitry Andric     // from cases where sym is not referenced. Retain wrap because we choose to
2078e8d8bef9SDimitry Andric     // wrap sym references regardless of whether sym is defined
2079e8d8bef9SDimitry Andric     // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
2080e8d8bef9SDimitry Andric     if (sym->referenced || sym->isDefined())
20810b57cec5SDimitry Andric       wrap->isUsedInRegularObj = true;
20820b57cec5SDimitry Andric   }
20830b57cec5SDimitry Andric   return v;
20840b57cec5SDimitry Andric }
20850b57cec5SDimitry Andric 
2086349cc55cSDimitry Andric // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
20870b57cec5SDimitry Andric //
20880b57cec5SDimitry Andric // When this function is executed, only InputFiles and symbol table
20890b57cec5SDimitry Andric // contain pointers to symbol objects. We visit them to replace pointers,
20900b57cec5SDimitry Andric // so that wrapped symbols are swapped as instructed by the command line.
2091e8d8bef9SDimitry Andric static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) {
2092e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Redirect symbols");
20930b57cec5SDimitry Andric   DenseMap<Symbol *, Symbol *> map;
20940b57cec5SDimitry Andric   for (const WrappedSymbol &w : wrapped) {
20950b57cec5SDimitry Andric     map[w.sym] = w.wrap;
20960b57cec5SDimitry Andric     map[w.real] = w.sym;
20970b57cec5SDimitry Andric   }
2098e8d8bef9SDimitry Andric   for (Symbol *sym : symtab->symbols()) {
2099*04eeddc0SDimitry Andric     // Enumerate symbols with a non-default version (foo@v1). hasVersionSuffix
2100*04eeddc0SDimitry Andric     // filters out most symbols but is not sufficient.
2101*04eeddc0SDimitry Andric     if (!sym->hasVersionSuffix)
2102*04eeddc0SDimitry Andric       continue;
2103e8d8bef9SDimitry Andric     const char *suffix1 = sym->getVersionSuffix();
2104e8d8bef9SDimitry Andric     if (suffix1[0] != '@' || suffix1[1] == '@')
2105e8d8bef9SDimitry Andric       continue;
2106e8d8bef9SDimitry Andric 
21076e75b2fbSDimitry Andric     // Check the existing symbol foo. We have two special cases to handle:
21086e75b2fbSDimitry Andric     //
21096e75b2fbSDimitry Andric     // * There is a definition of foo@v1 and foo@@v1.
21106e75b2fbSDimitry Andric     // * There is a definition of foo@v1 and foo.
2111*04eeddc0SDimitry Andric     Defined *sym2 = dyn_cast_or_null<Defined>(symtab->find(sym->getName()));
21126e75b2fbSDimitry Andric     if (!sym2)
2113e8d8bef9SDimitry Andric       continue;
21146e75b2fbSDimitry Andric     const char *suffix2 = sym2->getVersionSuffix();
21156e75b2fbSDimitry Andric     if (suffix2[0] == '@' && suffix2[1] == '@' &&
21166e75b2fbSDimitry Andric         strcmp(suffix1 + 1, suffix2 + 2) == 0) {
2117e8d8bef9SDimitry Andric       // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
21186e75b2fbSDimitry Andric       map.try_emplace(sym, sym2);
2119e8d8bef9SDimitry Andric       // If both foo@v1 and foo@@v1 are defined and non-weak, report a duplicate
2120e8d8bef9SDimitry Andric       // definition error.
21216e75b2fbSDimitry Andric       sym2->resolve(*sym);
2122e8d8bef9SDimitry Andric       // Eliminate foo@v1 from the symbol table.
2123e8d8bef9SDimitry Andric       sym->symbolKind = Symbol::PlaceholderKind;
2124*04eeddc0SDimitry Andric       sym->isUsedInRegularObj = false;
21256e75b2fbSDimitry Andric     } else if (auto *sym1 = dyn_cast<Defined>(sym)) {
21266e75b2fbSDimitry Andric       if (sym2->versionId > VER_NDX_GLOBAL
21276e75b2fbSDimitry Andric               ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1
21286e75b2fbSDimitry Andric               : sym1->section == sym2->section && sym1->value == sym2->value) {
21296e75b2fbSDimitry Andric         // Due to an assembler design flaw, if foo is defined, .symver foo,
21306e75b2fbSDimitry Andric         // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2131349cc55cSDimitry Andric         // different version, GNU ld makes foo@v1 canonical and eliminates foo.
21326e75b2fbSDimitry Andric         // Emulate its behavior, otherwise we would have foo or foo@@v1 beside
21336e75b2fbSDimitry Andric         // foo@v1. foo@v1 and foo combining does not apply if they are not
21346e75b2fbSDimitry Andric         // defined in the same place.
21356e75b2fbSDimitry Andric         map.try_emplace(sym2, sym);
21366e75b2fbSDimitry Andric         sym2->symbolKind = Symbol::PlaceholderKind;
2137*04eeddc0SDimitry Andric         sym2->isUsedInRegularObj = false;
21386e75b2fbSDimitry Andric       }
21396e75b2fbSDimitry Andric     }
2140e8d8bef9SDimitry Andric   }
2141e8d8bef9SDimitry Andric 
2142e8d8bef9SDimitry Andric   if (map.empty())
2143e8d8bef9SDimitry Andric     return;
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric   // Update pointers in input files.
21460eae32dcSDimitry Andric   parallelForEach(objectFiles, [&](ELFFileBase *file) {
21470eae32dcSDimitry Andric     for (Symbol *&sym : file->getMutableGlobalSymbols())
21480eae32dcSDimitry Andric       if (Symbol *s = map.lookup(sym))
21490eae32dcSDimitry Andric         sym = s;
21500b57cec5SDimitry Andric   });
21510b57cec5SDimitry Andric 
21520b57cec5SDimitry Andric   // Update pointers in the symbol table.
21530b57cec5SDimitry Andric   for (const WrappedSymbol &w : wrapped)
21540b57cec5SDimitry Andric     symtab->wrap(w.sym, w.real, w.wrap);
21550b57cec5SDimitry Andric }
21560b57cec5SDimitry Andric 
21570eae32dcSDimitry Andric static void checkAndReportMissingFeature(StringRef config, uint32_t features,
21580eae32dcSDimitry Andric                                          uint32_t mask, const Twine &report) {
21590eae32dcSDimitry Andric   if (!(features & mask)) {
21600eae32dcSDimitry Andric     if (config == "error")
21610eae32dcSDimitry Andric       error(report);
21620eae32dcSDimitry Andric     else if (config == "warning")
21630eae32dcSDimitry Andric       warn(report);
21640eae32dcSDimitry Andric   }
21650eae32dcSDimitry Andric }
21660eae32dcSDimitry Andric 
21670b57cec5SDimitry Andric // To enable CET (x86's hardware-assited control flow enforcement), each
21680b57cec5SDimitry Andric // source file must be compiled with -fcf-protection. Object files compiled
21690b57cec5SDimitry Andric // with the flag contain feature flags indicating that they are compatible
21700b57cec5SDimitry Andric // with CET. We enable the feature only when all object files are compatible
21710b57cec5SDimitry Andric // with CET.
21720b57cec5SDimitry Andric //
21730b57cec5SDimitry Andric // This is also the case with AARCH64's BTI and PAC which use the similar
21740b57cec5SDimitry Andric // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
21750b57cec5SDimitry Andric template <class ELFT> static uint32_t getAndFeatures() {
21760b57cec5SDimitry Andric   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
21770b57cec5SDimitry Andric       config->emachine != EM_AARCH64)
21780b57cec5SDimitry Andric     return 0;
21790b57cec5SDimitry Andric 
21800b57cec5SDimitry Andric   uint32_t ret = -1;
21810b57cec5SDimitry Andric   for (InputFile *f : objectFiles) {
21820b57cec5SDimitry Andric     uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
21830eae32dcSDimitry Andric 
21840eae32dcSDimitry Andric     checkAndReportMissingFeature(
21850eae32dcSDimitry Andric         config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI,
21860eae32dcSDimitry Andric         toString(f) + ": -z bti-report: file does not have "
21870eae32dcSDimitry Andric                       "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
21880eae32dcSDimitry Andric 
21890eae32dcSDimitry Andric     checkAndReportMissingFeature(
21900eae32dcSDimitry Andric         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT,
21910eae32dcSDimitry Andric         toString(f) + ": -z cet-report: file does not have "
21920eae32dcSDimitry Andric                       "GNU_PROPERTY_X86_FEATURE_1_IBT property");
21930eae32dcSDimitry Andric 
21940eae32dcSDimitry Andric     checkAndReportMissingFeature(
21950eae32dcSDimitry Andric         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK,
21960eae32dcSDimitry Andric         toString(f) + ": -z cet-report: file does not have "
21970eae32dcSDimitry Andric                       "GNU_PROPERTY_X86_FEATURE_1_SHSTK property");
21980eae32dcSDimitry Andric 
21995ffd83dbSDimitry Andric     if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
22000eae32dcSDimitry Andric       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
22010eae32dcSDimitry Andric       if (config->zBtiReport == "none")
22025ffd83dbSDimitry Andric         warn(toString(f) + ": -z force-bti: file does not have "
22035ffd83dbSDimitry Andric                            "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2204480093f4SDimitry Andric     } else if (config->zForceIbt &&
2205480093f4SDimitry Andric                !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
22060eae32dcSDimitry Andric       if (config->zCetReport == "none")
2207480093f4SDimitry Andric         warn(toString(f) + ": -z force-ibt: file does not have "
2208480093f4SDimitry Andric                            "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2209480093f4SDimitry Andric       features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
2210480093f4SDimitry Andric     }
22115ffd83dbSDimitry Andric     if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
22125ffd83dbSDimitry Andric       warn(toString(f) + ": -z pac-plt: file does not have "
22135ffd83dbSDimitry Andric                          "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
22145ffd83dbSDimitry Andric       features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
22155ffd83dbSDimitry Andric     }
22160b57cec5SDimitry Andric     ret &= features;
22170b57cec5SDimitry Andric   }
22180b57cec5SDimitry Andric 
2219480093f4SDimitry Andric   // Force enable Shadow Stack.
2220480093f4SDimitry Andric   if (config->zShstk)
2221480093f4SDimitry Andric     ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric   return ret;
22240b57cec5SDimitry Andric }
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric // Do actual linking. Note that when this function is called,
22270b57cec5SDimitry Andric // all linker scripts have already been parsed.
22280b57cec5SDimitry Andric template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
22295ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
2230349cc55cSDimitry Andric   // If a --hash-style option was not given, set to a default value,
22310b57cec5SDimitry Andric   // which varies depending on the target.
22320b57cec5SDimitry Andric   if (!args.hasArg(OPT_hash_style)) {
22330b57cec5SDimitry Andric     if (config->emachine == EM_MIPS)
22340b57cec5SDimitry Andric       config->sysvHash = true;
22350b57cec5SDimitry Andric     else
22360b57cec5SDimitry Andric       config->sysvHash = config->gnuHash = true;
22370b57cec5SDimitry Andric   }
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric   // Default output filename is "a.out" by the Unix tradition.
22400b57cec5SDimitry Andric   if (config->outputFile.empty())
22410b57cec5SDimitry Andric     config->outputFile = "a.out";
22420b57cec5SDimitry Andric 
22430b57cec5SDimitry Andric   // Fail early if the output file or map file is not writable. If a user has a
22440b57cec5SDimitry Andric   // long link, e.g. due to a large LTO link, they do not wish to run it and
22450b57cec5SDimitry Andric   // find that it failed because there was a mistake in their command-line.
2246e8d8bef9SDimitry Andric   {
2247e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Create output files");
22480b57cec5SDimitry Andric     if (auto e = tryCreateFile(config->outputFile))
2249e8d8bef9SDimitry Andric       error("cannot open output file " + config->outputFile + ": " +
2250e8d8bef9SDimitry Andric             e.message());
22510b57cec5SDimitry Andric     if (auto e = tryCreateFile(config->mapFile))
22520b57cec5SDimitry Andric       error("cannot open map file " + config->mapFile + ": " + e.message());
2253349cc55cSDimitry Andric     if (auto e = tryCreateFile(config->whyExtract))
2254349cc55cSDimitry Andric       error("cannot open --why-extract= file " + config->whyExtract + ": " +
2255349cc55cSDimitry Andric             e.message());
2256e8d8bef9SDimitry Andric   }
22570b57cec5SDimitry Andric   if (errorCount())
22580b57cec5SDimitry Andric     return;
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric   // Use default entry point name if no name was given via the command
22610b57cec5SDimitry Andric   // line nor linker scripts. For some reason, MIPS entry point name is
22620b57cec5SDimitry Andric   // different from others.
22630b57cec5SDimitry Andric   config->warnMissingEntry =
22640b57cec5SDimitry Andric       (!config->entry.empty() || (!config->shared && !config->relocatable));
22650b57cec5SDimitry Andric   if (config->entry.empty() && !config->relocatable)
22660b57cec5SDimitry Andric     config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric   // Handle --trace-symbol.
22690b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_trace_symbol))
22700b57cec5SDimitry Andric     symtab->insert(arg->getValue())->traced = true;
22710b57cec5SDimitry Andric 
22725ffd83dbSDimitry Andric   // Handle -u/--undefined before input files. If both a.a and b.so define foo,
22734824e7fdSDimitry Andric   // -u foo a.a b.so will extract a.a.
22745ffd83dbSDimitry Andric   for (StringRef name : config->undefined)
2275e8d8bef9SDimitry Andric     addUnusedUndefined(name)->referenced = true;
22765ffd83dbSDimitry Andric 
22770b57cec5SDimitry Andric   // Add all files to the symbol table. This will add almost all
22780b57cec5SDimitry Andric   // symbols that we need to the symbol table. This process might
22790b57cec5SDimitry Andric   // add files to the link, via autolinking, these files are always
22800b57cec5SDimitry Andric   // appended to the Files vector.
22815ffd83dbSDimitry Andric   {
22825ffd83dbSDimitry Andric     llvm::TimeTraceScope timeScope("Parse input files");
2283e8d8bef9SDimitry Andric     for (size_t i = 0; i < files.size(); ++i) {
2284e8d8bef9SDimitry Andric       llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
22850b57cec5SDimitry Andric       parseFile(files[i]);
22865ffd83dbSDimitry Andric     }
2287e8d8bef9SDimitry Andric   }
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric   // Now that we have every file, we can decide if we will need a
22900b57cec5SDimitry Andric   // dynamic symbol table.
22910b57cec5SDimitry Andric   // We need one if we were asked to export dynamic symbols or if we are
22920b57cec5SDimitry Andric   // producing a shared library.
22930b57cec5SDimitry Andric   // We also need one if any shared libraries are used and for pie executables
22940b57cec5SDimitry Andric   // (probably because the dynamic linker needs it).
22950b57cec5SDimitry Andric   config->hasDynSymTab =
22960b57cec5SDimitry Andric       !sharedFiles.empty() || config->isPic || config->exportDynamic;
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric   // Some symbols (such as __ehdr_start) are defined lazily only when there
22990b57cec5SDimitry Andric   // are undefined symbols for them, so we add these to trigger that logic.
23000b57cec5SDimitry Andric   for (StringRef name : script->referencedSymbols)
23010b57cec5SDimitry Andric     addUndefined(name);
23020b57cec5SDimitry Andric 
23035ffd83dbSDimitry Andric   // Prevent LTO from removing any definition referenced by -u.
23045ffd83dbSDimitry Andric   for (StringRef name : config->undefined)
23055ffd83dbSDimitry Andric     if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name)))
23065ffd83dbSDimitry Andric       sym->isUsedInRegularObj = true;
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric   // If an entry symbol is in a static archive, pull out that file now.
23090b57cec5SDimitry Andric   if (Symbol *sym = symtab->find(config->entry))
2310349cc55cSDimitry Andric     handleUndefined(sym, "--entry");
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric   // Handle the `--undefined-glob <pattern>` options.
23130b57cec5SDimitry Andric   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
23140b57cec5SDimitry Andric     handleUndefinedGlob(pat);
23150b57cec5SDimitry Andric 
2316480093f4SDimitry Andric   // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
23175ffd83dbSDimitry Andric   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init)))
2318480093f4SDimitry Andric     sym->isUsedInRegularObj = true;
23195ffd83dbSDimitry Andric   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini)))
2320480093f4SDimitry Andric     sym->isUsedInRegularObj = true;
2321480093f4SDimitry Andric 
23220b57cec5SDimitry Andric   // If any of our inputs are bitcode files, the LTO code generator may create
23230b57cec5SDimitry Andric   // references to certain library functions that might not be explicit in the
23240b57cec5SDimitry Andric   // bitcode file's symbol table. If any of those library functions are defined
23250b57cec5SDimitry Andric   // in a bitcode file in an archive member, we need to arrange to use LTO to
23260b57cec5SDimitry Andric   // compile those archive members by adding them to the link beforehand.
23270b57cec5SDimitry Andric   //
23280b57cec5SDimitry Andric   // However, adding all libcall symbols to the link can have undesired
23290b57cec5SDimitry Andric   // consequences. For example, the libgcc implementation of
23300b57cec5SDimitry Andric   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
23310b57cec5SDimitry Andric   // that aborts the program if the Linux kernel does not support 64-bit
23320b57cec5SDimitry Andric   // atomics, which would prevent the program from running even if it does not
23330b57cec5SDimitry Andric   // use 64-bit atomics.
23340b57cec5SDimitry Andric   //
23350b57cec5SDimitry Andric   // Therefore, we only add libcall symbols to the link before LTO if we have
23360b57cec5SDimitry Andric   // to, i.e. if the symbol's definition is in bitcode. Any other required
23370b57cec5SDimitry Andric   // libcall symbols will be added to the link after LTO when we add the LTO
23380b57cec5SDimitry Andric   // object file to the link.
23390b57cec5SDimitry Andric   if (!bitcodeFiles.empty())
234085868e8aSDimitry Andric     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
23410b57cec5SDimitry Andric       handleLibcall(s);
23420b57cec5SDimitry Andric 
23430b57cec5SDimitry Andric   // Return if there were name resolution errors.
23440b57cec5SDimitry Andric   if (errorCount())
23450b57cec5SDimitry Andric     return;
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric   // We want to declare linker script's symbols early,
23480b57cec5SDimitry Andric   // so that we can version them.
23490b57cec5SDimitry Andric   // They also might be exported if referenced by DSOs.
23500b57cec5SDimitry Andric   script->declareSymbols();
23510b57cec5SDimitry Andric 
2352e8d8bef9SDimitry Andric   // Handle --exclude-libs. This is before scanVersionScript() due to a
2353e8d8bef9SDimitry Andric   // workaround for Android ndk: for a defined versioned symbol in an archive
2354e8d8bef9SDimitry Andric   // without a version node in the version script, Android does not expect a
2355e8d8bef9SDimitry Andric   // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2356e8d8bef9SDimitry Andric   // GNU ld errors in this case.
23570b57cec5SDimitry Andric   if (args.hasArg(OPT_exclude_libs))
23580b57cec5SDimitry Andric     excludeLibs(args);
23590b57cec5SDimitry Andric 
23600b57cec5SDimitry Andric   // Create elfHeader early. We need a dummy section in
23610b57cec5SDimitry Andric   // addReservedSymbols to mark the created symbols as not absolute.
23620b57cec5SDimitry Andric   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric   // We need to create some reserved symbols such as _end. Create them.
23670b57cec5SDimitry Andric   if (!config->relocatable)
23680b57cec5SDimitry Andric     addReservedSymbols();
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric   // Apply version scripts.
23710b57cec5SDimitry Andric   //
23720b57cec5SDimitry Andric   // For a relocatable output, version scripts don't make sense, and
23730b57cec5SDimitry Andric   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
23740b57cec5SDimitry Andric   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2375e8d8bef9SDimitry Andric   if (!config->relocatable) {
2376e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Process symbol versions");
23770b57cec5SDimitry Andric     symtab->scanVersionScript();
2378e8d8bef9SDimitry Andric   }
23790b57cec5SDimitry Andric 
2380*04eeddc0SDimitry Andric   // Skip the normal linked output if some LTO options are specified.
2381*04eeddc0SDimitry Andric   //
2382*04eeddc0SDimitry Andric   // For --thinlto-index-only, index file creation is performed in
2383*04eeddc0SDimitry Andric   // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and
2384*04eeddc0SDimitry Andric   // --plugin-opt=emit-asm create output files in bitcode or assembly code,
2385*04eeddc0SDimitry Andric   // respectively. When only certain thinLTO modules are specified for
2386*04eeddc0SDimitry Andric   // compilation, the intermediate object file are the expected output.
2387*04eeddc0SDimitry Andric   const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM ||
2388*04eeddc0SDimitry Andric                                 config->ltoEmitAsm ||
2389*04eeddc0SDimitry Andric                                 !config->thinLTOModulesToCompile.empty();
2390*04eeddc0SDimitry Andric 
23910b57cec5SDimitry Andric   // Do link-time optimization if given files are LLVM bitcode files.
23920b57cec5SDimitry Andric   // This compiles bitcode files into real object files.
23930b57cec5SDimitry Andric   //
23940b57cec5SDimitry Andric   // With this the symbol table should be complete. After this, no new names
23950b57cec5SDimitry Andric   // except a few linker-synthesized ones will be added to the symbol table.
2396*04eeddc0SDimitry Andric   compileBitcodeFiles<ELFT>(skipLinkedOutput);
2397*04eeddc0SDimitry Andric 
2398*04eeddc0SDimitry Andric   // Symbol resolution finished. Report backward reference problems.
2399*04eeddc0SDimitry Andric   reportBackrefs();
2400*04eeddc0SDimitry Andric   if (errorCount())
2401*04eeddc0SDimitry Andric     return;
2402*04eeddc0SDimitry Andric 
2403*04eeddc0SDimitry Andric   // Bail out if normal linked output is skipped due to LTO.
2404*04eeddc0SDimitry Andric   if (skipLinkedOutput)
2405*04eeddc0SDimitry Andric     return;
24065ffd83dbSDimitry Andric 
2407e8d8bef9SDimitry Andric   // Handle --exclude-libs again because lto.tmp may reference additional
2408e8d8bef9SDimitry Andric   // libcalls symbols defined in an excluded archive. This may override
2409e8d8bef9SDimitry Andric   // versionId set by scanVersionScript().
2410e8d8bef9SDimitry Andric   if (args.hasArg(OPT_exclude_libs))
2411e8d8bef9SDimitry Andric     excludeLibs(args);
2412e8d8bef9SDimitry Andric 
2413349cc55cSDimitry Andric   // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
2414e8d8bef9SDimitry Andric   redirectSymbols(wrapped);
24150b57cec5SDimitry Andric 
2416*04eeddc0SDimitry Andric   // Replace common symbols with regular symbols.
2417*04eeddc0SDimitry Andric   replaceCommonSymbols();
2418*04eeddc0SDimitry Andric 
2419e8d8bef9SDimitry Andric   {
2420e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Aggregate sections");
24210b57cec5SDimitry Andric     // Now that we have a complete list of input files.
24220b57cec5SDimitry Andric     // Beyond this point, no new files are added.
24230b57cec5SDimitry Andric     // Aggregate all input sections into one place.
24240b57cec5SDimitry Andric     for (InputFile *f : objectFiles)
24250b57cec5SDimitry Andric       for (InputSectionBase *s : f->getSections())
24260b57cec5SDimitry Andric         if (s && s != &InputSection::discarded)
24270b57cec5SDimitry Andric           inputSections.push_back(s);
24280b57cec5SDimitry Andric     for (BinaryFile *f : binaryFiles)
24290b57cec5SDimitry Andric       for (InputSectionBase *s : f->getSections())
24300b57cec5SDimitry Andric         inputSections.push_back(cast<InputSection>(s));
2431e8d8bef9SDimitry Andric   }
24320b57cec5SDimitry Andric 
2433e8d8bef9SDimitry Andric   {
2434e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Strip sections");
24350b57cec5SDimitry Andric     llvm::erase_if(inputSections, [](InputSectionBase *s) {
24360b57cec5SDimitry Andric       if (s->type == SHT_LLVM_SYMPART) {
24370b57cec5SDimitry Andric         readSymbolPartitionSection<ELFT>(s);
24380b57cec5SDimitry Andric         return true;
24390b57cec5SDimitry Andric       }
24400b57cec5SDimitry Andric 
24410b57cec5SDimitry Andric       // We do not want to emit debug sections if --strip-all
2442349cc55cSDimitry Andric       // or --strip-debug are given.
2443d65cd7a5SDimitry Andric       if (config->strip == StripPolicy::None)
2444d65cd7a5SDimitry Andric         return false;
2445d65cd7a5SDimitry Andric 
2446d65cd7a5SDimitry Andric       if (isDebugSection(*s))
2447d65cd7a5SDimitry Andric         return true;
2448d65cd7a5SDimitry Andric       if (auto *isec = dyn_cast<InputSection>(s))
2449d65cd7a5SDimitry Andric         if (InputSectionBase *rel = isec->getRelocatedSection())
2450d65cd7a5SDimitry Andric           if (isDebugSection(*rel))
2451d65cd7a5SDimitry Andric             return true;
2452d65cd7a5SDimitry Andric 
2453d65cd7a5SDimitry Andric       return false;
24540b57cec5SDimitry Andric     });
2455e8d8bef9SDimitry Andric   }
2456e8d8bef9SDimitry Andric 
2457e8d8bef9SDimitry Andric   // Since we now have a complete set of input files, we can create
2458e8d8bef9SDimitry Andric   // a .d file to record build dependencies.
2459e8d8bef9SDimitry Andric   if (!config->dependencyFile.empty())
2460e8d8bef9SDimitry Andric     writeDependencyFile();
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric   // Now that the number of partitions is fixed, save a pointer to the main
24630b57cec5SDimitry Andric   // partition.
24640b57cec5SDimitry Andric   mainPart = &partitions[0];
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric   // Read .note.gnu.property sections from input object files which
24670b57cec5SDimitry Andric   // contain a hint to tweak linker's and loader's behaviors.
24680b57cec5SDimitry Andric   config->andFeatures = getAndFeatures<ELFT>();
24690b57cec5SDimitry Andric 
24700b57cec5SDimitry Andric   // The Target instance handles target-specific stuff, such as applying
24710b57cec5SDimitry Andric   // relocations or writing a PLT section. It also contains target-dependent
24720b57cec5SDimitry Andric   // values such as a default image base address.
24730b57cec5SDimitry Andric   target = getTarget();
24740b57cec5SDimitry Andric 
24750b57cec5SDimitry Andric   config->eflags = target->calcEFlags();
24760b57cec5SDimitry Andric   // maxPageSize (sometimes called abi page size) is the maximum page size that
24770b57cec5SDimitry Andric   // the output can be run on. For example if the OS can use 4k or 64k page
24780b57cec5SDimitry Andric   // sizes then maxPageSize must be 64k for the output to be useable on both.
24790b57cec5SDimitry Andric   // All important alignment decisions must use this value.
24800b57cec5SDimitry Andric   config->maxPageSize = getMaxPageSize(args);
24810b57cec5SDimitry Andric   // commonPageSize is the most common page size that the output will be run on.
24820b57cec5SDimitry Andric   // For example if an OS can use 4k or 64k page sizes and 4k is more common
24830b57cec5SDimitry Andric   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
24840b57cec5SDimitry Andric   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
24850b57cec5SDimitry Andric   // is limited to writing trap instructions on the last executable segment.
24860b57cec5SDimitry Andric   config->commonPageSize = getCommonPageSize(args);
24870b57cec5SDimitry Andric 
24880b57cec5SDimitry Andric   config->imageBase = getImageBase(args);
24890b57cec5SDimitry Andric 
24900b57cec5SDimitry Andric   if (config->emachine == EM_ARM) {
24910b57cec5SDimitry Andric     // FIXME: These warnings can be removed when lld only uses these features
24920b57cec5SDimitry Andric     // when the input objects have been compiled with an architecture that
24930b57cec5SDimitry Andric     // supports them.
24940b57cec5SDimitry Andric     if (config->armHasBlx == false)
24950b57cec5SDimitry Andric       warn("lld uses blx instruction, no object with architecture supporting "
24960b57cec5SDimitry Andric            "feature detected");
24970b57cec5SDimitry Andric   }
24980b57cec5SDimitry Andric 
249985868e8aSDimitry Andric   // This adds a .comment section containing a version string.
25000b57cec5SDimitry Andric   if (!config->relocatable)
25010b57cec5SDimitry Andric     inputSections.push_back(createCommentSection());
25020b57cec5SDimitry Andric 
250385868e8aSDimitry Andric   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
25040b57cec5SDimitry Andric   splitSections<ELFT>();
250585868e8aSDimitry Andric 
250685868e8aSDimitry Andric   // Garbage collection and removal of shared symbols from unused shared objects.
25070b57cec5SDimitry Andric   markLive<ELFT>();
25080b57cec5SDimitry Andric   demoteSharedSymbols();
250985868e8aSDimitry Andric 
251085868e8aSDimitry Andric   // Make copies of any input sections that need to be copied into each
251185868e8aSDimitry Andric   // partition.
251285868e8aSDimitry Andric   copySectionsIntoPartitions();
251385868e8aSDimitry Andric 
251485868e8aSDimitry Andric   // Create synthesized sections such as .got and .plt. This is called before
251585868e8aSDimitry Andric   // processSectionCommands() so that they can be placed by SECTIONS commands.
251685868e8aSDimitry Andric   createSyntheticSections<ELFT>();
251785868e8aSDimitry Andric 
251885868e8aSDimitry Andric   // Some input sections that are used for exception handling need to be moved
251985868e8aSDimitry Andric   // into synthetic sections. Do that now so that they aren't assigned to
252085868e8aSDimitry Andric   // output sections in the usual way.
252185868e8aSDimitry Andric   if (!config->relocatable)
252285868e8aSDimitry Andric     combineEhSections();
252385868e8aSDimitry Andric 
2524e8d8bef9SDimitry Andric   {
2525e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Assign sections");
2526e8d8bef9SDimitry Andric 
252785868e8aSDimitry Andric     // Create output sections described by SECTIONS commands.
252885868e8aSDimitry Andric     script->processSectionCommands();
252985868e8aSDimitry Andric 
2530e8d8bef9SDimitry Andric     // Linker scripts control how input sections are assigned to output
2531e8d8bef9SDimitry Andric     // sections. Input sections that were not handled by scripts are called
2532e8d8bef9SDimitry Andric     // "orphans", and they are assigned to output sections by the default rule.
2533e8d8bef9SDimitry Andric     // Process that.
253485868e8aSDimitry Andric     script->addOrphanSections();
2535e8d8bef9SDimitry Andric   }
2536e8d8bef9SDimitry Andric 
2537e8d8bef9SDimitry Andric   {
2538e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Merge/finalize input sections");
253985868e8aSDimitry Andric 
254085868e8aSDimitry Andric     // Migrate InputSectionDescription::sectionBases to sections. This includes
254185868e8aSDimitry Andric     // merging MergeInputSections into a single MergeSyntheticSection. From this
254285868e8aSDimitry Andric     // point onwards InputSectionDescription::sections should be used instead of
254385868e8aSDimitry Andric     // sectionBases.
25444824e7fdSDimitry Andric     for (SectionCommand *cmd : script->sectionCommands)
25454824e7fdSDimitry Andric       if (auto *sec = dyn_cast<OutputSection>(cmd))
254685868e8aSDimitry Andric         sec->finalizeInputSections();
2547e8d8bef9SDimitry Andric     llvm::erase_if(inputSections, [](InputSectionBase *s) {
2548e8d8bef9SDimitry Andric       return isa<MergeInputSection>(s);
2549e8d8bef9SDimitry Andric     });
2550e8d8bef9SDimitry Andric   }
255185868e8aSDimitry Andric 
255285868e8aSDimitry Andric   // Two input sections with different output sections should not be folded.
255385868e8aSDimitry Andric   // ICF runs after processSectionCommands() so that we know the output sections.
25540b57cec5SDimitry Andric   if (config->icf != ICFLevel::None) {
25550b57cec5SDimitry Andric     findKeepUniqueSections<ELFT>(args);
25560b57cec5SDimitry Andric     doIcf<ELFT>();
25570b57cec5SDimitry Andric   }
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric   // Read the callgraph now that we know what was gced or icfed
25600b57cec5SDimitry Andric   if (config->callGraphProfileSort) {
25610b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
25620b57cec5SDimitry Andric       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
25630b57cec5SDimitry Andric         readCallGraph(*buffer);
25640b57cec5SDimitry Andric     readCallGraphsFromObjectFiles<ELFT>();
25650b57cec5SDimitry Andric   }
25660b57cec5SDimitry Andric 
25670b57cec5SDimitry Andric   // Write the result to the file.
25680b57cec5SDimitry Andric   writeResult<ELFT>();
25690b57cec5SDimitry Andric }
2570