xref: /freebsd/contrib/llvm-project/lld/ELF/Driver.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
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 
745ffd83dbSDimitry Andric Configuration *elf::config;
755ffd83dbSDimitry Andric LinkerDriver *elf::driver;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args);
780b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args);
790b57cec5SDimitry Andric 
805ffd83dbSDimitry Andric bool elf::link(ArrayRef<const char *> args, bool canExitEarly,
815ffd83dbSDimitry Andric                raw_ostream &stdoutOS, raw_ostream &stderrOS) {
82480093f4SDimitry Andric   lld::stdoutOS = &stdoutOS;
83480093f4SDimitry Andric   lld::stderrOS = &stderrOS;
84480093f4SDimitry Andric 
85e8d8bef9SDimitry Andric   errorHandler().cleanupCallback = []() {
86e8d8bef9SDimitry Andric     freeArena();
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric     inputSections.clear();
890b57cec5SDimitry Andric     outputSections.clear();
905ffd83dbSDimitry Andric     archiveFiles.clear();
910b57cec5SDimitry Andric     binaryFiles.clear();
920b57cec5SDimitry Andric     bitcodeFiles.clear();
935ffd83dbSDimitry Andric     lazyObjFiles.clear();
940b57cec5SDimitry Andric     objectFiles.clear();
950b57cec5SDimitry Andric     sharedFiles.clear();
965ffd83dbSDimitry Andric     backwardReferences.clear();
97*349cc55cSDimitry Andric     whyExtract.clear();
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric     tar = nullptr;
1000b57cec5SDimitry Andric     memset(&in, 0, sizeof(in));
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric     partitions = {Partition()};
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric     SharedFile::vernauxNum = 0;
105e8d8bef9SDimitry Andric   };
106e8d8bef9SDimitry Andric 
107e8d8bef9SDimitry Andric   errorHandler().logName = args::getFilenameWithoutExe(args[0]);
108e8d8bef9SDimitry Andric   errorHandler().errorLimitExceededMsg =
109e8d8bef9SDimitry Andric       "too many errors emitted, stopping now (use "
110e8d8bef9SDimitry Andric       "-error-limit=0 to see all errors)";
111e8d8bef9SDimitry Andric   errorHandler().exitEarly = canExitEarly;
112e8d8bef9SDimitry Andric   stderrOS.enable_colors(stderrOS.has_colors());
113e8d8bef9SDimitry Andric 
114e8d8bef9SDimitry Andric   config = make<Configuration>();
115e8d8bef9SDimitry Andric   driver = make<LinkerDriver>();
116e8d8bef9SDimitry Andric   script = make<LinkerScript>();
117e8d8bef9SDimitry Andric   symtab = make<SymbolTable>();
118e8d8bef9SDimitry Andric 
119e8d8bef9SDimitry Andric   partitions = {Partition()};
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   config->progName = args[0];
1220b57cec5SDimitry Andric 
123e8d8bef9SDimitry Andric   driver->linkerMain(args);
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   // Exit immediately if we don't need to return to the caller.
1260b57cec5SDimitry Andric   // This saves time because the overhead of calling destructors
1270b57cec5SDimitry Andric   // for all globally-allocated objects is not negligible.
1280b57cec5SDimitry Andric   if (canExitEarly)
1290b57cec5SDimitry Andric     exitLld(errorCount() ? 1 : 0);
1300b57cec5SDimitry Andric 
131e8d8bef9SDimitry Andric   bool ret = errorCount() == 0;
132e8d8bef9SDimitry Andric   if (!canExitEarly)
133e8d8bef9SDimitry Andric     errorHandler().reset();
134e8d8bef9SDimitry Andric   return ret;
1350b57cec5SDimitry Andric }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric // Parses a linker -m option.
1380b57cec5SDimitry Andric static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
1390b57cec5SDimitry Andric   uint8_t osabi = 0;
1400b57cec5SDimitry Andric   StringRef s = emul;
1410b57cec5SDimitry Andric   if (s.endswith("_fbsd")) {
1420b57cec5SDimitry Andric     s = s.drop_back(5);
1430b57cec5SDimitry Andric     osabi = ELFOSABI_FREEBSD;
1440b57cec5SDimitry Andric   }
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   std::pair<ELFKind, uint16_t> ret =
1470b57cec5SDimitry Andric       StringSwitch<std::pair<ELFKind, uint16_t>>(s)
148fe6060f1SDimitry Andric           .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
149fe6060f1SDimitry Andric           .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})
1500b57cec5SDimitry Andric           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
1510b57cec5SDimitry Andric           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
1520b57cec5SDimitry Andric           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
1530b57cec5SDimitry Andric           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
1540b57cec5SDimitry Andric           .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
1550b57cec5SDimitry Andric           .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
156e8d8bef9SDimitry Andric           .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})
1570b57cec5SDimitry Andric           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
1580b57cec5SDimitry Andric           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
1590b57cec5SDimitry Andric           .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
1600b57cec5SDimitry Andric           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
1610b57cec5SDimitry Andric           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
1620b57cec5SDimitry Andric           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
1630b57cec5SDimitry Andric           .Case("elf_i386", {ELF32LEKind, EM_386})
1640b57cec5SDimitry Andric           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
1655ffd83dbSDimitry Andric           .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
166e8d8bef9SDimitry Andric           .Case("msp430elf", {ELF32LEKind, EM_MSP430})
1670b57cec5SDimitry Andric           .Default({ELFNoneKind, EM_NONE});
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   if (ret.first == ELFNoneKind)
1700b57cec5SDimitry Andric     error("unknown emulation: " + emul);
171e8d8bef9SDimitry Andric   if (ret.second == EM_MSP430)
172e8d8bef9SDimitry Andric     osabi = ELFOSABI_STANDALONE;
1730b57cec5SDimitry Andric   return std::make_tuple(ret.first, ret.second, osabi);
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric // Returns slices of MB by parsing MB as an archive file.
1770b57cec5SDimitry Andric // Each slice consists of a member file in the archive.
1780b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
1790b57cec5SDimitry Andric     MemoryBufferRef mb) {
1800b57cec5SDimitry Andric   std::unique_ptr<Archive> file =
1810b57cec5SDimitry Andric       CHECK(Archive::create(mb),
1820b57cec5SDimitry Andric             mb.getBufferIdentifier() + ": failed to parse archive");
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
1850b57cec5SDimitry Andric   Error err = Error::success();
1860b57cec5SDimitry Andric   bool addToTar = file->isThin() && tar;
187480093f4SDimitry Andric   for (const Archive::Child &c : file->children(err)) {
1880b57cec5SDimitry Andric     MemoryBufferRef mbref =
1890b57cec5SDimitry Andric         CHECK(c.getMemoryBufferRef(),
1900b57cec5SDimitry Andric               mb.getBufferIdentifier() +
1910b57cec5SDimitry Andric                   ": could not get the buffer for a child of the archive");
1920b57cec5SDimitry Andric     if (addToTar)
1930b57cec5SDimitry Andric       tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
1940b57cec5SDimitry Andric     v.push_back(std::make_pair(mbref, c.getChildOffset()));
1950b57cec5SDimitry Andric   }
1960b57cec5SDimitry Andric   if (err)
1970b57cec5SDimitry Andric     fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
1980b57cec5SDimitry Andric           toString(std::move(err)));
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   // Take ownership of memory buffers created for members of thin archives.
2010b57cec5SDimitry Andric   for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
2020b57cec5SDimitry Andric     make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   return v;
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric // Opens a file and create a file object. Path has to be resolved already.
2080b57cec5SDimitry Andric void LinkerDriver::addFile(StringRef path, bool withLOption) {
2090b57cec5SDimitry Andric   using namespace sys::fs;
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric   Optional<MemoryBufferRef> buffer = readFile(path);
2120b57cec5SDimitry Andric   if (!buffer.hasValue())
2130b57cec5SDimitry Andric     return;
2140b57cec5SDimitry Andric   MemoryBufferRef mbref = *buffer;
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric   if (config->formatBinary) {
2170b57cec5SDimitry Andric     files.push_back(make<BinaryFile>(mbref));
2180b57cec5SDimitry Andric     return;
2190b57cec5SDimitry Andric   }
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   switch (identify_magic(mbref.getBuffer())) {
2220b57cec5SDimitry Andric   case file_magic::unknown:
2230b57cec5SDimitry Andric     readLinkerScript(mbref);
2240b57cec5SDimitry Andric     return;
2250b57cec5SDimitry Andric   case file_magic::archive: {
2260b57cec5SDimitry Andric     if (inWholeArchive) {
2270b57cec5SDimitry Andric       for (const auto &p : getArchiveMembers(mbref))
2280b57cec5SDimitry Andric         files.push_back(createObjectFile(p.first, path, p.second));
2290b57cec5SDimitry Andric       return;
2300b57cec5SDimitry Andric     }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric     std::unique_ptr<Archive> file =
2330b57cec5SDimitry Andric         CHECK(Archive::create(mbref), path + ": failed to parse archive");
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     // If an archive file has no symbol table, it is likely that a user
2360b57cec5SDimitry Andric     // is attempting LTO and using a default ar command that doesn't
2370b57cec5SDimitry Andric     // understand the LLVM bitcode file. It is a pretty common error, so
2380b57cec5SDimitry Andric     // we'll handle it as if it had a symbol table.
2390b57cec5SDimitry Andric     if (!file->isEmpty() && !file->hasSymbolTable()) {
2400b57cec5SDimitry Andric       // Check if all members are bitcode files. If not, ignore, which is the
2410b57cec5SDimitry Andric       // default action without the LTO hack described above.
2420b57cec5SDimitry Andric       for (const std::pair<MemoryBufferRef, uint64_t> &p :
2430b57cec5SDimitry Andric            getArchiveMembers(mbref))
2440b57cec5SDimitry Andric         if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) {
2450b57cec5SDimitry Andric           error(path + ": archive has no index; run ranlib to add one");
2460b57cec5SDimitry Andric           return;
2470b57cec5SDimitry Andric         }
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric       for (const std::pair<MemoryBufferRef, uint64_t> &p :
2500b57cec5SDimitry Andric            getArchiveMembers(mbref))
2510b57cec5SDimitry Andric         files.push_back(make<LazyObjFile>(p.first, path, p.second));
2520b57cec5SDimitry Andric       return;
2530b57cec5SDimitry Andric     }
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric     // Handle the regular case.
2560b57cec5SDimitry Andric     files.push_back(make<ArchiveFile>(std::move(file)));
2570b57cec5SDimitry Andric     return;
2580b57cec5SDimitry Andric   }
2590b57cec5SDimitry Andric   case file_magic::elf_shared_object:
2600b57cec5SDimitry Andric     if (config->isStatic || config->relocatable) {
2610b57cec5SDimitry Andric       error("attempted static link of dynamic object " + path);
2620b57cec5SDimitry Andric       return;
2630b57cec5SDimitry Andric     }
2640b57cec5SDimitry Andric 
265*349cc55cSDimitry Andric     // Shared objects are identified by soname. soname is (if specified)
266*349cc55cSDimitry Andric     // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
267*349cc55cSDimitry Andric     // the directory part is ignored. Note that path may be a temporary and
268*349cc55cSDimitry Andric     // cannot be stored into SharedFile::soName.
269*349cc55cSDimitry Andric     path = mbref.getBufferIdentifier();
2700b57cec5SDimitry Andric     files.push_back(
2710b57cec5SDimitry Andric         make<SharedFile>(mbref, withLOption ? path::filename(path) : path));
2720b57cec5SDimitry Andric     return;
2730b57cec5SDimitry Andric   case file_magic::bitcode:
2740b57cec5SDimitry Andric   case file_magic::elf_relocatable:
2750b57cec5SDimitry Andric     if (inLib)
2760b57cec5SDimitry Andric       files.push_back(make<LazyObjFile>(mbref, "", 0));
2770b57cec5SDimitry Andric     else
2780b57cec5SDimitry Andric       files.push_back(createObjectFile(mbref));
2790b57cec5SDimitry Andric     break;
2800b57cec5SDimitry Andric   default:
2810b57cec5SDimitry Andric     error(path + ": unknown file type");
2820b57cec5SDimitry Andric   }
2830b57cec5SDimitry Andric }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric // Add a given library by searching it from input search paths.
2860b57cec5SDimitry Andric void LinkerDriver::addLibrary(StringRef name) {
2870b57cec5SDimitry Andric   if (Optional<std::string> path = searchLibrary(name))
2880b57cec5SDimitry Andric     addFile(*path, /*withLOption=*/true);
2890b57cec5SDimitry Andric   else
290e8d8bef9SDimitry Andric     error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
2910b57cec5SDimitry Andric }
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric // This function is called on startup. We need this for LTO since
2940b57cec5SDimitry Andric // LTO calls LLVM functions to compile bitcode files to native code.
2950b57cec5SDimitry Andric // Technically this can be delayed until we read bitcode files, but
2960b57cec5SDimitry Andric // we don't bother to do lazily because the initialization is fast.
2970b57cec5SDimitry Andric static void initLLVM() {
2980b57cec5SDimitry Andric   InitializeAllTargets();
2990b57cec5SDimitry Andric   InitializeAllTargetMCs();
3000b57cec5SDimitry Andric   InitializeAllAsmPrinters();
3010b57cec5SDimitry Andric   InitializeAllAsmParsers();
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric // Some command line options or some combinations of them are not allowed.
3050b57cec5SDimitry Andric // This function checks for such errors.
3060b57cec5SDimitry Andric static void checkOptions() {
3070b57cec5SDimitry Andric   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
3080b57cec5SDimitry Andric   // table which is a relatively new feature.
3090b57cec5SDimitry Andric   if (config->emachine == EM_MIPS && config->gnuHash)
3100b57cec5SDimitry Andric     error("the .gnu.hash section is not compatible with the MIPS target");
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric   if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
3130b57cec5SDimitry Andric     error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
3140b57cec5SDimitry Andric 
31585868e8aSDimitry Andric   if (config->fixCortexA8 && config->emachine != EM_ARM)
31685868e8aSDimitry Andric     error("--fix-cortex-a8 is only supported on ARM targets");
31785868e8aSDimitry Andric 
3180b57cec5SDimitry Andric   if (config->tocOptimize && config->emachine != EM_PPC64)
319e8d8bef9SDimitry Andric     error("--toc-optimize is only supported on PowerPC64 targets");
320e8d8bef9SDimitry Andric 
321e8d8bef9SDimitry Andric   if (config->pcRelOptimize && config->emachine != EM_PPC64)
322e8d8bef9SDimitry Andric     error("--pcrel-optimize is only supported on PowerPC64 targets");
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric   if (config->pie && config->shared)
3250b57cec5SDimitry Andric     error("-shared and -pie may not be used together");
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   if (!config->shared && !config->filterList.empty())
3280b57cec5SDimitry Andric     error("-F may not be used without -shared");
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric   if (!config->shared && !config->auxiliaryList.empty())
3310b57cec5SDimitry Andric     error("-f may not be used without -shared");
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric   if (!config->relocatable && !config->defineCommon)
3340b57cec5SDimitry Andric     error("-no-define-common not supported in non relocatable output");
3350b57cec5SDimitry Andric 
33685868e8aSDimitry Andric   if (config->strip == StripPolicy::All && config->emitRelocs)
33785868e8aSDimitry Andric     error("--strip-all and --emit-relocs may not be used together");
33885868e8aSDimitry Andric 
3390b57cec5SDimitry Andric   if (config->zText && config->zIfuncNoplt)
3400b57cec5SDimitry Andric     error("-z text and -z ifunc-noplt may not be used together");
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   if (config->relocatable) {
3430b57cec5SDimitry Andric     if (config->shared)
3440b57cec5SDimitry Andric       error("-r and -shared may not be used together");
3450b57cec5SDimitry Andric     if (config->gdbIndex)
3460b57cec5SDimitry Andric       error("-r and --gdb-index may not be used together");
3470b57cec5SDimitry Andric     if (config->icf != ICFLevel::None)
3480b57cec5SDimitry Andric       error("-r and --icf may not be used together");
3490b57cec5SDimitry Andric     if (config->pie)
3500b57cec5SDimitry Andric       error("-r and -pie may not be used together");
35185868e8aSDimitry Andric     if (config->exportDynamic)
35285868e8aSDimitry Andric       error("-r and --export-dynamic may not be used together");
3530b57cec5SDimitry Andric   }
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   if (config->executeOnly) {
3560b57cec5SDimitry Andric     if (config->emachine != EM_AARCH64)
357*349cc55cSDimitry Andric       error("--execute-only is only supported on AArch64 targets");
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric     if (config->singleRoRx && !script->hasSectionsCommand)
360*349cc55cSDimitry Andric       error("--execute-only and --no-rosegment cannot be used together");
3610b57cec5SDimitry Andric   }
3620b57cec5SDimitry Andric 
363480093f4SDimitry Andric   if (config->zRetpolineplt && config->zForceIbt)
364480093f4SDimitry Andric     error("-z force-ibt may not be used with -z retpolineplt");
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   if (config->emachine != EM_AARCH64) {
3675ffd83dbSDimitry Andric     if (config->zPacPlt)
368480093f4SDimitry Andric       error("-z pac-plt only supported on AArch64");
3695ffd83dbSDimitry Andric     if (config->zForceBti)
370480093f4SDimitry Andric       error("-z force-bti only supported on AArch64");
3710b57cec5SDimitry Andric   }
3720b57cec5SDimitry Andric }
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric static const char *getReproduceOption(opt::InputArgList &args) {
3750b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_reproduce))
3760b57cec5SDimitry Andric     return arg->getValue();
3770b57cec5SDimitry Andric   return getenv("LLD_REPRODUCE");
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric static bool hasZOption(opt::InputArgList &args, StringRef key) {
3810b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_z))
3820b57cec5SDimitry Andric     if (key == arg->getValue())
3830b57cec5SDimitry Andric       return true;
3840b57cec5SDimitry Andric   return false;
3850b57cec5SDimitry Andric }
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
3880b57cec5SDimitry Andric                      bool Default) {
3890b57cec5SDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
3900b57cec5SDimitry Andric     if (k1 == arg->getValue())
3910b57cec5SDimitry Andric       return true;
3920b57cec5SDimitry Andric     if (k2 == arg->getValue())
3930b57cec5SDimitry Andric       return false;
3940b57cec5SDimitry Andric   }
3950b57cec5SDimitry Andric   return Default;
3960b57cec5SDimitry Andric }
3970b57cec5SDimitry Andric 
39885868e8aSDimitry Andric static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
39985868e8aSDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
40085868e8aSDimitry Andric     StringRef v = arg->getValue();
40185868e8aSDimitry Andric     if (v == "noseparate-code")
40285868e8aSDimitry Andric       return SeparateSegmentKind::None;
40385868e8aSDimitry Andric     if (v == "separate-code")
40485868e8aSDimitry Andric       return SeparateSegmentKind::Code;
40585868e8aSDimitry Andric     if (v == "separate-loadable-segments")
40685868e8aSDimitry Andric       return SeparateSegmentKind::Loadable;
40785868e8aSDimitry Andric   }
40885868e8aSDimitry Andric   return SeparateSegmentKind::None;
40985868e8aSDimitry Andric }
41085868e8aSDimitry Andric 
411480093f4SDimitry Andric static GnuStackKind getZGnuStack(opt::InputArgList &args) {
412480093f4SDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
413480093f4SDimitry Andric     if (StringRef("execstack") == arg->getValue())
414480093f4SDimitry Andric       return GnuStackKind::Exec;
415480093f4SDimitry Andric     if (StringRef("noexecstack") == arg->getValue())
416480093f4SDimitry Andric       return GnuStackKind::NoExec;
417480093f4SDimitry Andric     if (StringRef("nognustack") == arg->getValue())
418480093f4SDimitry Andric       return GnuStackKind::None;
419480093f4SDimitry Andric   }
420480093f4SDimitry Andric 
421480093f4SDimitry Andric   return GnuStackKind::NoExec;
422480093f4SDimitry Andric }
423480093f4SDimitry Andric 
4245ffd83dbSDimitry Andric static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
4255ffd83dbSDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
4265ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
4275ffd83dbSDimitry Andric     if (kv.first == "start-stop-visibility") {
4285ffd83dbSDimitry Andric       if (kv.second == "default")
4295ffd83dbSDimitry Andric         return STV_DEFAULT;
4305ffd83dbSDimitry Andric       else if (kv.second == "internal")
4315ffd83dbSDimitry Andric         return STV_INTERNAL;
4325ffd83dbSDimitry Andric       else if (kv.second == "hidden")
4335ffd83dbSDimitry Andric         return STV_HIDDEN;
4345ffd83dbSDimitry Andric       else if (kv.second == "protected")
4355ffd83dbSDimitry Andric         return STV_PROTECTED;
4365ffd83dbSDimitry Andric       error("unknown -z start-stop-visibility= value: " + StringRef(kv.second));
4375ffd83dbSDimitry Andric     }
4385ffd83dbSDimitry Andric   }
4395ffd83dbSDimitry Andric   return STV_PROTECTED;
4405ffd83dbSDimitry Andric }
4415ffd83dbSDimitry Andric 
4420b57cec5SDimitry Andric static bool isKnownZFlag(StringRef s) {
4430b57cec5SDimitry Andric   return s == "combreloc" || s == "copyreloc" || s == "defs" ||
444480093f4SDimitry Andric          s == "execstack" || s == "force-bti" || s == "force-ibt" ||
445480093f4SDimitry Andric          s == "global" || s == "hazardplt" || s == "ifunc-noplt" ||
446480093f4SDimitry Andric          s == "initfirst" || s == "interpose" ||
4470b57cec5SDimitry Andric          s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
44885868e8aSDimitry Andric          s == "separate-code" || s == "separate-loadable-segments" ||
449fe6060f1SDimitry Andric          s == "start-stop-gc" || s == "nocombreloc" || s == "nocopyreloc" ||
450fe6060f1SDimitry Andric          s == "nodefaultlib" || s == "nodelete" || s == "nodlopen" ||
451fe6060f1SDimitry Andric          s == "noexecstack" || s == "nognustack" ||
452fe6060f1SDimitry Andric          s == "nokeep-text-section-prefix" || s == "norelro" ||
453fe6060f1SDimitry Andric          s == "noseparate-code" || s == "nostart-stop-gc" || s == "notext" ||
4545ffd83dbSDimitry Andric          s == "now" || s == "origin" || s == "pac-plt" || s == "rel" ||
4555ffd83dbSDimitry Andric          s == "rela" || s == "relro" || s == "retpolineplt" ||
4565ffd83dbSDimitry Andric          s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" ||
4575ffd83dbSDimitry Andric          s == "wxneeded" || s.startswith("common-page-size=") ||
4585ffd83dbSDimitry Andric          s.startswith("dead-reloc-in-nonalloc=") ||
4595ffd83dbSDimitry Andric          s.startswith("max-page-size=") || s.startswith("stack-size=") ||
4605ffd83dbSDimitry Andric          s.startswith("start-stop-visibility=");
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric // Report an error for an unknown -z option.
4640b57cec5SDimitry Andric static void checkZOptions(opt::InputArgList &args) {
4650b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_z))
4660b57cec5SDimitry Andric     if (!isKnownZFlag(arg->getValue()))
4670b57cec5SDimitry Andric       error("unknown -z value: " + StringRef(arg->getValue()));
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric 
470e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
4710b57cec5SDimitry Andric   ELFOptTable parser;
4720b57cec5SDimitry Andric   opt::InputArgList args = parser.parse(argsArr.slice(1));
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   // Interpret this flag early because error() depends on them.
4750b57cec5SDimitry Andric   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
4760b57cec5SDimitry Andric   checkZOptions(args);
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   // Handle -help
4790b57cec5SDimitry Andric   if (args.hasArg(OPT_help)) {
4800b57cec5SDimitry Andric     printHelp();
4810b57cec5SDimitry Andric     return;
4820b57cec5SDimitry Andric   }
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   // Handle -v or -version.
4850b57cec5SDimitry Andric   //
4860b57cec5SDimitry Andric   // A note about "compatible with GNU linkers" message: this is a hack for
487*349cc55cSDimitry Andric   // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
488*349cc55cSDimitry Andric   // a GNU compatible linker. See
489*349cc55cSDimitry Andric   // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
4900b57cec5SDimitry Andric   //
4910b57cec5SDimitry Andric   // This is somewhat ugly hack, but in reality, we had no choice other
4920b57cec5SDimitry Andric   // than doing this. Considering the very long release cycle of Libtool,
4930b57cec5SDimitry Andric   // it is not easy to improve it to recognize LLD as a GNU compatible
4940b57cec5SDimitry Andric   // linker in a timely manner. Even if we can make it, there are still a
4950b57cec5SDimitry Andric   // lot of "configure" scripts out there that are generated by old version
4960b57cec5SDimitry Andric   // of Libtool. We cannot convince every software developer to migrate to
4970b57cec5SDimitry Andric   // the latest version and re-generate scripts. So we have this hack.
4980b57cec5SDimitry Andric   if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
4990b57cec5SDimitry Andric     message(getLLDVersion() + " (compatible with GNU linkers)");
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric   if (const char *path = getReproduceOption(args)) {
5020b57cec5SDimitry Andric     // Note that --reproduce is a debug option so you can ignore it
5030b57cec5SDimitry Andric     // if you are trying to understand the whole picture of the code.
5040b57cec5SDimitry Andric     Expected<std::unique_ptr<TarWriter>> errOrWriter =
5050b57cec5SDimitry Andric         TarWriter::create(path, path::stem(path));
5060b57cec5SDimitry Andric     if (errOrWriter) {
5070b57cec5SDimitry Andric       tar = std::move(*errOrWriter);
5080b57cec5SDimitry Andric       tar->append("response.txt", createResponseFile(args));
5090b57cec5SDimitry Andric       tar->append("version.txt", getLLDVersion() + "\n");
510e8d8bef9SDimitry Andric       StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
511e8d8bef9SDimitry Andric       if (!ltoSampleProfile.empty())
512e8d8bef9SDimitry Andric         readFile(ltoSampleProfile);
5130b57cec5SDimitry Andric     } else {
5140b57cec5SDimitry Andric       error("--reproduce: " + toString(errOrWriter.takeError()));
5150b57cec5SDimitry Andric     }
5160b57cec5SDimitry Andric   }
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   readConfigs(args);
5190b57cec5SDimitry Andric 
5200b57cec5SDimitry Andric   // The behavior of -v or --version is a bit strange, but this is
5210b57cec5SDimitry Andric   // needed for compatibility with GNU linkers.
5220b57cec5SDimitry Andric   if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
5230b57cec5SDimitry Andric     return;
5240b57cec5SDimitry Andric   if (args.hasArg(OPT_version))
5250b57cec5SDimitry Andric     return;
5260b57cec5SDimitry Andric 
5275ffd83dbSDimitry Andric   // Initialize time trace profiler.
5285ffd83dbSDimitry Andric   if (config->timeTraceEnabled)
5295ffd83dbSDimitry Andric     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
5305ffd83dbSDimitry Andric 
5315ffd83dbSDimitry Andric   {
5325ffd83dbSDimitry Andric     llvm::TimeTraceScope timeScope("ExecuteLinker");
5335ffd83dbSDimitry Andric 
5340b57cec5SDimitry Andric     initLLVM();
5350b57cec5SDimitry Andric     createFiles(args);
5360b57cec5SDimitry Andric     if (errorCount())
5370b57cec5SDimitry Andric       return;
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric     inferMachineType();
5400b57cec5SDimitry Andric     setConfigs(args);
5410b57cec5SDimitry Andric     checkOptions();
5420b57cec5SDimitry Andric     if (errorCount())
5430b57cec5SDimitry Andric       return;
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric     // The Target instance handles target-specific stuff, such as applying
5460b57cec5SDimitry Andric     // relocations or writing a PLT section. It also contains target-dependent
5470b57cec5SDimitry Andric     // values such as a default image base address.
5480b57cec5SDimitry Andric     target = getTarget();
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric     switch (config->ekind) {
5510b57cec5SDimitry Andric     case ELF32LEKind:
5520b57cec5SDimitry Andric       link<ELF32LE>(args);
5535ffd83dbSDimitry Andric       break;
5540b57cec5SDimitry Andric     case ELF32BEKind:
5550b57cec5SDimitry Andric       link<ELF32BE>(args);
5565ffd83dbSDimitry Andric       break;
5570b57cec5SDimitry Andric     case ELF64LEKind:
5580b57cec5SDimitry Andric       link<ELF64LE>(args);
5595ffd83dbSDimitry Andric       break;
5600b57cec5SDimitry Andric     case ELF64BEKind:
5610b57cec5SDimitry Andric       link<ELF64BE>(args);
5625ffd83dbSDimitry Andric       break;
5630b57cec5SDimitry Andric     default:
5640b57cec5SDimitry Andric       llvm_unreachable("unknown Config->EKind");
5650b57cec5SDimitry Andric     }
5660b57cec5SDimitry Andric   }
5670b57cec5SDimitry Andric 
5685ffd83dbSDimitry Andric   if (config->timeTraceEnabled) {
569*349cc55cSDimitry Andric     checkError(timeTraceProfilerWrite(
570*349cc55cSDimitry Andric         args.getLastArgValue(OPT_time_trace_file_eq).str(),
571*349cc55cSDimitry Andric         config->outputFile));
5725ffd83dbSDimitry Andric     timeTraceProfilerCleanup();
5735ffd83dbSDimitry Andric   }
5745ffd83dbSDimitry Andric }
5755ffd83dbSDimitry Andric 
5760b57cec5SDimitry Andric static std::string getRpath(opt::InputArgList &args) {
5770b57cec5SDimitry Andric   std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
5780b57cec5SDimitry Andric   return llvm::join(v.begin(), v.end(), ":");
5790b57cec5SDimitry Andric }
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric // Determines what we should do if there are remaining unresolved
5820b57cec5SDimitry Andric // symbols after the name resolution.
583e8d8bef9SDimitry Andric static void setUnresolvedSymbolPolicy(opt::InputArgList &args) {
5840b57cec5SDimitry Andric   UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
5850b57cec5SDimitry Andric                                               OPT_warn_unresolved_symbols, true)
5860b57cec5SDimitry Andric                                      ? UnresolvedPolicy::ReportError
5870b57cec5SDimitry Andric                                      : UnresolvedPolicy::Warn;
588*349cc55cSDimitry Andric   // -shared implies --unresolved-symbols=ignore-all because missing
589e8d8bef9SDimitry Andric   // symbols are likely to be resolved at runtime.
590e8d8bef9SDimitry Andric   bool diagRegular = !config->shared, diagShlib = !config->shared;
5910b57cec5SDimitry Andric 
592e8d8bef9SDimitry Andric   for (const opt::Arg *arg : args) {
5930b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
5940b57cec5SDimitry Andric     case OPT_unresolved_symbols: {
5950b57cec5SDimitry Andric       StringRef s = arg->getValue();
596e8d8bef9SDimitry Andric       if (s == "ignore-all") {
597e8d8bef9SDimitry Andric         diagRegular = false;
598e8d8bef9SDimitry Andric         diagShlib = false;
599e8d8bef9SDimitry Andric       } else if (s == "ignore-in-object-files") {
600e8d8bef9SDimitry Andric         diagRegular = false;
601e8d8bef9SDimitry Andric         diagShlib = true;
602e8d8bef9SDimitry Andric       } else if (s == "ignore-in-shared-libs") {
603e8d8bef9SDimitry Andric         diagRegular = true;
604e8d8bef9SDimitry Andric         diagShlib = false;
605e8d8bef9SDimitry Andric       } else if (s == "report-all") {
606e8d8bef9SDimitry Andric         diagRegular = true;
607e8d8bef9SDimitry Andric         diagShlib = true;
608e8d8bef9SDimitry Andric       } else {
6090b57cec5SDimitry Andric         error("unknown --unresolved-symbols value: " + s);
610e8d8bef9SDimitry Andric       }
611e8d8bef9SDimitry Andric       break;
6120b57cec5SDimitry Andric     }
6130b57cec5SDimitry Andric     case OPT_no_undefined:
614e8d8bef9SDimitry Andric       diagRegular = true;
615e8d8bef9SDimitry Andric       break;
6160b57cec5SDimitry Andric     case OPT_z:
6170b57cec5SDimitry Andric       if (StringRef(arg->getValue()) == "defs")
618e8d8bef9SDimitry Andric         diagRegular = true;
619e8d8bef9SDimitry Andric       else if (StringRef(arg->getValue()) == "undefs")
620e8d8bef9SDimitry Andric         diagRegular = false;
621e8d8bef9SDimitry Andric       break;
622e8d8bef9SDimitry Andric     case OPT_allow_shlib_undefined:
623e8d8bef9SDimitry Andric       diagShlib = false;
624e8d8bef9SDimitry Andric       break;
625e8d8bef9SDimitry Andric     case OPT_no_allow_shlib_undefined:
626e8d8bef9SDimitry Andric       diagShlib = true;
627e8d8bef9SDimitry Andric       break;
6280b57cec5SDimitry Andric     }
6290b57cec5SDimitry Andric   }
6300b57cec5SDimitry Andric 
631e8d8bef9SDimitry Andric   config->unresolvedSymbols =
632e8d8bef9SDimitry Andric       diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;
633e8d8bef9SDimitry Andric   config->unresolvedSymbolsInShlib =
634e8d8bef9SDimitry Andric       diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;
6350b57cec5SDimitry Andric }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric static Target2Policy getTarget2(opt::InputArgList &args) {
6380b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
6390b57cec5SDimitry Andric   if (s == "rel")
6400b57cec5SDimitry Andric     return Target2Policy::Rel;
6410b57cec5SDimitry Andric   if (s == "abs")
6420b57cec5SDimitry Andric     return Target2Policy::Abs;
6430b57cec5SDimitry Andric   if (s == "got-rel")
6440b57cec5SDimitry Andric     return Target2Policy::GotRel;
6450b57cec5SDimitry Andric   error("unknown --target2 option: " + s);
6460b57cec5SDimitry Andric   return Target2Policy::GotRel;
6470b57cec5SDimitry Andric }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric static bool isOutputFormatBinary(opt::InputArgList &args) {
6500b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_oformat, "elf");
6510b57cec5SDimitry Andric   if (s == "binary")
6520b57cec5SDimitry Andric     return true;
6530b57cec5SDimitry Andric   if (!s.startswith("elf"))
6540b57cec5SDimitry Andric     error("unknown --oformat value: " + s);
6550b57cec5SDimitry Andric   return false;
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric static DiscardPolicy getDiscard(opt::InputArgList &args) {
6590b57cec5SDimitry Andric   auto *arg =
6600b57cec5SDimitry Andric       args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
6610b57cec5SDimitry Andric   if (!arg)
6620b57cec5SDimitry Andric     return DiscardPolicy::Default;
6630b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_discard_all)
6640b57cec5SDimitry Andric     return DiscardPolicy::All;
6650b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_discard_locals)
6660b57cec5SDimitry Andric     return DiscardPolicy::Locals;
6670b57cec5SDimitry Andric   return DiscardPolicy::None;
6680b57cec5SDimitry Andric }
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric static StringRef getDynamicLinker(opt::InputArgList &args) {
6710b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
67255e4f9d5SDimitry Andric   if (!arg)
6730b57cec5SDimitry Andric     return "";
67455e4f9d5SDimitry Andric   if (arg->getOption().getID() == OPT_no_dynamic_linker) {
67555e4f9d5SDimitry Andric     // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
67655e4f9d5SDimitry Andric     config->noDynamicLinker = true;
67755e4f9d5SDimitry Andric     return "";
67855e4f9d5SDimitry Andric   }
6790b57cec5SDimitry Andric   return arg->getValue();
6800b57cec5SDimitry Andric }
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric static ICFLevel getICF(opt::InputArgList &args) {
6830b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
6840b57cec5SDimitry Andric   if (!arg || arg->getOption().getID() == OPT_icf_none)
6850b57cec5SDimitry Andric     return ICFLevel::None;
6860b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_icf_safe)
6870b57cec5SDimitry Andric     return ICFLevel::Safe;
6880b57cec5SDimitry Andric   return ICFLevel::All;
6890b57cec5SDimitry Andric }
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric static StripPolicy getStrip(opt::InputArgList &args) {
6920b57cec5SDimitry Andric   if (args.hasArg(OPT_relocatable))
6930b57cec5SDimitry Andric     return StripPolicy::None;
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
6960b57cec5SDimitry Andric   if (!arg)
6970b57cec5SDimitry Andric     return StripPolicy::None;
6980b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_strip_all)
6990b57cec5SDimitry Andric     return StripPolicy::All;
7000b57cec5SDimitry Andric   return StripPolicy::Debug;
7010b57cec5SDimitry Andric }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
7040b57cec5SDimitry Andric                                     const opt::Arg &arg) {
7050b57cec5SDimitry Andric   uint64_t va = 0;
7060b57cec5SDimitry Andric   if (s.startswith("0x"))
7070b57cec5SDimitry Andric     s = s.drop_front(2);
7080b57cec5SDimitry Andric   if (!to_integer(s, va, 16))
7090b57cec5SDimitry Andric     error("invalid argument: " + arg.getAsString(args));
7100b57cec5SDimitry Andric   return va;
7110b57cec5SDimitry Andric }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
7140b57cec5SDimitry Andric   StringMap<uint64_t> ret;
7150b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_section_start)) {
7160b57cec5SDimitry Andric     StringRef name;
7170b57cec5SDimitry Andric     StringRef addr;
7180b57cec5SDimitry Andric     std::tie(name, addr) = StringRef(arg->getValue()).split('=');
7190b57cec5SDimitry Andric     ret[name] = parseSectionAddress(addr, args, *arg);
7200b57cec5SDimitry Andric   }
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Ttext))
7230b57cec5SDimitry Andric     ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
7240b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Tdata))
7250b57cec5SDimitry Andric     ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
7260b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_Tbss))
7270b57cec5SDimitry Andric     ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
7280b57cec5SDimitry Andric   return ret;
7290b57cec5SDimitry Andric }
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric static SortSectionPolicy getSortSection(opt::InputArgList &args) {
7320b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_sort_section);
7330b57cec5SDimitry Andric   if (s == "alignment")
7340b57cec5SDimitry Andric     return SortSectionPolicy::Alignment;
7350b57cec5SDimitry Andric   if (s == "name")
7360b57cec5SDimitry Andric     return SortSectionPolicy::Name;
7370b57cec5SDimitry Andric   if (!s.empty())
7380b57cec5SDimitry Andric     error("unknown --sort-section rule: " + s);
7390b57cec5SDimitry Andric   return SortSectionPolicy::Default;
7400b57cec5SDimitry Andric }
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
7430b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
7440b57cec5SDimitry Andric   if (s == "warn")
7450b57cec5SDimitry Andric     return OrphanHandlingPolicy::Warn;
7460b57cec5SDimitry Andric   if (s == "error")
7470b57cec5SDimitry Andric     return OrphanHandlingPolicy::Error;
7480b57cec5SDimitry Andric   if (s != "place")
7490b57cec5SDimitry Andric     error("unknown --orphan-handling mode: " + s);
7500b57cec5SDimitry Andric   return OrphanHandlingPolicy::Place;
7510b57cec5SDimitry Andric }
7520b57cec5SDimitry Andric 
753fe6060f1SDimitry Andric // Parses --power10-stubs= flags, to disable or enable Power 10
754fe6060f1SDimitry Andric // instructions in stubs.
755fe6060f1SDimitry Andric static bool getP10StubOpt(opt::InputArgList &args) {
756fe6060f1SDimitry Andric 
757fe6060f1SDimitry Andric   if (args.getLastArgValue(OPT_power10_stubs_eq)== "no")
758fe6060f1SDimitry Andric     return false;
759fe6060f1SDimitry Andric 
760fe6060f1SDimitry Andric   if (!args.hasArg(OPT_power10_stubs_eq) &&
761fe6060f1SDimitry Andric       args.hasArg(OPT_no_power10_stubs))
762fe6060f1SDimitry Andric     return false;
763fe6060f1SDimitry Andric 
764fe6060f1SDimitry Andric   return true;
765fe6060f1SDimitry Andric }
766fe6060f1SDimitry Andric 
7670b57cec5SDimitry Andric // Parse --build-id or --build-id=<style>. We handle "tree" as a
7680b57cec5SDimitry Andric // synonym for "sha1" because all our hash functions including
769*349cc55cSDimitry Andric // --build-id=sha1 are actually tree hashes for performance reasons.
7700b57cec5SDimitry Andric static std::pair<BuildIdKind, std::vector<uint8_t>>
7710b57cec5SDimitry Andric getBuildId(opt::InputArgList &args) {
7720b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
7730b57cec5SDimitry Andric   if (!arg)
7740b57cec5SDimitry Andric     return {BuildIdKind::None, {}};
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   if (arg->getOption().getID() == OPT_build_id)
7770b57cec5SDimitry Andric     return {BuildIdKind::Fast, {}};
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   StringRef s = arg->getValue();
7800b57cec5SDimitry Andric   if (s == "fast")
7810b57cec5SDimitry Andric     return {BuildIdKind::Fast, {}};
7820b57cec5SDimitry Andric   if (s == "md5")
7830b57cec5SDimitry Andric     return {BuildIdKind::Md5, {}};
7840b57cec5SDimitry Andric   if (s == "sha1" || s == "tree")
7850b57cec5SDimitry Andric     return {BuildIdKind::Sha1, {}};
7860b57cec5SDimitry Andric   if (s == "uuid")
7870b57cec5SDimitry Andric     return {BuildIdKind::Uuid, {}};
7880b57cec5SDimitry Andric   if (s.startswith("0x"))
7890b57cec5SDimitry Andric     return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   if (s != "none")
7920b57cec5SDimitry Andric     error("unknown --build-id style: " + s);
7930b57cec5SDimitry Andric   return {BuildIdKind::None, {}};
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
7970b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
7980b57cec5SDimitry Andric   if (s == "android")
7990b57cec5SDimitry Andric     return {true, false};
8000b57cec5SDimitry Andric   if (s == "relr")
8010b57cec5SDimitry Andric     return {false, true};
8020b57cec5SDimitry Andric   if (s == "android+relr")
8030b57cec5SDimitry Andric     return {true, true};
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric   if (s != "none")
806*349cc55cSDimitry Andric     error("unknown --pack-dyn-relocs format: " + s);
8070b57cec5SDimitry Andric   return {false, false};
8080b57cec5SDimitry Andric }
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric static void readCallGraph(MemoryBufferRef mb) {
8110b57cec5SDimitry Andric   // Build a map from symbol name to section
8120b57cec5SDimitry Andric   DenseMap<StringRef, Symbol *> map;
8130b57cec5SDimitry Andric   for (InputFile *file : objectFiles)
8140b57cec5SDimitry Andric     for (Symbol *sym : file->getSymbols())
8150b57cec5SDimitry Andric       map[sym->getName()] = sym;
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric   auto findSection = [&](StringRef name) -> InputSectionBase * {
8180b57cec5SDimitry Andric     Symbol *sym = map.lookup(name);
8190b57cec5SDimitry Andric     if (!sym) {
8200b57cec5SDimitry Andric       if (config->warnSymbolOrdering)
8210b57cec5SDimitry Andric         warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
8220b57cec5SDimitry Andric       return nullptr;
8230b57cec5SDimitry Andric     }
8240b57cec5SDimitry Andric     maybeWarnUnorderableSymbol(sym);
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric     if (Defined *dr = dyn_cast_or_null<Defined>(sym))
8270b57cec5SDimitry Andric       return dyn_cast_or_null<InputSectionBase>(dr->section);
8280b57cec5SDimitry Andric     return nullptr;
8290b57cec5SDimitry Andric   };
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   for (StringRef line : args::getLines(mb)) {
8320b57cec5SDimitry Andric     SmallVector<StringRef, 3> fields;
8330b57cec5SDimitry Andric     line.split(fields, ' ');
8340b57cec5SDimitry Andric     uint64_t count;
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric     if (fields.size() != 3 || !to_integer(fields[2], count)) {
8370b57cec5SDimitry Andric       error(mb.getBufferIdentifier() + ": parse error");
8380b57cec5SDimitry Andric       return;
8390b57cec5SDimitry Andric     }
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric     if (InputSectionBase *from = findSection(fields[0]))
8420b57cec5SDimitry Andric       if (InputSectionBase *to = findSection(fields[1]))
8430b57cec5SDimitry Andric         config->callGraphProfile[std::make_pair(from, to)] += count;
8440b57cec5SDimitry Andric   }
8450b57cec5SDimitry Andric }
8460b57cec5SDimitry Andric 
847fe6060f1SDimitry Andric // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
848fe6060f1SDimitry Andric // true and populates cgProfile and symbolIndices.
849fe6060f1SDimitry Andric template <class ELFT>
850fe6060f1SDimitry Andric static bool
851fe6060f1SDimitry Andric processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices,
852fe6060f1SDimitry Andric                             ArrayRef<typename ELFT::CGProfile> &cgProfile,
853fe6060f1SDimitry Andric                             ObjFile<ELFT> *inputObj) {
854fe6060f1SDimitry Andric   symbolIndices.clear();
855fe6060f1SDimitry Andric   const ELFFile<ELFT> &obj = inputObj->getObj();
856fe6060f1SDimitry Andric   ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
857fe6060f1SDimitry Andric       CHECK(obj.sections(), "could not retrieve object sections");
858fe6060f1SDimitry Andric 
859fe6060f1SDimitry Andric   if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
860fe6060f1SDimitry Andric     return false;
861fe6060f1SDimitry Andric 
862fe6060f1SDimitry Andric   cgProfile =
863fe6060f1SDimitry Andric       check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(
864fe6060f1SDimitry Andric           objSections[inputObj->cgProfileSectionIndex]));
865fe6060f1SDimitry Andric 
866fe6060f1SDimitry Andric   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
867fe6060f1SDimitry Andric     const Elf_Shdr_Impl<ELFT> &sec = objSections[i];
868fe6060f1SDimitry Andric     if (sec.sh_info == inputObj->cgProfileSectionIndex) {
869fe6060f1SDimitry Andric       if (sec.sh_type == SHT_RELA) {
870fe6060f1SDimitry Andric         ArrayRef<typename ELFT::Rela> relas =
871fe6060f1SDimitry Andric             CHECK(obj.relas(sec), "could not retrieve cg profile rela section");
872fe6060f1SDimitry Andric         for (const typename ELFT::Rela &rel : relas)
873fe6060f1SDimitry Andric           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
874fe6060f1SDimitry Andric         break;
875fe6060f1SDimitry Andric       }
876fe6060f1SDimitry Andric       if (sec.sh_type == SHT_REL) {
877fe6060f1SDimitry Andric         ArrayRef<typename ELFT::Rel> rels =
878fe6060f1SDimitry Andric             CHECK(obj.rels(sec), "could not retrieve cg profile rel section");
879fe6060f1SDimitry Andric         for (const typename ELFT::Rel &rel : rels)
880fe6060f1SDimitry Andric           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
881fe6060f1SDimitry Andric         break;
882fe6060f1SDimitry Andric       }
883fe6060f1SDimitry Andric     }
884fe6060f1SDimitry Andric   }
885fe6060f1SDimitry Andric   if (symbolIndices.empty())
886fe6060f1SDimitry Andric     warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");
887fe6060f1SDimitry Andric   return !symbolIndices.empty();
888fe6060f1SDimitry Andric }
889fe6060f1SDimitry Andric 
8900b57cec5SDimitry Andric template <class ELFT> static void readCallGraphsFromObjectFiles() {
891fe6060f1SDimitry Andric   SmallVector<uint32_t, 32> symbolIndices;
892fe6060f1SDimitry Andric   ArrayRef<typename ELFT::CGProfile> cgProfile;
8930b57cec5SDimitry Andric   for (auto file : objectFiles) {
8940b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(file);
895fe6060f1SDimitry Andric     if (!processCallGraphRelocations(symbolIndices, cgProfile, obj))
896fe6060f1SDimitry Andric       continue;
8970b57cec5SDimitry Andric 
898fe6060f1SDimitry Andric     if (symbolIndices.size() != cgProfile.size() * 2)
899fe6060f1SDimitry Andric       fatal("number of relocations doesn't match Weights");
900fe6060f1SDimitry Andric 
901fe6060f1SDimitry Andric     for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {
902fe6060f1SDimitry Andric       const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];
903fe6060f1SDimitry Andric       uint32_t fromIndex = symbolIndices[i * 2];
904fe6060f1SDimitry Andric       uint32_t toIndex = symbolIndices[i * 2 + 1];
905fe6060f1SDimitry Andric       auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
906fe6060f1SDimitry Andric       auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
9070b57cec5SDimitry Andric       if (!fromSym || !toSym)
9080b57cec5SDimitry Andric         continue;
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric       auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
9110b57cec5SDimitry Andric       auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
9120b57cec5SDimitry Andric       if (from && to)
9130b57cec5SDimitry Andric         config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
9140b57cec5SDimitry Andric     }
9150b57cec5SDimitry Andric   }
9160b57cec5SDimitry Andric }
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric static bool getCompressDebugSections(opt::InputArgList &args) {
9190b57cec5SDimitry Andric   StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
9200b57cec5SDimitry Andric   if (s == "none")
9210b57cec5SDimitry Andric     return false;
9220b57cec5SDimitry Andric   if (s != "zlib")
9230b57cec5SDimitry Andric     error("unknown --compress-debug-sections value: " + s);
9240b57cec5SDimitry Andric   if (!zlib::isAvailable())
9250b57cec5SDimitry Andric     error("--compress-debug-sections: zlib is not available");
9260b57cec5SDimitry Andric   return true;
9270b57cec5SDimitry Andric }
9280b57cec5SDimitry Andric 
92985868e8aSDimitry Andric static StringRef getAliasSpelling(opt::Arg *arg) {
93085868e8aSDimitry Andric   if (const opt::Arg *alias = arg->getAlias())
93185868e8aSDimitry Andric     return alias->getSpelling();
93285868e8aSDimitry Andric   return arg->getSpelling();
93385868e8aSDimitry Andric }
93485868e8aSDimitry Andric 
9350b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
9360b57cec5SDimitry Andric                                                         unsigned id) {
9370b57cec5SDimitry Andric   auto *arg = args.getLastArg(id);
9380b57cec5SDimitry Andric   if (!arg)
9390b57cec5SDimitry Andric     return {"", ""};
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   StringRef s = arg->getValue();
9420b57cec5SDimitry Andric   std::pair<StringRef, StringRef> ret = s.split(';');
9430b57cec5SDimitry Andric   if (ret.second.empty())
94485868e8aSDimitry Andric     error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
9450b57cec5SDimitry Andric   return ret;
9460b57cec5SDimitry Andric }
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric // Parse the symbol ordering file and warn for any duplicate entries.
9490b57cec5SDimitry Andric static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
9500b57cec5SDimitry Andric   SetVector<StringRef> names;
9510b57cec5SDimitry Andric   for (StringRef s : args::getLines(mb))
9520b57cec5SDimitry Andric     if (!names.insert(s) && config->warnSymbolOrdering)
9530b57cec5SDimitry Andric       warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric   return names.takeVector();
9560b57cec5SDimitry Andric }
9570b57cec5SDimitry Andric 
9585ffd83dbSDimitry Andric static bool getIsRela(opt::InputArgList &args) {
9595ffd83dbSDimitry Andric   // If -z rel or -z rela is specified, use the last option.
9605ffd83dbSDimitry Andric   for (auto *arg : args.filtered_reverse(OPT_z)) {
9615ffd83dbSDimitry Andric     StringRef s(arg->getValue());
9625ffd83dbSDimitry Andric     if (s == "rel")
9635ffd83dbSDimitry Andric       return false;
9645ffd83dbSDimitry Andric     if (s == "rela")
9655ffd83dbSDimitry Andric       return true;
9665ffd83dbSDimitry Andric   }
9675ffd83dbSDimitry Andric 
9685ffd83dbSDimitry Andric   // Otherwise use the psABI defined relocation entry format.
9695ffd83dbSDimitry Andric   uint16_t m = config->emachine;
9705ffd83dbSDimitry Andric   return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC ||
9715ffd83dbSDimitry Andric          m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64;
9725ffd83dbSDimitry Andric }
9735ffd83dbSDimitry Andric 
9740b57cec5SDimitry Andric static void parseClangOption(StringRef opt, const Twine &msg) {
9750b57cec5SDimitry Andric   std::string err;
9760b57cec5SDimitry Andric   raw_string_ostream os(err);
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric   const char *argv[] = {config->progName.data(), opt.data()};
9790b57cec5SDimitry Andric   if (cl::ParseCommandLineOptions(2, argv, "", &os))
9800b57cec5SDimitry Andric     return;
9810b57cec5SDimitry Andric   os.flush();
9820b57cec5SDimitry Andric   error(msg + ": " + StringRef(err).trim());
9830b57cec5SDimitry Andric }
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric // Initializes Config members by the command line options.
9860b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args) {
9870b57cec5SDimitry Andric   errorHandler().verbose = args.hasArg(OPT_verbose);
9880b57cec5SDimitry Andric   errorHandler().fatalWarnings =
9890b57cec5SDimitry Andric       args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
9900b57cec5SDimitry Andric   errorHandler().vsDiagnostics =
9910b57cec5SDimitry Andric       args.hasArg(OPT_visual_studio_diagnostics_format, false);
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   config->allowMultipleDefinition =
9940b57cec5SDimitry Andric       args.hasFlag(OPT_allow_multiple_definition,
9950b57cec5SDimitry Andric                    OPT_no_allow_multiple_definition, false) ||
9960b57cec5SDimitry Andric       hasZOption(args, "muldefs");
9970b57cec5SDimitry Andric   config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
9986e75b2fbSDimitry Andric   if (opt::Arg *arg =
9996e75b2fbSDimitry Andric           args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,
10006e75b2fbSDimitry Andric                           OPT_Bsymbolic_functions, OPT_Bsymbolic)) {
10016e75b2fbSDimitry Andric     if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
10026e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::NonWeakFunctions;
10036e75b2fbSDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic_functions))
10046e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::Functions;
1005fe6060f1SDimitry Andric     else if (arg->getOption().matches(OPT_Bsymbolic))
10066e75b2fbSDimitry Andric       config->bsymbolic = BsymbolicKind::All;
1007fe6060f1SDimitry Andric   }
10080b57cec5SDimitry Andric   config->checkSections =
10090b57cec5SDimitry Andric       args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
10100b57cec5SDimitry Andric   config->chroot = args.getLastArgValue(OPT_chroot);
10110b57cec5SDimitry Andric   config->compressDebugSections = getCompressDebugSections(args);
1012fe6060f1SDimitry Andric   config->cref = args.hasArg(OPT_cref);
10130b57cec5SDimitry Andric   config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
10140b57cec5SDimitry Andric                                       !args.hasArg(OPT_relocatable));
10155ffd83dbSDimitry Andric   config->optimizeBBJumps =
10165ffd83dbSDimitry Andric       args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
10170b57cec5SDimitry Andric   config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
1018e8d8bef9SDimitry Andric   config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
10190b57cec5SDimitry Andric   config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
10200b57cec5SDimitry Andric   config->disableVerify = args.hasArg(OPT_disable_verify);
10210b57cec5SDimitry Andric   config->discard = getDiscard(args);
10220b57cec5SDimitry Andric   config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
10230b57cec5SDimitry Andric   config->dynamicLinker = getDynamicLinker(args);
10240b57cec5SDimitry Andric   config->ehFrameHdr =
10250b57cec5SDimitry Andric       args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
10260b57cec5SDimitry Andric   config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
10270b57cec5SDimitry Andric   config->emitRelocs = args.hasArg(OPT_emit_relocs);
10280b57cec5SDimitry Andric   config->callGraphProfileSort = args.hasFlag(
10290b57cec5SDimitry Andric       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
10300b57cec5SDimitry Andric   config->enableNewDtags =
10310b57cec5SDimitry Andric       args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
10320b57cec5SDimitry Andric   config->entry = args.getLastArgValue(OPT_entry);
1033e8d8bef9SDimitry Andric 
1034e8d8bef9SDimitry Andric   errorHandler().errorHandlingScript =
1035e8d8bef9SDimitry Andric       args.getLastArgValue(OPT_error_handling_script);
1036e8d8bef9SDimitry Andric 
10370b57cec5SDimitry Andric   config->executeOnly =
10380b57cec5SDimitry Andric       args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
10390b57cec5SDimitry Andric   config->exportDynamic =
10400b57cec5SDimitry Andric       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
10410b57cec5SDimitry Andric   config->filterList = args::getStrings(args, OPT_filter);
10420b57cec5SDimitry Andric   config->fini = args.getLastArgValue(OPT_fini, "_fini");
10435ffd83dbSDimitry Andric   config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
10445ffd83dbSDimitry Andric                                      !args.hasArg(OPT_relocatable);
10455ffd83dbSDimitry Andric   config->fixCortexA8 =
10465ffd83dbSDimitry Andric       args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
1047e8d8bef9SDimitry Andric   config->fortranCommon =
1048e8d8bef9SDimitry Andric       args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, true);
10490b57cec5SDimitry Andric   config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
10500b57cec5SDimitry Andric   config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
10510b57cec5SDimitry Andric   config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
10520b57cec5SDimitry Andric   config->icf = getICF(args);
10530b57cec5SDimitry Andric   config->ignoreDataAddressEquality =
10540b57cec5SDimitry Andric       args.hasArg(OPT_ignore_data_address_equality);
10550b57cec5SDimitry Andric   config->ignoreFunctionAddressEquality =
10560b57cec5SDimitry Andric       args.hasArg(OPT_ignore_function_address_equality);
10570b57cec5SDimitry Andric   config->init = args.getLastArgValue(OPT_init, "_init");
10580b57cec5SDimitry Andric   config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
10590b57cec5SDimitry Andric   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
10600b57cec5SDimitry Andric   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1061*349cc55cSDimitry Andric   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1062*349cc55cSDimitry Andric                                             OPT_no_lto_pgo_warn_mismatch, true);
10630b57cec5SDimitry Andric   config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
10645ffd83dbSDimitry Andric   config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
1065e8d8bef9SDimitry Andric   config->ltoNewPassManager =
1066e8d8bef9SDimitry Andric       args.hasFlag(OPT_no_lto_legacy_pass_manager, OPT_lto_legacy_pass_manager,
1067e8d8bef9SDimitry Andric                    LLVM_ENABLE_NEW_PASS_MANAGER);
10680b57cec5SDimitry Andric   config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
10695ffd83dbSDimitry Andric   config->ltoWholeProgramVisibility =
1070e8d8bef9SDimitry Andric       args.hasFlag(OPT_lto_whole_program_visibility,
1071e8d8bef9SDimitry Andric                    OPT_no_lto_whole_program_visibility, false);
10720b57cec5SDimitry Andric   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
107385868e8aSDimitry Andric   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
10740b57cec5SDimitry Andric   config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
10750b57cec5SDimitry Andric   config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
10765ffd83dbSDimitry Andric   config->ltoBasicBlockSections =
1077e8d8bef9SDimitry Andric       args.getLastArgValue(OPT_lto_basic_block_sections);
10785ffd83dbSDimitry Andric   config->ltoUniqueBasicBlockSectionNames =
1079e8d8bef9SDimitry Andric       args.hasFlag(OPT_lto_unique_basic_block_section_names,
1080e8d8bef9SDimitry Andric                    OPT_no_lto_unique_basic_block_section_names, false);
10810b57cec5SDimitry Andric   config->mapFile = args.getLastArgValue(OPT_Map);
10820b57cec5SDimitry Andric   config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
10830b57cec5SDimitry Andric   config->mergeArmExidx =
10840b57cec5SDimitry Andric       args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
1085480093f4SDimitry Andric   config->mmapOutputFile =
1086480093f4SDimitry Andric       args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
10870b57cec5SDimitry Andric   config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
10880b57cec5SDimitry Andric   config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
10890b57cec5SDimitry Andric   config->nostdlib = args.hasArg(OPT_nostdlib);
10900b57cec5SDimitry Andric   config->oFormatBinary = isOutputFormatBinary(args);
10910b57cec5SDimitry Andric   config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
10920b57cec5SDimitry Andric   config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
1093e8d8bef9SDimitry Andric 
1094e8d8bef9SDimitry Andric   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1095e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {
1096e8d8bef9SDimitry Andric     auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());
1097e8d8bef9SDimitry Andric     if (!resultOrErr)
1098e8d8bef9SDimitry Andric       error(arg->getSpelling() + ": invalid argument '" + arg->getValue() +
1099e8d8bef9SDimitry Andric             "', only integer or 'auto' is supported");
1100e8d8bef9SDimitry Andric     else
1101e8d8bef9SDimitry Andric       config->optRemarksHotnessThreshold = *resultOrErr;
1102e8d8bef9SDimitry Andric   }
1103e8d8bef9SDimitry Andric 
11040b57cec5SDimitry Andric   config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
11050b57cec5SDimitry Andric   config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
11060b57cec5SDimitry Andric   config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
11070b57cec5SDimitry Andric   config->optimize = args::getInteger(args, OPT_O, 1);
11080b57cec5SDimitry Andric   config->orphanHandling = getOrphanHandling(args);
11090b57cec5SDimitry Andric   config->outputFile = args.getLastArgValue(OPT_o);
11100b57cec5SDimitry Andric   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
11110b57cec5SDimitry Andric   config->printIcfSections =
11120b57cec5SDimitry Andric       args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
11130b57cec5SDimitry Andric   config->printGcSections =
11140b57cec5SDimitry Andric       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
11155ffd83dbSDimitry Andric   config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
11160b57cec5SDimitry Andric   config->printSymbolOrder =
11170b57cec5SDimitry Andric       args.getLastArgValue(OPT_print_symbol_order);
1118*349cc55cSDimitry Andric   config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true);
11190b57cec5SDimitry Andric   config->rpath = getRpath(args);
11200b57cec5SDimitry Andric   config->relocatable = args.hasArg(OPT_relocatable);
11210b57cec5SDimitry Andric   config->saveTemps = args.hasArg(OPT_save_temps);
11220b57cec5SDimitry Andric   config->searchPaths = args::getStrings(args, OPT_library_path);
11230b57cec5SDimitry Andric   config->sectionStartMap = getSectionStartMap(args);
11240b57cec5SDimitry Andric   config->shared = args.hasArg(OPT_shared);
11255ffd83dbSDimitry Andric   config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
11260b57cec5SDimitry Andric   config->soName = args.getLastArgValue(OPT_soname);
11270b57cec5SDimitry Andric   config->sortSection = getSortSection(args);
11280b57cec5SDimitry Andric   config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
11290b57cec5SDimitry Andric   config->strip = getStrip(args);
11300b57cec5SDimitry Andric   config->sysroot = args.getLastArgValue(OPT_sysroot);
11310b57cec5SDimitry Andric   config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
11320b57cec5SDimitry Andric   config->target2 = getTarget2(args);
11330b57cec5SDimitry Andric   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
11340b57cec5SDimitry Andric   config->thinLTOCachePolicy = CHECK(
11350b57cec5SDimitry Andric       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
11360b57cec5SDimitry Andric       "--thinlto-cache-policy: invalid cache policy");
113785868e8aSDimitry Andric   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
113885868e8aSDimitry Andric   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
113985868e8aSDimitry Andric                              args.hasArg(OPT_thinlto_index_only_eq);
114085868e8aSDimitry Andric   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
11410b57cec5SDimitry Andric   config->thinLTOObjectSuffixReplace =
114285868e8aSDimitry Andric       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
11430b57cec5SDimitry Andric   config->thinLTOPrefixReplace =
114485868e8aSDimitry Andric       getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
11455ffd83dbSDimitry Andric   config->thinLTOModulesToCompile =
11465ffd83dbSDimitry Andric       args::getStrings(args, OPT_thinlto_single_module_eq);
11475ffd83dbSDimitry Andric   config->timeTraceEnabled = args.hasArg(OPT_time_trace);
11485ffd83dbSDimitry Andric   config->timeTraceGranularity =
11495ffd83dbSDimitry Andric       args::getInteger(args, OPT_time_trace_granularity, 500);
11500b57cec5SDimitry Andric   config->trace = args.hasArg(OPT_trace);
11510b57cec5SDimitry Andric   config->undefined = args::getStrings(args, OPT_undefined);
11520b57cec5SDimitry Andric   config->undefinedVersion =
11530b57cec5SDimitry Andric       args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
11545ffd83dbSDimitry Andric   config->unique = args.hasArg(OPT_unique);
11550b57cec5SDimitry Andric   config->useAndroidRelrTags = args.hasFlag(
11560b57cec5SDimitry Andric       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
11570b57cec5SDimitry Andric   config->warnBackrefs =
11580b57cec5SDimitry Andric       args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
11590b57cec5SDimitry Andric   config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
11600b57cec5SDimitry Andric   config->warnSymbolOrdering =
11610b57cec5SDimitry Andric       args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1162*349cc55cSDimitry Andric   config->whyExtract = args.getLastArgValue(OPT_why_extract);
11630b57cec5SDimitry Andric   config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
11640b57cec5SDimitry Andric   config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
11655ffd83dbSDimitry Andric   config->zForceBti = hasZOption(args, "force-bti");
1166480093f4SDimitry Andric   config->zForceIbt = hasZOption(args, "force-ibt");
11670b57cec5SDimitry Andric   config->zGlobal = hasZOption(args, "global");
1168480093f4SDimitry Andric   config->zGnustack = getZGnuStack(args);
11690b57cec5SDimitry Andric   config->zHazardplt = hasZOption(args, "hazardplt");
11700b57cec5SDimitry Andric   config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
11710b57cec5SDimitry Andric   config->zInitfirst = hasZOption(args, "initfirst");
11720b57cec5SDimitry Andric   config->zInterpose = hasZOption(args, "interpose");
11730b57cec5SDimitry Andric   config->zKeepTextSectionPrefix = getZFlag(
11740b57cec5SDimitry Andric       args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
11750b57cec5SDimitry Andric   config->zNodefaultlib = hasZOption(args, "nodefaultlib");
11760b57cec5SDimitry Andric   config->zNodelete = hasZOption(args, "nodelete");
11770b57cec5SDimitry Andric   config->zNodlopen = hasZOption(args, "nodlopen");
11780b57cec5SDimitry Andric   config->zNow = getZFlag(args, "now", "lazy", false);
11790b57cec5SDimitry Andric   config->zOrigin = hasZOption(args, "origin");
11805ffd83dbSDimitry Andric   config->zPacPlt = hasZOption(args, "pac-plt");
11810b57cec5SDimitry Andric   config->zRelro = getZFlag(args, "relro", "norelro", true);
11820b57cec5SDimitry Andric   config->zRetpolineplt = hasZOption(args, "retpolineplt");
11830b57cec5SDimitry Andric   config->zRodynamic = hasZOption(args, "rodynamic");
118485868e8aSDimitry Andric   config->zSeparate = getZSeparate(args);
1185480093f4SDimitry Andric   config->zShstk = hasZOption(args, "shstk");
11860b57cec5SDimitry Andric   config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1187fe6060f1SDimitry Andric   config->zStartStopGC =
1188fe6060f1SDimitry Andric       getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);
11895ffd83dbSDimitry Andric   config->zStartStopVisibility = getZStartStopVisibility(args);
11900b57cec5SDimitry Andric   config->zText = getZFlag(args, "text", "notext", true);
11910b57cec5SDimitry Andric   config->zWxneeded = hasZOption(args, "wxneeded");
1192e8d8bef9SDimitry Andric   setUnresolvedSymbolPolicy(args);
1193fe6060f1SDimitry Andric   config->Power10Stub = getP10StubOpt(args);
1194fe6060f1SDimitry Andric 
1195fe6060f1SDimitry Andric   if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {
1196fe6060f1SDimitry Andric     if (arg->getOption().matches(OPT_eb))
1197fe6060f1SDimitry Andric       config->optEB = true;
1198fe6060f1SDimitry Andric     else
1199fe6060f1SDimitry Andric       config->optEL = true;
1200fe6060f1SDimitry Andric   }
1201fe6060f1SDimitry Andric 
1202fe6060f1SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {
1203fe6060f1SDimitry Andric     constexpr StringRef errPrefix = "--shuffle-sections=: ";
1204fe6060f1SDimitry Andric     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
1205fe6060f1SDimitry Andric     if (kv.first.empty() || kv.second.empty()) {
1206fe6060f1SDimitry Andric       error(errPrefix + "expected <section_glob>=<seed>, but got '" +
1207fe6060f1SDimitry Andric             arg->getValue() + "'");
1208fe6060f1SDimitry Andric       continue;
1209fe6060f1SDimitry Andric     }
1210fe6060f1SDimitry Andric     // Signed so that <section_glob>=-1 is allowed.
1211fe6060f1SDimitry Andric     int64_t v;
1212fe6060f1SDimitry Andric     if (!to_integer(kv.second, v))
1213fe6060f1SDimitry Andric       error(errPrefix + "expected an integer, but got '" + kv.second + "'");
1214fe6060f1SDimitry Andric     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1215fe6060f1SDimitry Andric       config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v));
1216fe6060f1SDimitry Andric     else
1217fe6060f1SDimitry Andric       error(errPrefix + toString(pat.takeError()));
1218fe6060f1SDimitry Andric   }
12190b57cec5SDimitry Andric 
12205ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_z)) {
12215ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> option =
12225ffd83dbSDimitry Andric         StringRef(arg->getValue()).split('=');
12235ffd83dbSDimitry Andric     if (option.first != "dead-reloc-in-nonalloc")
12245ffd83dbSDimitry Andric       continue;
12255ffd83dbSDimitry Andric     constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
12265ffd83dbSDimitry Andric     std::pair<StringRef, StringRef> kv = option.second.split('=');
12275ffd83dbSDimitry Andric     if (kv.first.empty() || kv.second.empty()) {
12285ffd83dbSDimitry Andric       error(errPrefix + "expected <section_glob>=<value>");
12295ffd83dbSDimitry Andric       continue;
12305ffd83dbSDimitry Andric     }
12315ffd83dbSDimitry Andric     uint64_t v;
12325ffd83dbSDimitry Andric     if (!to_integer(kv.second, v))
12335ffd83dbSDimitry Andric       error(errPrefix + "expected a non-negative integer, but got '" +
12345ffd83dbSDimitry Andric             kv.second + "'");
12355ffd83dbSDimitry Andric     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
12365ffd83dbSDimitry Andric       config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
12375ffd83dbSDimitry Andric     else
12385ffd83dbSDimitry Andric       error(errPrefix + toString(pat.takeError()));
12395ffd83dbSDimitry Andric   }
12405ffd83dbSDimitry Andric 
1241e8d8bef9SDimitry Andric   cl::ResetAllOptionOccurrences();
1242e8d8bef9SDimitry Andric 
12430b57cec5SDimitry Andric   // Parse LTO options.
12440b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
12450b57cec5SDimitry Andric     parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
12460b57cec5SDimitry Andric                      arg->getSpelling());
12470b57cec5SDimitry Andric 
12485ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
12495ffd83dbSDimitry Andric     parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
12505ffd83dbSDimitry Andric 
12515ffd83dbSDimitry Andric   // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
12525ffd83dbSDimitry Andric   // relative path. Just ignore. If not ended with "lto-wrapper", consider it an
12535ffd83dbSDimitry Andric   // unsupported LLVMgold.so option and error.
12545ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq))
12555ffd83dbSDimitry Andric     if (!StringRef(arg->getValue()).endswith("lto-wrapper"))
12565ffd83dbSDimitry Andric       error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
12575ffd83dbSDimitry Andric             "'");
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric   // Parse -mllvm options.
12600b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_mllvm))
12610b57cec5SDimitry Andric     parseClangOption(arg->getValue(), arg->getSpelling());
12620b57cec5SDimitry Andric 
12635ffd83dbSDimitry Andric   // --threads= takes a positive integer and provides the default value for
12645ffd83dbSDimitry Andric   // --thinlto-jobs=.
12655ffd83dbSDimitry Andric   if (auto *arg = args.getLastArg(OPT_threads)) {
12665ffd83dbSDimitry Andric     StringRef v(arg->getValue());
12675ffd83dbSDimitry Andric     unsigned threads = 0;
12685ffd83dbSDimitry Andric     if (!llvm::to_integer(v, threads, 0) || threads == 0)
12695ffd83dbSDimitry Andric       error(arg->getSpelling() + ": expected a positive integer, but got '" +
12705ffd83dbSDimitry Andric             arg->getValue() + "'");
12715ffd83dbSDimitry Andric     parallel::strategy = hardware_concurrency(threads);
12725ffd83dbSDimitry Andric     config->thinLTOJobs = v;
12735ffd83dbSDimitry Andric   }
12745ffd83dbSDimitry Andric   if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
12755ffd83dbSDimitry Andric     config->thinLTOJobs = arg->getValue();
12765ffd83dbSDimitry Andric 
12770b57cec5SDimitry Andric   if (config->ltoo > 3)
12780b57cec5SDimitry Andric     error("invalid optimization level for LTO: " + Twine(config->ltoo));
12790b57cec5SDimitry Andric   if (config->ltoPartitions == 0)
12800b57cec5SDimitry Andric     error("--lto-partitions: number of threads must be > 0");
12815ffd83dbSDimitry Andric   if (!get_threadpool_strategy(config->thinLTOJobs))
12825ffd83dbSDimitry Andric     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   if (config->splitStackAdjustSize < 0)
12850b57cec5SDimitry Andric     error("--split-stack-adjust-size: size must be >= 0");
12860b57cec5SDimitry Andric 
1287480093f4SDimitry Andric   // The text segment is traditionally the first segment, whose address equals
1288480093f4SDimitry Andric   // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1289480093f4SDimitry Andric   // is an old-fashioned option that does not play well with lld's layout.
1290480093f4SDimitry Andric   // Suggest --image-base as a likely alternative.
1291480093f4SDimitry Andric   if (args.hasArg(OPT_Ttext_segment))
1292480093f4SDimitry Andric     error("-Ttext-segment is not supported. Use --image-base if you "
1293480093f4SDimitry Andric           "intend to set the base address");
1294480093f4SDimitry Andric 
12950b57cec5SDimitry Andric   // Parse ELF{32,64}{LE,BE} and CPU type.
12960b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_m)) {
12970b57cec5SDimitry Andric     StringRef s = arg->getValue();
12980b57cec5SDimitry Andric     std::tie(config->ekind, config->emachine, config->osabi) =
12990b57cec5SDimitry Andric         parseEmulation(s);
13000b57cec5SDimitry Andric     config->mipsN32Abi =
13010b57cec5SDimitry Andric         (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
13020b57cec5SDimitry Andric     config->emulation = s;
13030b57cec5SDimitry Andric   }
13040b57cec5SDimitry Andric 
1305*349cc55cSDimitry Andric   // Parse --hash-style={sysv,gnu,both}.
13060b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_hash_style)) {
13070b57cec5SDimitry Andric     StringRef s = arg->getValue();
13080b57cec5SDimitry Andric     if (s == "sysv")
13090b57cec5SDimitry Andric       config->sysvHash = true;
13100b57cec5SDimitry Andric     else if (s == "gnu")
13110b57cec5SDimitry Andric       config->gnuHash = true;
13120b57cec5SDimitry Andric     else if (s == "both")
13130b57cec5SDimitry Andric       config->sysvHash = config->gnuHash = true;
13140b57cec5SDimitry Andric     else
1315*349cc55cSDimitry Andric       error("unknown --hash-style: " + s);
13160b57cec5SDimitry Andric   }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric   if (args.hasArg(OPT_print_map))
13190b57cec5SDimitry Andric     config->mapFile = "-";
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
13220b57cec5SDimitry Andric   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
13230b57cec5SDimitry Andric   // it.
13240b57cec5SDimitry Andric   if (config->nmagic || config->omagic)
13250b57cec5SDimitry Andric     config->zRelro = false;
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric   std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
13300b57cec5SDimitry Andric       getPackDynRelocs(args);
13310b57cec5SDimitry Andric 
13320b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
13330b57cec5SDimitry Andric     if (args.hasArg(OPT_call_graph_ordering_file))
13340b57cec5SDimitry Andric       error("--symbol-ordering-file and --call-graph-order-file "
13350b57cec5SDimitry Andric             "may not be used together");
13360b57cec5SDimitry Andric     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
13370b57cec5SDimitry Andric       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
13380b57cec5SDimitry Andric       // Also need to disable CallGraphProfileSort to prevent
13390b57cec5SDimitry Andric       // LLD order symbols with CGProfile
13400b57cec5SDimitry Andric       config->callGraphProfileSort = false;
13410b57cec5SDimitry Andric     }
13420b57cec5SDimitry Andric   }
13430b57cec5SDimitry Andric 
134485868e8aSDimitry Andric   assert(config->versionDefinitions.empty());
134585868e8aSDimitry Andric   config->versionDefinitions.push_back(
13466e75b2fbSDimitry Andric       {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});
13476e75b2fbSDimitry Andric   config->versionDefinitions.push_back(
13486e75b2fbSDimitry Andric       {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});
134985868e8aSDimitry Andric 
13500b57cec5SDimitry Andric   // If --retain-symbol-file is used, we'll keep only the symbols listed in
13510b57cec5SDimitry Andric   // the file and discard all others.
13520b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
13536e75b2fbSDimitry Andric     config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
135485868e8aSDimitry Andric         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
13550b57cec5SDimitry Andric     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
13560b57cec5SDimitry Andric       for (StringRef s : args::getLines(*buffer))
13576e75b2fbSDimitry Andric         config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
135885868e8aSDimitry Andric             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
13590b57cec5SDimitry Andric   }
13600b57cec5SDimitry Andric 
13615ffd83dbSDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
13625ffd83dbSDimitry Andric     StringRef pattern(arg->getValue());
13635ffd83dbSDimitry Andric     if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
13645ffd83dbSDimitry Andric       config->warnBackrefsExclude.push_back(std::move(*pat));
13655ffd83dbSDimitry Andric     else
13665ffd83dbSDimitry Andric       error(arg->getSpelling() + ": " + toString(pat.takeError()));
13675ffd83dbSDimitry Andric   }
13685ffd83dbSDimitry Andric 
1369*349cc55cSDimitry Andric   // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1370*349cc55cSDimitry Andric   // which should be exported. For -shared, references to matched non-local
1371*349cc55cSDimitry Andric   // STV_DEFAULT symbols are not bound to definitions within the shared object,
1372*349cc55cSDimitry Andric   // even if other options express a symbolic intention: -Bsymbolic,
13735ffd83dbSDimitry Andric   // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
13740b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
13750b57cec5SDimitry Andric     config->dynamicList.push_back(
13765ffd83dbSDimitry Andric         {arg->getValue(), /*isExternCpp=*/false,
13775ffd83dbSDimitry Andric          /*hasWildcard=*/hasWildcard(arg->getValue())});
13780b57cec5SDimitry Andric 
1379*349cc55cSDimitry Andric   // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1380*349cc55cSDimitry Andric   // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1381*349cc55cSDimitry Andric   // like semantics.
1382*349cc55cSDimitry Andric   config->symbolic =
1383*349cc55cSDimitry Andric       config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1384*349cc55cSDimitry Andric   for (auto *arg :
1385*349cc55cSDimitry Andric        args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))
1386*349cc55cSDimitry Andric     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1387*349cc55cSDimitry Andric       readDynamicList(*buffer);
1388*349cc55cSDimitry Andric 
13890b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_version_script))
13900b57cec5SDimitry Andric     if (Optional<std::string> path = searchScript(arg->getValue())) {
13910b57cec5SDimitry Andric       if (Optional<MemoryBufferRef> buffer = readFile(*path))
13920b57cec5SDimitry Andric         readVersionScript(*buffer);
13930b57cec5SDimitry Andric     } else {
13940b57cec5SDimitry Andric       error(Twine("cannot find version script ") + arg->getValue());
13950b57cec5SDimitry Andric     }
13960b57cec5SDimitry Andric }
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric // Some Config members do not directly correspond to any particular
13990b57cec5SDimitry Andric // command line options, but computed based on other Config values.
14000b57cec5SDimitry Andric // This function initialize such members. See Config.h for the details
14010b57cec5SDimitry Andric // of these values.
14020b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args) {
14030b57cec5SDimitry Andric   ELFKind k = config->ekind;
14040b57cec5SDimitry Andric   uint16_t m = config->emachine;
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric   config->copyRelocs = (config->relocatable || config->emitRelocs);
14070b57cec5SDimitry Andric   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
14080b57cec5SDimitry Andric   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
14090b57cec5SDimitry Andric   config->endianness = config->isLE ? endianness::little : endianness::big;
14100b57cec5SDimitry Andric   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
14110b57cec5SDimitry Andric   config->isPic = config->pie || config->shared;
14120b57cec5SDimitry Andric   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
14130b57cec5SDimitry Andric   config->wordsize = config->is64 ? 8 : 4;
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric   // ELF defines two different ways to store relocation addends as shown below:
14160b57cec5SDimitry Andric   //
14175ffd83dbSDimitry Andric   //  Rel: Addends are stored to the location where relocations are applied. It
14185ffd83dbSDimitry Andric   //  cannot pack the full range of addend values for all relocation types, but
14195ffd83dbSDimitry Andric   //  this only affects relocation types that we don't support emitting as
14205ffd83dbSDimitry Andric   //  dynamic relocations (see getDynRel).
14210b57cec5SDimitry Andric   //  Rela: Addends are stored as part of relocation entry.
14220b57cec5SDimitry Andric   //
14230b57cec5SDimitry Andric   // In other words, Rela makes it easy to read addends at the price of extra
14245ffd83dbSDimitry Andric   // 4 or 8 byte for each relocation entry.
14250b57cec5SDimitry Andric   //
14265ffd83dbSDimitry Andric   // We pick the format for dynamic relocations according to the psABI for each
14275ffd83dbSDimitry Andric   // processor, but a contrary choice can be made if the dynamic loader
14285ffd83dbSDimitry Andric   // supports.
14295ffd83dbSDimitry Andric   config->isRela = getIsRela(args);
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric   // If the output uses REL relocations we must store the dynamic relocation
14320b57cec5SDimitry Andric   // addends to the output sections. We also store addends for RELA relocations
14330b57cec5SDimitry Andric   // if --apply-dynamic-relocs is used.
14340b57cec5SDimitry Andric   // We default to not writing the addends when using RELA relocations since
14350b57cec5SDimitry Andric   // any standard conforming tool can find it in r_addend.
14360b57cec5SDimitry Andric   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
14370b57cec5SDimitry Andric                                       OPT_no_apply_dynamic_relocs, false) ||
14380b57cec5SDimitry Andric                          !config->isRela;
1439fe6060f1SDimitry Andric   // Validation of dynamic relocation addends is on by default for assertions
1440fe6060f1SDimitry Andric   // builds (for supported targets) and disabled otherwise. Ideally we would
1441fe6060f1SDimitry Andric   // enable the debug checks for all targets, but currently not all targets
1442fe6060f1SDimitry Andric   // have support for reading Elf_Rel addends, so we only enable for a subset.
1443fe6060f1SDimitry Andric #ifndef NDEBUG
1444fe6060f1SDimitry Andric   bool checkDynamicRelocsDefault = m == EM_ARM || m == EM_386 || m == EM_MIPS ||
1445fe6060f1SDimitry Andric                                    m == EM_X86_64 || m == EM_RISCV;
1446fe6060f1SDimitry Andric #else
1447fe6060f1SDimitry Andric   bool checkDynamicRelocsDefault = false;
1448fe6060f1SDimitry Andric #endif
1449fe6060f1SDimitry Andric   config->checkDynamicRelocs =
1450fe6060f1SDimitry Andric       args.hasFlag(OPT_check_dynamic_relocations,
1451fe6060f1SDimitry Andric                    OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);
14520b57cec5SDimitry Andric   config->tocOptimize =
14530b57cec5SDimitry Andric       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1454e8d8bef9SDimitry Andric   config->pcRelOptimize =
1455e8d8bef9SDimitry Andric       args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
14560b57cec5SDimitry Andric }
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric static bool isFormatBinary(StringRef s) {
14590b57cec5SDimitry Andric   if (s == "binary")
14600b57cec5SDimitry Andric     return true;
14610b57cec5SDimitry Andric   if (s == "elf" || s == "default")
14620b57cec5SDimitry Andric     return false;
1463*349cc55cSDimitry Andric   error("unknown --format value: " + s +
14640b57cec5SDimitry Andric         " (supported formats: elf, default, binary)");
14650b57cec5SDimitry Andric   return false;
14660b57cec5SDimitry Andric }
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric void LinkerDriver::createFiles(opt::InputArgList &args) {
1469e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Load input files");
14700b57cec5SDimitry Andric   // For --{push,pop}-state.
14710b57cec5SDimitry Andric   std::vector<std::tuple<bool, bool, bool>> stack;
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric   // Iterate over argv to process input files and positional arguments.
1474e8d8bef9SDimitry Andric   InputFile::isInGroup = false;
14750b57cec5SDimitry Andric   for (auto *arg : args) {
14760b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
14770b57cec5SDimitry Andric     case OPT_library:
14780b57cec5SDimitry Andric       addLibrary(arg->getValue());
14790b57cec5SDimitry Andric       break;
14800b57cec5SDimitry Andric     case OPT_INPUT:
14810b57cec5SDimitry Andric       addFile(arg->getValue(), /*withLOption=*/false);
14820b57cec5SDimitry Andric       break;
14830b57cec5SDimitry Andric     case OPT_defsym: {
14840b57cec5SDimitry Andric       StringRef from;
14850b57cec5SDimitry Andric       StringRef to;
14860b57cec5SDimitry Andric       std::tie(from, to) = StringRef(arg->getValue()).split('=');
14870b57cec5SDimitry Andric       if (from.empty() || to.empty())
1488*349cc55cSDimitry Andric         error("--defsym: syntax error: " + StringRef(arg->getValue()));
14890b57cec5SDimitry Andric       else
1490*349cc55cSDimitry Andric         readDefsym(from, MemoryBufferRef(to, "--defsym"));
14910b57cec5SDimitry Andric       break;
14920b57cec5SDimitry Andric     }
14930b57cec5SDimitry Andric     case OPT_script:
14940b57cec5SDimitry Andric       if (Optional<std::string> path = searchScript(arg->getValue())) {
14950b57cec5SDimitry Andric         if (Optional<MemoryBufferRef> mb = readFile(*path))
14960b57cec5SDimitry Andric           readLinkerScript(*mb);
14970b57cec5SDimitry Andric         break;
14980b57cec5SDimitry Andric       }
14990b57cec5SDimitry Andric       error(Twine("cannot find linker script ") + arg->getValue());
15000b57cec5SDimitry Andric       break;
15010b57cec5SDimitry Andric     case OPT_as_needed:
15020b57cec5SDimitry Andric       config->asNeeded = true;
15030b57cec5SDimitry Andric       break;
15040b57cec5SDimitry Andric     case OPT_format:
15050b57cec5SDimitry Andric       config->formatBinary = isFormatBinary(arg->getValue());
15060b57cec5SDimitry Andric       break;
15070b57cec5SDimitry Andric     case OPT_no_as_needed:
15080b57cec5SDimitry Andric       config->asNeeded = false;
15090b57cec5SDimitry Andric       break;
15100b57cec5SDimitry Andric     case OPT_Bstatic:
15110b57cec5SDimitry Andric     case OPT_omagic:
15120b57cec5SDimitry Andric     case OPT_nmagic:
15130b57cec5SDimitry Andric       config->isStatic = true;
15140b57cec5SDimitry Andric       break;
15150b57cec5SDimitry Andric     case OPT_Bdynamic:
15160b57cec5SDimitry Andric       config->isStatic = false;
15170b57cec5SDimitry Andric       break;
15180b57cec5SDimitry Andric     case OPT_whole_archive:
15190b57cec5SDimitry Andric       inWholeArchive = true;
15200b57cec5SDimitry Andric       break;
15210b57cec5SDimitry Andric     case OPT_no_whole_archive:
15220b57cec5SDimitry Andric       inWholeArchive = false;
15230b57cec5SDimitry Andric       break;
15240b57cec5SDimitry Andric     case OPT_just_symbols:
15250b57cec5SDimitry Andric       if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
15260b57cec5SDimitry Andric         files.push_back(createObjectFile(*mb));
15270b57cec5SDimitry Andric         files.back()->justSymbols = true;
15280b57cec5SDimitry Andric       }
15290b57cec5SDimitry Andric       break;
15300b57cec5SDimitry Andric     case OPT_start_group:
15310b57cec5SDimitry Andric       if (InputFile::isInGroup)
15320b57cec5SDimitry Andric         error("nested --start-group");
15330b57cec5SDimitry Andric       InputFile::isInGroup = true;
15340b57cec5SDimitry Andric       break;
15350b57cec5SDimitry Andric     case OPT_end_group:
15360b57cec5SDimitry Andric       if (!InputFile::isInGroup)
15370b57cec5SDimitry Andric         error("stray --end-group");
15380b57cec5SDimitry Andric       InputFile::isInGroup = false;
15390b57cec5SDimitry Andric       ++InputFile::nextGroupId;
15400b57cec5SDimitry Andric       break;
15410b57cec5SDimitry Andric     case OPT_start_lib:
15420b57cec5SDimitry Andric       if (inLib)
15430b57cec5SDimitry Andric         error("nested --start-lib");
15440b57cec5SDimitry Andric       if (InputFile::isInGroup)
15450b57cec5SDimitry Andric         error("may not nest --start-lib in --start-group");
15460b57cec5SDimitry Andric       inLib = true;
15470b57cec5SDimitry Andric       InputFile::isInGroup = true;
15480b57cec5SDimitry Andric       break;
15490b57cec5SDimitry Andric     case OPT_end_lib:
15500b57cec5SDimitry Andric       if (!inLib)
15510b57cec5SDimitry Andric         error("stray --end-lib");
15520b57cec5SDimitry Andric       inLib = false;
15530b57cec5SDimitry Andric       InputFile::isInGroup = false;
15540b57cec5SDimitry Andric       ++InputFile::nextGroupId;
15550b57cec5SDimitry Andric       break;
15560b57cec5SDimitry Andric     case OPT_push_state:
15570b57cec5SDimitry Andric       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
15580b57cec5SDimitry Andric       break;
15590b57cec5SDimitry Andric     case OPT_pop_state:
15600b57cec5SDimitry Andric       if (stack.empty()) {
15610b57cec5SDimitry Andric         error("unbalanced --push-state/--pop-state");
15620b57cec5SDimitry Andric         break;
15630b57cec5SDimitry Andric       }
15640b57cec5SDimitry Andric       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
15650b57cec5SDimitry Andric       stack.pop_back();
15660b57cec5SDimitry Andric       break;
15670b57cec5SDimitry Andric     }
15680b57cec5SDimitry Andric   }
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric   if (files.empty() && errorCount() == 0)
15710b57cec5SDimitry Andric     error("no input files");
15720b57cec5SDimitry Andric }
15730b57cec5SDimitry Andric 
15740b57cec5SDimitry Andric // If -m <machine_type> was not given, infer it from object files.
15750b57cec5SDimitry Andric void LinkerDriver::inferMachineType() {
15760b57cec5SDimitry Andric   if (config->ekind != ELFNoneKind)
15770b57cec5SDimitry Andric     return;
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric   for (InputFile *f : files) {
15800b57cec5SDimitry Andric     if (f->ekind == ELFNoneKind)
15810b57cec5SDimitry Andric       continue;
15820b57cec5SDimitry Andric     config->ekind = f->ekind;
15830b57cec5SDimitry Andric     config->emachine = f->emachine;
15840b57cec5SDimitry Andric     config->osabi = f->osabi;
15850b57cec5SDimitry Andric     config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
15860b57cec5SDimitry Andric     return;
15870b57cec5SDimitry Andric   }
15880b57cec5SDimitry Andric   error("target emulation unknown: -m or at least one .o file required");
15890b57cec5SDimitry Andric }
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric // Parse -z max-page-size=<value>. The default value is defined by
15920b57cec5SDimitry Andric // each target.
15930b57cec5SDimitry Andric static uint64_t getMaxPageSize(opt::InputArgList &args) {
15940b57cec5SDimitry Andric   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
15950b57cec5SDimitry Andric                                        target->defaultMaxPageSize);
15960b57cec5SDimitry Andric   if (!isPowerOf2_64(val))
15970b57cec5SDimitry Andric     error("max-page-size: value isn't a power of 2");
15980b57cec5SDimitry Andric   if (config->nmagic || config->omagic) {
15990b57cec5SDimitry Andric     if (val != target->defaultMaxPageSize)
16000b57cec5SDimitry Andric       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
16010b57cec5SDimitry Andric     return 1;
16020b57cec5SDimitry Andric   }
16030b57cec5SDimitry Andric   return val;
16040b57cec5SDimitry Andric }
16050b57cec5SDimitry Andric 
16060b57cec5SDimitry Andric // Parse -z common-page-size=<value>. The default value is defined by
16070b57cec5SDimitry Andric // each target.
16080b57cec5SDimitry Andric static uint64_t getCommonPageSize(opt::InputArgList &args) {
16090b57cec5SDimitry Andric   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
16100b57cec5SDimitry Andric                                        target->defaultCommonPageSize);
16110b57cec5SDimitry Andric   if (!isPowerOf2_64(val))
16120b57cec5SDimitry Andric     error("common-page-size: value isn't a power of 2");
16130b57cec5SDimitry Andric   if (config->nmagic || config->omagic) {
16140b57cec5SDimitry Andric     if (val != target->defaultCommonPageSize)
16150b57cec5SDimitry Andric       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
16160b57cec5SDimitry Andric     return 1;
16170b57cec5SDimitry Andric   }
16180b57cec5SDimitry Andric   // commonPageSize can't be larger than maxPageSize.
16190b57cec5SDimitry Andric   if (val > config->maxPageSize)
16200b57cec5SDimitry Andric     val = config->maxPageSize;
16210b57cec5SDimitry Andric   return val;
16220b57cec5SDimitry Andric }
16230b57cec5SDimitry Andric 
1624*349cc55cSDimitry Andric // Parses --image-base option.
16250b57cec5SDimitry Andric static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
16260b57cec5SDimitry Andric   // Because we are using "Config->maxPageSize" here, this function has to be
16270b57cec5SDimitry Andric   // called after the variable is initialized.
16280b57cec5SDimitry Andric   auto *arg = args.getLastArg(OPT_image_base);
16290b57cec5SDimitry Andric   if (!arg)
16300b57cec5SDimitry Andric     return None;
16310b57cec5SDimitry Andric 
16320b57cec5SDimitry Andric   StringRef s = arg->getValue();
16330b57cec5SDimitry Andric   uint64_t v;
16340b57cec5SDimitry Andric   if (!to_integer(s, v)) {
1635*349cc55cSDimitry Andric     error("--image-base: number expected, but got " + s);
16360b57cec5SDimitry Andric     return 0;
16370b57cec5SDimitry Andric   }
16380b57cec5SDimitry Andric   if ((v % config->maxPageSize) != 0)
1639*349cc55cSDimitry Andric     warn("--image-base: address isn't multiple of page size: " + s);
16400b57cec5SDimitry Andric   return v;
16410b57cec5SDimitry Andric }
16420b57cec5SDimitry Andric 
16430b57cec5SDimitry Andric // Parses `--exclude-libs=lib,lib,...`.
16440b57cec5SDimitry Andric // The library names may be delimited by commas or colons.
16450b57cec5SDimitry Andric static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
16460b57cec5SDimitry Andric   DenseSet<StringRef> ret;
16470b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_exclude_libs)) {
16480b57cec5SDimitry Andric     StringRef s = arg->getValue();
16490b57cec5SDimitry Andric     for (;;) {
16500b57cec5SDimitry Andric       size_t pos = s.find_first_of(",:");
16510b57cec5SDimitry Andric       if (pos == StringRef::npos)
16520b57cec5SDimitry Andric         break;
16530b57cec5SDimitry Andric       ret.insert(s.substr(0, pos));
16540b57cec5SDimitry Andric       s = s.substr(pos + 1);
16550b57cec5SDimitry Andric     }
16560b57cec5SDimitry Andric     ret.insert(s);
16570b57cec5SDimitry Andric   }
16580b57cec5SDimitry Andric   return ret;
16590b57cec5SDimitry Andric }
16600b57cec5SDimitry Andric 
1661*349cc55cSDimitry Andric // Handles the --exclude-libs option. If a static library file is specified
1662*349cc55cSDimitry Andric // by the --exclude-libs option, all public symbols from the archive become
16630b57cec5SDimitry Andric // private unless otherwise specified by version scripts or something.
16640b57cec5SDimitry Andric // A special library name "ALL" means all archive files.
16650b57cec5SDimitry Andric //
16660b57cec5SDimitry Andric // This is not a popular option, but some programs such as bionic libc use it.
16670b57cec5SDimitry Andric static void excludeLibs(opt::InputArgList &args) {
16680b57cec5SDimitry Andric   DenseSet<StringRef> libs = getExcludeLibs(args);
16690b57cec5SDimitry Andric   bool all = libs.count("ALL");
16700b57cec5SDimitry Andric 
16710b57cec5SDimitry Andric   auto visit = [&](InputFile *file) {
16720b57cec5SDimitry Andric     if (!file->archiveName.empty())
16730b57cec5SDimitry Andric       if (all || libs.count(path::filename(file->archiveName)))
16740b57cec5SDimitry Andric         for (Symbol *sym : file->getSymbols())
1675480093f4SDimitry Andric           if (!sym->isUndefined() && !sym->isLocal() && sym->file == file)
16760b57cec5SDimitry Andric             sym->versionId = VER_NDX_LOCAL;
16770b57cec5SDimitry Andric   };
16780b57cec5SDimitry Andric 
16790b57cec5SDimitry Andric   for (InputFile *file : objectFiles)
16800b57cec5SDimitry Andric     visit(file);
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric   for (BitcodeFile *file : bitcodeFiles)
16830b57cec5SDimitry Andric     visit(file);
16840b57cec5SDimitry Andric }
16850b57cec5SDimitry Andric 
16865ffd83dbSDimitry Andric // Force Sym to be entered in the output.
1687*349cc55cSDimitry Andric static void handleUndefined(Symbol *sym, const char *option) {
16880b57cec5SDimitry Andric   // Since a symbol may not be used inside the program, LTO may
16890b57cec5SDimitry Andric   // eliminate it. Mark the symbol as "used" to prevent it.
16900b57cec5SDimitry Andric   sym->isUsedInRegularObj = true;
16910b57cec5SDimitry Andric 
1692*349cc55cSDimitry Andric   if (!sym->isLazy())
1693*349cc55cSDimitry Andric     return;
16940b57cec5SDimitry Andric   sym->fetch();
1695*349cc55cSDimitry Andric   if (!config->whyExtract.empty())
1696*349cc55cSDimitry Andric     whyExtract.emplace_back(option, sym->file, *sym);
16970b57cec5SDimitry Andric }
16980b57cec5SDimitry Andric 
1699480093f4SDimitry Andric // As an extension to GNU linkers, lld supports a variant of `-u`
17000b57cec5SDimitry Andric // which accepts wildcard patterns. All symbols that match a given
17010b57cec5SDimitry Andric // pattern are handled as if they were given by `-u`.
17020b57cec5SDimitry Andric static void handleUndefinedGlob(StringRef arg) {
17030b57cec5SDimitry Andric   Expected<GlobPattern> pat = GlobPattern::create(arg);
17040b57cec5SDimitry Andric   if (!pat) {
17050b57cec5SDimitry Andric     error("--undefined-glob: " + toString(pat.takeError()));
17060b57cec5SDimitry Andric     return;
17070b57cec5SDimitry Andric   }
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   std::vector<Symbol *> syms;
1710480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols()) {
17110b57cec5SDimitry Andric     // Calling Sym->fetch() from here is not safe because it may
17120b57cec5SDimitry Andric     // add new symbols to the symbol table, invalidating the
17130b57cec5SDimitry Andric     // current iterator. So we just keep a note.
17140b57cec5SDimitry Andric     if (pat->match(sym->getName()))
17150b57cec5SDimitry Andric       syms.push_back(sym);
1716480093f4SDimitry Andric   }
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   for (Symbol *sym : syms)
1719*349cc55cSDimitry Andric     handleUndefined(sym, "--undefined-glob");
17200b57cec5SDimitry Andric }
17210b57cec5SDimitry Andric 
17220b57cec5SDimitry Andric static void handleLibcall(StringRef name) {
17230b57cec5SDimitry Andric   Symbol *sym = symtab->find(name);
17240b57cec5SDimitry Andric   if (!sym || !sym->isLazy())
17250b57cec5SDimitry Andric     return;
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   MemoryBufferRef mb;
17280b57cec5SDimitry Andric   if (auto *lo = dyn_cast<LazyObject>(sym))
17290b57cec5SDimitry Andric     mb = lo->file->mb;
17300b57cec5SDimitry Andric   else
17310b57cec5SDimitry Andric     mb = cast<LazyArchive>(sym)->getMemberBuffer();
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   if (isBitcode(mb))
17340b57cec5SDimitry Andric     sym->fetch();
17350b57cec5SDimitry Andric }
17360b57cec5SDimitry Andric 
1737e8d8bef9SDimitry Andric // Handle --dependency-file=<path>. If that option is given, lld creates a
1738e8d8bef9SDimitry Andric // file at a given path with the following contents:
1739e8d8bef9SDimitry Andric //
1740e8d8bef9SDimitry Andric //   <output-file>: <input-file> ...
1741e8d8bef9SDimitry Andric //
1742e8d8bef9SDimitry Andric //   <input-file>:
1743e8d8bef9SDimitry Andric //
1744e8d8bef9SDimitry Andric // where <output-file> is a pathname of an output file and <input-file>
1745e8d8bef9SDimitry Andric // ... is a list of pathnames of all input files. `make` command can read a
1746e8d8bef9SDimitry Andric // file in the above format and interpret it as a dependency info. We write
1747e8d8bef9SDimitry Andric // phony targets for every <input-file> to avoid an error when that file is
1748e8d8bef9SDimitry Andric // removed.
1749e8d8bef9SDimitry Andric //
1750e8d8bef9SDimitry Andric // This option is useful if you want to make your final executable to depend
1751e8d8bef9SDimitry Andric // on all input files including system libraries. Here is why.
1752e8d8bef9SDimitry Andric //
1753e8d8bef9SDimitry Andric // When you write a Makefile, you usually write it so that the final
1754e8d8bef9SDimitry Andric // executable depends on all user-generated object files. Normally, you
1755e8d8bef9SDimitry Andric // don't make your executable to depend on system libraries (such as libc)
1756e8d8bef9SDimitry Andric // because you don't know the exact paths of libraries, even though system
1757e8d8bef9SDimitry Andric // libraries that are linked to your executable statically are technically a
1758e8d8bef9SDimitry Andric // part of your program. By using --dependency-file option, you can make
1759e8d8bef9SDimitry Andric // lld to dump dependency info so that you can maintain exact dependencies
1760e8d8bef9SDimitry Andric // easily.
1761e8d8bef9SDimitry Andric static void writeDependencyFile() {
1762e8d8bef9SDimitry Andric   std::error_code ec;
1763fe6060f1SDimitry Andric   raw_fd_ostream os(config->dependencyFile, ec, sys::fs::OF_None);
1764e8d8bef9SDimitry Andric   if (ec) {
1765e8d8bef9SDimitry Andric     error("cannot open " + config->dependencyFile + ": " + ec.message());
1766e8d8bef9SDimitry Andric     return;
1767e8d8bef9SDimitry Andric   }
1768e8d8bef9SDimitry Andric 
1769e8d8bef9SDimitry Andric   // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
1770e8d8bef9SDimitry Andric   // * A space is escaped by a backslash which itself must be escaped.
1771e8d8bef9SDimitry Andric   // * A hash sign is escaped by a single backslash.
1772e8d8bef9SDimitry Andric   // * $ is escapes as $$.
1773e8d8bef9SDimitry Andric   auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
1774e8d8bef9SDimitry Andric     llvm::SmallString<256> nativePath;
1775e8d8bef9SDimitry Andric     llvm::sys::path::native(filename.str(), nativePath);
1776e8d8bef9SDimitry Andric     llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
1777e8d8bef9SDimitry Andric     for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
1778e8d8bef9SDimitry Andric       if (nativePath[i] == '#') {
1779e8d8bef9SDimitry Andric         os << '\\';
1780e8d8bef9SDimitry Andric       } else if (nativePath[i] == ' ') {
1781e8d8bef9SDimitry Andric         os << '\\';
1782e8d8bef9SDimitry Andric         unsigned j = i;
1783e8d8bef9SDimitry Andric         while (j > 0 && nativePath[--j] == '\\')
1784e8d8bef9SDimitry Andric           os << '\\';
1785e8d8bef9SDimitry Andric       } else if (nativePath[i] == '$') {
1786e8d8bef9SDimitry Andric         os << '$';
1787e8d8bef9SDimitry Andric       }
1788e8d8bef9SDimitry Andric       os << nativePath[i];
1789e8d8bef9SDimitry Andric     }
1790e8d8bef9SDimitry Andric   };
1791e8d8bef9SDimitry Andric 
1792e8d8bef9SDimitry Andric   os << config->outputFile << ":";
1793e8d8bef9SDimitry Andric   for (StringRef path : config->dependencyFiles) {
1794e8d8bef9SDimitry Andric     os << " \\\n ";
1795e8d8bef9SDimitry Andric     printFilename(os, path);
1796e8d8bef9SDimitry Andric   }
1797e8d8bef9SDimitry Andric   os << "\n";
1798e8d8bef9SDimitry Andric 
1799e8d8bef9SDimitry Andric   for (StringRef path : config->dependencyFiles) {
1800e8d8bef9SDimitry Andric     os << "\n";
1801e8d8bef9SDimitry Andric     printFilename(os, path);
1802e8d8bef9SDimitry Andric     os << ":\n";
1803e8d8bef9SDimitry Andric   }
1804e8d8bef9SDimitry Andric }
1805e8d8bef9SDimitry Andric 
18060b57cec5SDimitry Andric // Replaces common symbols with defined symbols reside in .bss sections.
18070b57cec5SDimitry Andric // This function is called after all symbol names are resolved. As a
18080b57cec5SDimitry Andric // result, the passes after the symbol resolution won't see any
18090b57cec5SDimitry Andric // symbols of type CommonSymbol.
18100b57cec5SDimitry Andric static void replaceCommonSymbols() {
1811e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Replace common symbols");
1812480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols()) {
18130b57cec5SDimitry Andric     auto *s = dyn_cast<CommonSymbol>(sym);
18140b57cec5SDimitry Andric     if (!s)
1815480093f4SDimitry Andric       continue;
18160b57cec5SDimitry Andric 
18170b57cec5SDimitry Andric     auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
18180b57cec5SDimitry Andric     bss->file = s->file;
18190b57cec5SDimitry Andric     bss->markDead();
18200b57cec5SDimitry Andric     inputSections.push_back(bss);
18210b57cec5SDimitry Andric     s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
18220b57cec5SDimitry Andric                        /*value=*/0, s->size, bss});
1823480093f4SDimitry Andric   }
18240b57cec5SDimitry Andric }
18250b57cec5SDimitry Andric 
18260b57cec5SDimitry Andric // If all references to a DSO happen to be weak, the DSO is not added
18270b57cec5SDimitry Andric // to DT_NEEDED. If that happens, we need to eliminate shared symbols
18280b57cec5SDimitry Andric // created from the DSO. Otherwise, they become dangling references
18290b57cec5SDimitry Andric // that point to a non-existent DSO.
18300b57cec5SDimitry Andric static void demoteSharedSymbols() {
1831e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Demote shared symbols");
1832480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols()) {
18330b57cec5SDimitry Andric     auto *s = dyn_cast<SharedSymbol>(sym);
1834*349cc55cSDimitry Andric     if (!((s && !s->getFile().isNeeded) ||
1835*349cc55cSDimitry Andric           (sym->isLazy() && sym->isUsedInRegularObj)))
1836480093f4SDimitry Andric       continue;
18370b57cec5SDimitry Andric 
1838*349cc55cSDimitry Andric     bool used = sym->used;
1839*349cc55cSDimitry Andric     sym->replace(
1840*349cc55cSDimitry Andric         Undefined{nullptr, sym->getName(), STB_WEAK, sym->stOther, sym->type});
1841*349cc55cSDimitry Andric     sym->used = used;
1842*349cc55cSDimitry Andric     sym->versionId = VER_NDX_GLOBAL;
1843480093f4SDimitry Andric   }
18440b57cec5SDimitry Andric }
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric // The section referred to by `s` is considered address-significant. Set the
18470b57cec5SDimitry Andric // keepUnique flag on the section if appropriate.
18480b57cec5SDimitry Andric static void markAddrsig(Symbol *s) {
18490b57cec5SDimitry Andric   if (auto *d = dyn_cast_or_null<Defined>(s))
18500b57cec5SDimitry Andric     if (d->section)
18510b57cec5SDimitry Andric       // We don't need to keep text sections unique under --icf=all even if they
18520b57cec5SDimitry Andric       // are address-significant.
18530b57cec5SDimitry Andric       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
18540b57cec5SDimitry Andric         d->section->keepUnique = true;
18550b57cec5SDimitry Andric }
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric // Record sections that define symbols mentioned in --keep-unique <symbol>
18580b57cec5SDimitry Andric // and symbols referred to by address-significance tables. These sections are
18590b57cec5SDimitry Andric // ineligible for ICF.
18600b57cec5SDimitry Andric template <class ELFT>
18610b57cec5SDimitry Andric static void findKeepUniqueSections(opt::InputArgList &args) {
18620b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_keep_unique)) {
18630b57cec5SDimitry Andric     StringRef name = arg->getValue();
18640b57cec5SDimitry Andric     auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
18650b57cec5SDimitry Andric     if (!d || !d->section) {
18660b57cec5SDimitry Andric       warn("could not find symbol " + name + " to keep unique");
18670b57cec5SDimitry Andric       continue;
18680b57cec5SDimitry Andric     }
18690b57cec5SDimitry Andric     d->section->keepUnique = true;
18700b57cec5SDimitry Andric   }
18710b57cec5SDimitry Andric 
18720b57cec5SDimitry Andric   // --icf=all --ignore-data-address-equality means that we can ignore
18730b57cec5SDimitry Andric   // the dynsym and address-significance tables entirely.
18740b57cec5SDimitry Andric   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
18750b57cec5SDimitry Andric     return;
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   // Symbols in the dynsym could be address-significant in other executables
18780b57cec5SDimitry Andric   // or DSOs, so we conservatively mark them as address-significant.
1879480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols())
18800b57cec5SDimitry Andric     if (sym->includeInDynsym())
18810b57cec5SDimitry Andric       markAddrsig(sym);
18820b57cec5SDimitry Andric 
18830b57cec5SDimitry Andric   // Visit the address-significance table in each object file and mark each
18840b57cec5SDimitry Andric   // referenced symbol as address-significant.
18850b57cec5SDimitry Andric   for (InputFile *f : objectFiles) {
18860b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(f);
18870b57cec5SDimitry Andric     ArrayRef<Symbol *> syms = obj->getSymbols();
18880b57cec5SDimitry Andric     if (obj->addrsigSec) {
18890b57cec5SDimitry Andric       ArrayRef<uint8_t> contents =
1890e8d8bef9SDimitry Andric           check(obj->getObj().getSectionContents(*obj->addrsigSec));
18910b57cec5SDimitry Andric       const uint8_t *cur = contents.begin();
18920b57cec5SDimitry Andric       while (cur != contents.end()) {
18930b57cec5SDimitry Andric         unsigned size;
18940b57cec5SDimitry Andric         const char *err;
18950b57cec5SDimitry Andric         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
18960b57cec5SDimitry Andric         if (err)
18970b57cec5SDimitry Andric           fatal(toString(f) + ": could not decode addrsig section: " + err);
18980b57cec5SDimitry Andric         markAddrsig(syms[symIndex]);
18990b57cec5SDimitry Andric         cur += size;
19000b57cec5SDimitry Andric       }
19010b57cec5SDimitry Andric     } else {
19020b57cec5SDimitry Andric       // If an object file does not have an address-significance table,
19030b57cec5SDimitry Andric       // conservatively mark all of its symbols as address-significant.
19040b57cec5SDimitry Andric       for (Symbol *s : syms)
19050b57cec5SDimitry Andric         markAddrsig(s);
19060b57cec5SDimitry Andric     }
19070b57cec5SDimitry Andric   }
19080b57cec5SDimitry Andric }
19090b57cec5SDimitry Andric 
19100b57cec5SDimitry Andric // This function reads a symbol partition specification section. These sections
19110b57cec5SDimitry Andric // are used to control which partition a symbol is allocated to. See
19120b57cec5SDimitry Andric // https://lld.llvm.org/Partitions.html for more details on partitions.
19130b57cec5SDimitry Andric template <typename ELFT>
19140b57cec5SDimitry Andric static void readSymbolPartitionSection(InputSectionBase *s) {
19150b57cec5SDimitry Andric   // Read the relocation that refers to the partition's entry point symbol.
19160b57cec5SDimitry Andric   Symbol *sym;
1917*349cc55cSDimitry Andric   const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
1918*349cc55cSDimitry Andric   if (rels.areRelocsRel())
1919*349cc55cSDimitry Andric     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]);
19200b57cec5SDimitry Andric   else
1921*349cc55cSDimitry Andric     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]);
19220b57cec5SDimitry Andric   if (!isa<Defined>(sym) || !sym->includeInDynsym())
19230b57cec5SDimitry Andric     return;
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric   StringRef partName = reinterpret_cast<const char *>(s->data().data());
19260b57cec5SDimitry Andric   for (Partition &part : partitions) {
19270b57cec5SDimitry Andric     if (part.name == partName) {
19280b57cec5SDimitry Andric       sym->partition = part.getNumber();
19290b57cec5SDimitry Andric       return;
19300b57cec5SDimitry Andric     }
19310b57cec5SDimitry Andric   }
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric   // Forbid partitions from being used on incompatible targets, and forbid them
19340b57cec5SDimitry Andric   // from being used together with various linker features that assume a single
19350b57cec5SDimitry Andric   // set of output sections.
19360b57cec5SDimitry Andric   if (script->hasSectionsCommand)
19370b57cec5SDimitry Andric     error(toString(s->file) +
19380b57cec5SDimitry Andric           ": partitions cannot be used with the SECTIONS command");
19390b57cec5SDimitry Andric   if (script->hasPhdrsCommands())
19400b57cec5SDimitry Andric     error(toString(s->file) +
19410b57cec5SDimitry Andric           ": partitions cannot be used with the PHDRS command");
19420b57cec5SDimitry Andric   if (!config->sectionStartMap.empty())
19430b57cec5SDimitry Andric     error(toString(s->file) + ": partitions cannot be used with "
19440b57cec5SDimitry Andric                               "--section-start, -Ttext, -Tdata or -Tbss");
19450b57cec5SDimitry Andric   if (config->emachine == EM_MIPS)
19460b57cec5SDimitry Andric     error(toString(s->file) + ": partitions cannot be used on this target");
19470b57cec5SDimitry Andric 
19480b57cec5SDimitry Andric   // Impose a limit of no more than 254 partitions. This limit comes from the
19490b57cec5SDimitry Andric   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
19500b57cec5SDimitry Andric   // the amount of space devoted to the partition number in RankFlags.
19510b57cec5SDimitry Andric   if (partitions.size() == 254)
19520b57cec5SDimitry Andric     fatal("may not have more than 254 partitions");
19530b57cec5SDimitry Andric 
19540b57cec5SDimitry Andric   partitions.emplace_back();
19550b57cec5SDimitry Andric   Partition &newPart = partitions.back();
19560b57cec5SDimitry Andric   newPart.name = partName;
19570b57cec5SDimitry Andric   sym->partition = newPart.getNumber();
19580b57cec5SDimitry Andric }
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric static Symbol *addUndefined(StringRef name) {
19610b57cec5SDimitry Andric   return symtab->addSymbol(
19620b57cec5SDimitry Andric       Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
19630b57cec5SDimitry Andric }
19640b57cec5SDimitry Andric 
1965fe6060f1SDimitry Andric static Symbol *addUnusedUndefined(StringRef name,
1966fe6060f1SDimitry Andric                                   uint8_t binding = STB_GLOBAL) {
1967fe6060f1SDimitry Andric   Undefined sym{nullptr, name, binding, STV_DEFAULT, 0};
19685ffd83dbSDimitry Andric   sym.isUsedInRegularObj = false;
19695ffd83dbSDimitry Andric   return symtab->addSymbol(sym);
19705ffd83dbSDimitry Andric }
19715ffd83dbSDimitry Andric 
19720b57cec5SDimitry Andric // This function is where all the optimizations of link-time
19730b57cec5SDimitry Andric // optimization takes place. When LTO is in use, some input files are
19740b57cec5SDimitry Andric // not in native object file format but in the LLVM bitcode format.
19750b57cec5SDimitry Andric // This function compiles bitcode files into a few big native files
19760b57cec5SDimitry Andric // using LLVM functions and replaces bitcode symbols with the results.
19770b57cec5SDimitry Andric // Because all bitcode files that the program consists of are passed to
19780b57cec5SDimitry Andric // the compiler at once, it can do a whole-program optimization.
19790b57cec5SDimitry Andric template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
19805ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("LTO");
19810b57cec5SDimitry Andric   // Compile bitcode files and replace bitcode symbols.
19820b57cec5SDimitry Andric   lto.reset(new BitcodeCompiler);
19830b57cec5SDimitry Andric   for (BitcodeFile *file : bitcodeFiles)
19840b57cec5SDimitry Andric     lto->add(*file);
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric   for (InputFile *file : lto->compile()) {
19870b57cec5SDimitry Andric     auto *obj = cast<ObjFile<ELFT>>(file);
19880b57cec5SDimitry Andric     obj->parse(/*ignoreComdats=*/true);
19895ffd83dbSDimitry Andric 
19905ffd83dbSDimitry Andric     // Parse '@' in symbol names for non-relocatable output.
19915ffd83dbSDimitry Andric     if (!config->relocatable)
19920b57cec5SDimitry Andric       for (Symbol *sym : obj->getGlobalSymbols())
19930b57cec5SDimitry Andric         sym->parseSymbolVersion();
19940b57cec5SDimitry Andric     objectFiles.push_back(file);
19950b57cec5SDimitry Andric   }
19960b57cec5SDimitry Andric }
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric // The --wrap option is a feature to rename symbols so that you can write
1999*349cc55cSDimitry Andric // wrappers for existing functions. If you pass `--wrap=foo`, all
2000e8d8bef9SDimitry Andric // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
2001e8d8bef9SDimitry Andric // expected to write `__wrap_foo` function as a wrapper). The original
2002e8d8bef9SDimitry Andric // symbol becomes accessible as `__real_foo`, so you can call that from your
20030b57cec5SDimitry Andric // wrapper.
20040b57cec5SDimitry Andric //
2005*349cc55cSDimitry Andric // This data structure is instantiated for each --wrap option.
20060b57cec5SDimitry Andric struct WrappedSymbol {
20070b57cec5SDimitry Andric   Symbol *sym;
20080b57cec5SDimitry Andric   Symbol *real;
20090b57cec5SDimitry Andric   Symbol *wrap;
20100b57cec5SDimitry Andric };
20110b57cec5SDimitry Andric 
2012*349cc55cSDimitry Andric // Handles --wrap option.
20130b57cec5SDimitry Andric //
20140b57cec5SDimitry Andric // This function instantiates wrapper symbols. At this point, they seem
20150b57cec5SDimitry Andric // like they are not being used at all, so we explicitly set some flags so
20160b57cec5SDimitry Andric // that LTO won't eliminate them.
20170b57cec5SDimitry Andric static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
20180b57cec5SDimitry Andric   std::vector<WrappedSymbol> v;
20190b57cec5SDimitry Andric   DenseSet<StringRef> seen;
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wrap)) {
20220b57cec5SDimitry Andric     StringRef name = arg->getValue();
20230b57cec5SDimitry Andric     if (!seen.insert(name).second)
20240b57cec5SDimitry Andric       continue;
20250b57cec5SDimitry Andric 
20260b57cec5SDimitry Andric     Symbol *sym = symtab->find(name);
20270b57cec5SDimitry Andric     if (!sym)
20280b57cec5SDimitry Andric       continue;
20290b57cec5SDimitry Andric 
2030e8d8bef9SDimitry Andric     Symbol *real = addUnusedUndefined(saver.save("__real_" + name));
2031fe6060f1SDimitry Andric     Symbol *wrap =
2032fe6060f1SDimitry Andric         addUnusedUndefined(saver.save("__wrap_" + name), sym->binding);
20330b57cec5SDimitry Andric     v.push_back({sym, real, wrap});
20340b57cec5SDimitry Andric 
20350b57cec5SDimitry Andric     // We want to tell LTO not to inline symbols to be overwritten
20360b57cec5SDimitry Andric     // because LTO doesn't know the final symbol contents after renaming.
20370b57cec5SDimitry Andric     real->canInline = false;
20380b57cec5SDimitry Andric     sym->canInline = false;
20390b57cec5SDimitry Andric 
20400b57cec5SDimitry Andric     // Tell LTO not to eliminate these symbols.
20410b57cec5SDimitry Andric     sym->isUsedInRegularObj = true;
2042e8d8bef9SDimitry Andric     // If sym is referenced in any object file, bitcode file or shared object,
2043e8d8bef9SDimitry Andric     // retain wrap which is the redirection target of sym. If the object file
2044e8d8bef9SDimitry Andric     // defining sym has sym references, we cannot easily distinguish the case
2045e8d8bef9SDimitry Andric     // from cases where sym is not referenced. Retain wrap because we choose to
2046e8d8bef9SDimitry Andric     // wrap sym references regardless of whether sym is defined
2047e8d8bef9SDimitry Andric     // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
2048e8d8bef9SDimitry Andric     if (sym->referenced || sym->isDefined())
20490b57cec5SDimitry Andric       wrap->isUsedInRegularObj = true;
20500b57cec5SDimitry Andric   }
20510b57cec5SDimitry Andric   return v;
20520b57cec5SDimitry Andric }
20530b57cec5SDimitry Andric 
2054*349cc55cSDimitry Andric // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
20550b57cec5SDimitry Andric //
20560b57cec5SDimitry Andric // When this function is executed, only InputFiles and symbol table
20570b57cec5SDimitry Andric // contain pointers to symbol objects. We visit them to replace pointers,
20580b57cec5SDimitry Andric // so that wrapped symbols are swapped as instructed by the command line.
2059e8d8bef9SDimitry Andric static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) {
2060e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Redirect symbols");
20610b57cec5SDimitry Andric   DenseMap<Symbol *, Symbol *> map;
20620b57cec5SDimitry Andric   for (const WrappedSymbol &w : wrapped) {
20630b57cec5SDimitry Andric     map[w.sym] = w.wrap;
20640b57cec5SDimitry Andric     map[w.real] = w.sym;
20650b57cec5SDimitry Andric   }
2066e8d8bef9SDimitry Andric   for (Symbol *sym : symtab->symbols()) {
2067e8d8bef9SDimitry Andric     // Enumerate symbols with a non-default version (foo@v1).
2068e8d8bef9SDimitry Andric     StringRef name = sym->getName();
2069e8d8bef9SDimitry Andric     const char *suffix1 = sym->getVersionSuffix();
2070e8d8bef9SDimitry Andric     if (suffix1[0] != '@' || suffix1[1] == '@')
2071e8d8bef9SDimitry Andric       continue;
2072e8d8bef9SDimitry Andric 
20736e75b2fbSDimitry Andric     // Check the existing symbol foo. We have two special cases to handle:
20746e75b2fbSDimitry Andric     //
20756e75b2fbSDimitry Andric     // * There is a definition of foo@v1 and foo@@v1.
20766e75b2fbSDimitry Andric     // * There is a definition of foo@v1 and foo.
20776e75b2fbSDimitry Andric     Defined *sym2 = dyn_cast_or_null<Defined>(symtab->find(name));
20786e75b2fbSDimitry Andric     if (!sym2)
2079e8d8bef9SDimitry Andric       continue;
20806e75b2fbSDimitry Andric     const char *suffix2 = sym2->getVersionSuffix();
20816e75b2fbSDimitry Andric     if (suffix2[0] == '@' && suffix2[1] == '@' &&
20826e75b2fbSDimitry Andric         strcmp(suffix1 + 1, suffix2 + 2) == 0) {
2083e8d8bef9SDimitry Andric       // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
20846e75b2fbSDimitry Andric       map.try_emplace(sym, sym2);
2085e8d8bef9SDimitry Andric       // If both foo@v1 and foo@@v1 are defined and non-weak, report a duplicate
2086e8d8bef9SDimitry Andric       // definition error.
20876e75b2fbSDimitry Andric       sym2->resolve(*sym);
2088e8d8bef9SDimitry Andric       // Eliminate foo@v1 from the symbol table.
2089e8d8bef9SDimitry Andric       sym->symbolKind = Symbol::PlaceholderKind;
20906e75b2fbSDimitry Andric     } else if (auto *sym1 = dyn_cast<Defined>(sym)) {
20916e75b2fbSDimitry Andric       if (sym2->versionId > VER_NDX_GLOBAL
20926e75b2fbSDimitry Andric               ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1
20936e75b2fbSDimitry Andric               : sym1->section == sym2->section && sym1->value == sym2->value) {
20946e75b2fbSDimitry Andric         // Due to an assembler design flaw, if foo is defined, .symver foo,
20956e75b2fbSDimitry Andric         // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2096*349cc55cSDimitry Andric         // different version, GNU ld makes foo@v1 canonical and eliminates foo.
20976e75b2fbSDimitry Andric         // Emulate its behavior, otherwise we would have foo or foo@@v1 beside
20986e75b2fbSDimitry Andric         // foo@v1. foo@v1 and foo combining does not apply if they are not
20996e75b2fbSDimitry Andric         // defined in the same place.
21006e75b2fbSDimitry Andric         map.try_emplace(sym2, sym);
21016e75b2fbSDimitry Andric         sym2->symbolKind = Symbol::PlaceholderKind;
21026e75b2fbSDimitry Andric       }
21036e75b2fbSDimitry Andric     }
2104e8d8bef9SDimitry Andric   }
2105e8d8bef9SDimitry Andric 
2106e8d8bef9SDimitry Andric   if (map.empty())
2107e8d8bef9SDimitry Andric     return;
21080b57cec5SDimitry Andric 
21090b57cec5SDimitry Andric   // Update pointers in input files.
21100b57cec5SDimitry Andric   parallelForEach(objectFiles, [&](InputFile *file) {
21110b57cec5SDimitry Andric     MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
21120b57cec5SDimitry Andric     for (size_t i = 0, e = syms.size(); i != e; ++i)
21130b57cec5SDimitry Andric       if (Symbol *s = map.lookup(syms[i]))
21140b57cec5SDimitry Andric         syms[i] = s;
21150b57cec5SDimitry Andric   });
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric   // Update pointers in the symbol table.
21180b57cec5SDimitry Andric   for (const WrappedSymbol &w : wrapped)
21190b57cec5SDimitry Andric     symtab->wrap(w.sym, w.real, w.wrap);
21200b57cec5SDimitry Andric }
21210b57cec5SDimitry Andric 
21220b57cec5SDimitry Andric // To enable CET (x86's hardware-assited control flow enforcement), each
21230b57cec5SDimitry Andric // source file must be compiled with -fcf-protection. Object files compiled
21240b57cec5SDimitry Andric // with the flag contain feature flags indicating that they are compatible
21250b57cec5SDimitry Andric // with CET. We enable the feature only when all object files are compatible
21260b57cec5SDimitry Andric // with CET.
21270b57cec5SDimitry Andric //
21280b57cec5SDimitry Andric // This is also the case with AARCH64's BTI and PAC which use the similar
21290b57cec5SDimitry Andric // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
21300b57cec5SDimitry Andric template <class ELFT> static uint32_t getAndFeatures() {
21310b57cec5SDimitry Andric   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
21320b57cec5SDimitry Andric       config->emachine != EM_AARCH64)
21330b57cec5SDimitry Andric     return 0;
21340b57cec5SDimitry Andric 
21350b57cec5SDimitry Andric   uint32_t ret = -1;
21360b57cec5SDimitry Andric   for (InputFile *f : objectFiles) {
21370b57cec5SDimitry Andric     uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
21385ffd83dbSDimitry Andric     if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
21395ffd83dbSDimitry Andric       warn(toString(f) + ": -z force-bti: file does not have "
21405ffd83dbSDimitry Andric                          "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
21410b57cec5SDimitry Andric       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
2142480093f4SDimitry Andric     } else if (config->zForceIbt &&
2143480093f4SDimitry Andric                !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
2144480093f4SDimitry Andric       warn(toString(f) + ": -z force-ibt: file does not have "
2145480093f4SDimitry Andric                          "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2146480093f4SDimitry Andric       features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
2147480093f4SDimitry Andric     }
21485ffd83dbSDimitry Andric     if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
21495ffd83dbSDimitry Andric       warn(toString(f) + ": -z pac-plt: file does not have "
21505ffd83dbSDimitry Andric                          "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
21515ffd83dbSDimitry Andric       features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
21525ffd83dbSDimitry Andric     }
21530b57cec5SDimitry Andric     ret &= features;
21540b57cec5SDimitry Andric   }
21550b57cec5SDimitry Andric 
2156480093f4SDimitry Andric   // Force enable Shadow Stack.
2157480093f4SDimitry Andric   if (config->zShstk)
2158480093f4SDimitry Andric     ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric   return ret;
21610b57cec5SDimitry Andric }
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric // Do actual linking. Note that when this function is called,
21640b57cec5SDimitry Andric // all linker scripts have already been parsed.
21650b57cec5SDimitry Andric template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
21665ffd83dbSDimitry Andric   llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
2167*349cc55cSDimitry Andric   // If a --hash-style option was not given, set to a default value,
21680b57cec5SDimitry Andric   // which varies depending on the target.
21690b57cec5SDimitry Andric   if (!args.hasArg(OPT_hash_style)) {
21700b57cec5SDimitry Andric     if (config->emachine == EM_MIPS)
21710b57cec5SDimitry Andric       config->sysvHash = true;
21720b57cec5SDimitry Andric     else
21730b57cec5SDimitry Andric       config->sysvHash = config->gnuHash = true;
21740b57cec5SDimitry Andric   }
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric   // Default output filename is "a.out" by the Unix tradition.
21770b57cec5SDimitry Andric   if (config->outputFile.empty())
21780b57cec5SDimitry Andric     config->outputFile = "a.out";
21790b57cec5SDimitry Andric 
21800b57cec5SDimitry Andric   // Fail early if the output file or map file is not writable. If a user has a
21810b57cec5SDimitry Andric   // long link, e.g. due to a large LTO link, they do not wish to run it and
21820b57cec5SDimitry Andric   // find that it failed because there was a mistake in their command-line.
2183e8d8bef9SDimitry Andric   {
2184e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Create output files");
21850b57cec5SDimitry Andric     if (auto e = tryCreateFile(config->outputFile))
2186e8d8bef9SDimitry Andric       error("cannot open output file " + config->outputFile + ": " +
2187e8d8bef9SDimitry Andric             e.message());
21880b57cec5SDimitry Andric     if (auto e = tryCreateFile(config->mapFile))
21890b57cec5SDimitry Andric       error("cannot open map file " + config->mapFile + ": " + e.message());
2190*349cc55cSDimitry Andric     if (auto e = tryCreateFile(config->whyExtract))
2191*349cc55cSDimitry Andric       error("cannot open --why-extract= file " + config->whyExtract + ": " +
2192*349cc55cSDimitry Andric             e.message());
2193e8d8bef9SDimitry Andric   }
21940b57cec5SDimitry Andric   if (errorCount())
21950b57cec5SDimitry Andric     return;
21960b57cec5SDimitry Andric 
21970b57cec5SDimitry Andric   // Use default entry point name if no name was given via the command
21980b57cec5SDimitry Andric   // line nor linker scripts. For some reason, MIPS entry point name is
21990b57cec5SDimitry Andric   // different from others.
22000b57cec5SDimitry Andric   config->warnMissingEntry =
22010b57cec5SDimitry Andric       (!config->entry.empty() || (!config->shared && !config->relocatable));
22020b57cec5SDimitry Andric   if (config->entry.empty() && !config->relocatable)
22030b57cec5SDimitry Andric     config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
22040b57cec5SDimitry Andric 
22050b57cec5SDimitry Andric   // Handle --trace-symbol.
22060b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_trace_symbol))
22070b57cec5SDimitry Andric     symtab->insert(arg->getValue())->traced = true;
22080b57cec5SDimitry Andric 
22095ffd83dbSDimitry Andric   // Handle -u/--undefined before input files. If both a.a and b.so define foo,
22105ffd83dbSDimitry Andric   // -u foo a.a b.so will fetch a.a.
22115ffd83dbSDimitry Andric   for (StringRef name : config->undefined)
2212e8d8bef9SDimitry Andric     addUnusedUndefined(name)->referenced = true;
22135ffd83dbSDimitry Andric 
22140b57cec5SDimitry Andric   // Add all files to the symbol table. This will add almost all
22150b57cec5SDimitry Andric   // symbols that we need to the symbol table. This process might
22160b57cec5SDimitry Andric   // add files to the link, via autolinking, these files are always
22170b57cec5SDimitry Andric   // appended to the Files vector.
22185ffd83dbSDimitry Andric   {
22195ffd83dbSDimitry Andric     llvm::TimeTraceScope timeScope("Parse input files");
2220e8d8bef9SDimitry Andric     for (size_t i = 0; i < files.size(); ++i) {
2221e8d8bef9SDimitry Andric       llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
22220b57cec5SDimitry Andric       parseFile(files[i]);
22235ffd83dbSDimitry Andric     }
2224e8d8bef9SDimitry Andric   }
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric   // Now that we have every file, we can decide if we will need a
22270b57cec5SDimitry Andric   // dynamic symbol table.
22280b57cec5SDimitry Andric   // We need one if we were asked to export dynamic symbols or if we are
22290b57cec5SDimitry Andric   // producing a shared library.
22300b57cec5SDimitry Andric   // We also need one if any shared libraries are used and for pie executables
22310b57cec5SDimitry Andric   // (probably because the dynamic linker needs it).
22320b57cec5SDimitry Andric   config->hasDynSymTab =
22330b57cec5SDimitry Andric       !sharedFiles.empty() || config->isPic || config->exportDynamic;
22340b57cec5SDimitry Andric 
22350b57cec5SDimitry Andric   // Some symbols (such as __ehdr_start) are defined lazily only when there
22360b57cec5SDimitry Andric   // are undefined symbols for them, so we add these to trigger that logic.
22370b57cec5SDimitry Andric   for (StringRef name : script->referencedSymbols)
22380b57cec5SDimitry Andric     addUndefined(name);
22390b57cec5SDimitry Andric 
22405ffd83dbSDimitry Andric   // Prevent LTO from removing any definition referenced by -u.
22415ffd83dbSDimitry Andric   for (StringRef name : config->undefined)
22425ffd83dbSDimitry Andric     if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name)))
22435ffd83dbSDimitry Andric       sym->isUsedInRegularObj = true;
22440b57cec5SDimitry Andric 
22450b57cec5SDimitry Andric   // If an entry symbol is in a static archive, pull out that file now.
22460b57cec5SDimitry Andric   if (Symbol *sym = symtab->find(config->entry))
2247*349cc55cSDimitry Andric     handleUndefined(sym, "--entry");
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   // Handle the `--undefined-glob <pattern>` options.
22500b57cec5SDimitry Andric   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
22510b57cec5SDimitry Andric     handleUndefinedGlob(pat);
22520b57cec5SDimitry Andric 
2253480093f4SDimitry Andric   // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
22545ffd83dbSDimitry Andric   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init)))
2255480093f4SDimitry Andric     sym->isUsedInRegularObj = true;
22565ffd83dbSDimitry Andric   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini)))
2257480093f4SDimitry Andric     sym->isUsedInRegularObj = true;
2258480093f4SDimitry Andric 
22590b57cec5SDimitry Andric   // If any of our inputs are bitcode files, the LTO code generator may create
22600b57cec5SDimitry Andric   // references to certain library functions that might not be explicit in the
22610b57cec5SDimitry Andric   // bitcode file's symbol table. If any of those library functions are defined
22620b57cec5SDimitry Andric   // in a bitcode file in an archive member, we need to arrange to use LTO to
22630b57cec5SDimitry Andric   // compile those archive members by adding them to the link beforehand.
22640b57cec5SDimitry Andric   //
22650b57cec5SDimitry Andric   // However, adding all libcall symbols to the link can have undesired
22660b57cec5SDimitry Andric   // consequences. For example, the libgcc implementation of
22670b57cec5SDimitry Andric   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
22680b57cec5SDimitry Andric   // that aborts the program if the Linux kernel does not support 64-bit
22690b57cec5SDimitry Andric   // atomics, which would prevent the program from running even if it does not
22700b57cec5SDimitry Andric   // use 64-bit atomics.
22710b57cec5SDimitry Andric   //
22720b57cec5SDimitry Andric   // Therefore, we only add libcall symbols to the link before LTO if we have
22730b57cec5SDimitry Andric   // to, i.e. if the symbol's definition is in bitcode. Any other required
22740b57cec5SDimitry Andric   // libcall symbols will be added to the link after LTO when we add the LTO
22750b57cec5SDimitry Andric   // object file to the link.
22760b57cec5SDimitry Andric   if (!bitcodeFiles.empty())
227785868e8aSDimitry Andric     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
22780b57cec5SDimitry Andric       handleLibcall(s);
22790b57cec5SDimitry Andric 
22800b57cec5SDimitry Andric   // Return if there were name resolution errors.
22810b57cec5SDimitry Andric   if (errorCount())
22820b57cec5SDimitry Andric     return;
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric   // We want to declare linker script's symbols early,
22850b57cec5SDimitry Andric   // so that we can version them.
22860b57cec5SDimitry Andric   // They also might be exported if referenced by DSOs.
22870b57cec5SDimitry Andric   script->declareSymbols();
22880b57cec5SDimitry Andric 
2289e8d8bef9SDimitry Andric   // Handle --exclude-libs. This is before scanVersionScript() due to a
2290e8d8bef9SDimitry Andric   // workaround for Android ndk: for a defined versioned symbol in an archive
2291e8d8bef9SDimitry Andric   // without a version node in the version script, Android does not expect a
2292e8d8bef9SDimitry Andric   // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2293e8d8bef9SDimitry Andric   // GNU ld errors in this case.
22940b57cec5SDimitry Andric   if (args.hasArg(OPT_exclude_libs))
22950b57cec5SDimitry Andric     excludeLibs(args);
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric   // Create elfHeader early. We need a dummy section in
22980b57cec5SDimitry Andric   // addReservedSymbols to mark the created symbols as not absolute.
22990b57cec5SDimitry Andric   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
23000b57cec5SDimitry Andric   Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
23010b57cec5SDimitry Andric 
23020b57cec5SDimitry Andric   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
23030b57cec5SDimitry Andric 
23040b57cec5SDimitry Andric   // We need to create some reserved symbols such as _end. Create them.
23050b57cec5SDimitry Andric   if (!config->relocatable)
23060b57cec5SDimitry Andric     addReservedSymbols();
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric   // Apply version scripts.
23090b57cec5SDimitry Andric   //
23100b57cec5SDimitry Andric   // For a relocatable output, version scripts don't make sense, and
23110b57cec5SDimitry Andric   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
23120b57cec5SDimitry Andric   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2313e8d8bef9SDimitry Andric   if (!config->relocatable) {
2314e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Process symbol versions");
23150b57cec5SDimitry Andric     symtab->scanVersionScript();
2316e8d8bef9SDimitry Andric   }
23170b57cec5SDimitry Andric 
23180b57cec5SDimitry Andric   // Do link-time optimization if given files are LLVM bitcode files.
23190b57cec5SDimitry Andric   // This compiles bitcode files into real object files.
23200b57cec5SDimitry Andric   //
23210b57cec5SDimitry Andric   // With this the symbol table should be complete. After this, no new names
23220b57cec5SDimitry Andric   // except a few linker-synthesized ones will be added to the symbol table.
23230b57cec5SDimitry Andric   compileBitcodeFiles<ELFT>();
23245ffd83dbSDimitry Andric 
2325e8d8bef9SDimitry Andric   // Handle --exclude-libs again because lto.tmp may reference additional
2326e8d8bef9SDimitry Andric   // libcalls symbols defined in an excluded archive. This may override
2327e8d8bef9SDimitry Andric   // versionId set by scanVersionScript().
2328e8d8bef9SDimitry Andric   if (args.hasArg(OPT_exclude_libs))
2329e8d8bef9SDimitry Andric     excludeLibs(args);
2330e8d8bef9SDimitry Andric 
23315ffd83dbSDimitry Andric   // Symbol resolution finished. Report backward reference problems.
23325ffd83dbSDimitry Andric   reportBackrefs();
23330b57cec5SDimitry Andric   if (errorCount())
23340b57cec5SDimitry Andric     return;
23350b57cec5SDimitry Andric 
2336*349cc55cSDimitry Andric   // If --thinlto-index-only is given, we should create only "index
23370b57cec5SDimitry Andric   // files" and not object files. Index file creation is already done
2338*349cc55cSDimitry Andric   // in compileBitcodeFiles, so we are done if that's the case.
23395ffd83dbSDimitry Andric   // Likewise, --plugin-opt=emit-llvm and --plugin-opt=emit-asm are the
23405ffd83dbSDimitry Andric   // options to create output files in bitcode or assembly code
2341fe6060f1SDimitry Andric   // respectively. No object files are generated.
23425ffd83dbSDimitry Andric   // Also bail out here when only certain thinLTO modules are specified for
23435ffd83dbSDimitry Andric   // compilation. The intermediate object file are the expected output.
23445ffd83dbSDimitry Andric   if (config->thinLTOIndexOnly || config->emitLLVM || config->ltoEmitAsm ||
23455ffd83dbSDimitry Andric       !config->thinLTOModulesToCompile.empty())
23460b57cec5SDimitry Andric     return;
23470b57cec5SDimitry Andric 
2348*349cc55cSDimitry Andric   // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
2349e8d8bef9SDimitry Andric   redirectSymbols(wrapped);
23500b57cec5SDimitry Andric 
2351e8d8bef9SDimitry Andric   {
2352e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Aggregate sections");
23530b57cec5SDimitry Andric     // Now that we have a complete list of input files.
23540b57cec5SDimitry Andric     // Beyond this point, no new files are added.
23550b57cec5SDimitry Andric     // Aggregate all input sections into one place.
23560b57cec5SDimitry Andric     for (InputFile *f : objectFiles)
23570b57cec5SDimitry Andric       for (InputSectionBase *s : f->getSections())
23580b57cec5SDimitry Andric         if (s && s != &InputSection::discarded)
23590b57cec5SDimitry Andric           inputSections.push_back(s);
23600b57cec5SDimitry Andric     for (BinaryFile *f : binaryFiles)
23610b57cec5SDimitry Andric       for (InputSectionBase *s : f->getSections())
23620b57cec5SDimitry Andric         inputSections.push_back(cast<InputSection>(s));
2363e8d8bef9SDimitry Andric   }
23640b57cec5SDimitry Andric 
2365e8d8bef9SDimitry Andric   {
2366e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Strip sections");
23670b57cec5SDimitry Andric     llvm::erase_if(inputSections, [](InputSectionBase *s) {
23680b57cec5SDimitry Andric       if (s->type == SHT_LLVM_SYMPART) {
23690b57cec5SDimitry Andric         readSymbolPartitionSection<ELFT>(s);
23700b57cec5SDimitry Andric         return true;
23710b57cec5SDimitry Andric       }
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric       // We do not want to emit debug sections if --strip-all
2374*349cc55cSDimitry Andric       // or --strip-debug are given.
2375d65cd7a5SDimitry Andric       if (config->strip == StripPolicy::None)
2376d65cd7a5SDimitry Andric         return false;
2377d65cd7a5SDimitry Andric 
2378d65cd7a5SDimitry Andric       if (isDebugSection(*s))
2379d65cd7a5SDimitry Andric         return true;
2380d65cd7a5SDimitry Andric       if (auto *isec = dyn_cast<InputSection>(s))
2381d65cd7a5SDimitry Andric         if (InputSectionBase *rel = isec->getRelocatedSection())
2382d65cd7a5SDimitry Andric           if (isDebugSection(*rel))
2383d65cd7a5SDimitry Andric             return true;
2384d65cd7a5SDimitry Andric 
2385d65cd7a5SDimitry Andric       return false;
23860b57cec5SDimitry Andric     });
2387e8d8bef9SDimitry Andric   }
2388e8d8bef9SDimitry Andric 
2389e8d8bef9SDimitry Andric   // Since we now have a complete set of input files, we can create
2390e8d8bef9SDimitry Andric   // a .d file to record build dependencies.
2391e8d8bef9SDimitry Andric   if (!config->dependencyFile.empty())
2392e8d8bef9SDimitry Andric     writeDependencyFile();
23930b57cec5SDimitry Andric 
23940b57cec5SDimitry Andric   // Now that the number of partitions is fixed, save a pointer to the main
23950b57cec5SDimitry Andric   // partition.
23960b57cec5SDimitry Andric   mainPart = &partitions[0];
23970b57cec5SDimitry Andric 
23980b57cec5SDimitry Andric   // Read .note.gnu.property sections from input object files which
23990b57cec5SDimitry Andric   // contain a hint to tweak linker's and loader's behaviors.
24000b57cec5SDimitry Andric   config->andFeatures = getAndFeatures<ELFT>();
24010b57cec5SDimitry Andric 
24020b57cec5SDimitry Andric   // The Target instance handles target-specific stuff, such as applying
24030b57cec5SDimitry Andric   // relocations or writing a PLT section. It also contains target-dependent
24040b57cec5SDimitry Andric   // values such as a default image base address.
24050b57cec5SDimitry Andric   target = getTarget();
24060b57cec5SDimitry Andric 
24070b57cec5SDimitry Andric   config->eflags = target->calcEFlags();
24080b57cec5SDimitry Andric   // maxPageSize (sometimes called abi page size) is the maximum page size that
24090b57cec5SDimitry Andric   // the output can be run on. For example if the OS can use 4k or 64k page
24100b57cec5SDimitry Andric   // sizes then maxPageSize must be 64k for the output to be useable on both.
24110b57cec5SDimitry Andric   // All important alignment decisions must use this value.
24120b57cec5SDimitry Andric   config->maxPageSize = getMaxPageSize(args);
24130b57cec5SDimitry Andric   // commonPageSize is the most common page size that the output will be run on.
24140b57cec5SDimitry Andric   // For example if an OS can use 4k or 64k page sizes and 4k is more common
24150b57cec5SDimitry Andric   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
24160b57cec5SDimitry Andric   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
24170b57cec5SDimitry Andric   // is limited to writing trap instructions on the last executable segment.
24180b57cec5SDimitry Andric   config->commonPageSize = getCommonPageSize(args);
24190b57cec5SDimitry Andric 
24200b57cec5SDimitry Andric   config->imageBase = getImageBase(args);
24210b57cec5SDimitry Andric 
24220b57cec5SDimitry Andric   if (config->emachine == EM_ARM) {
24230b57cec5SDimitry Andric     // FIXME: These warnings can be removed when lld only uses these features
24240b57cec5SDimitry Andric     // when the input objects have been compiled with an architecture that
24250b57cec5SDimitry Andric     // supports them.
24260b57cec5SDimitry Andric     if (config->armHasBlx == false)
24270b57cec5SDimitry Andric       warn("lld uses blx instruction, no object with architecture supporting "
24280b57cec5SDimitry Andric            "feature detected");
24290b57cec5SDimitry Andric   }
24300b57cec5SDimitry Andric 
243185868e8aSDimitry Andric   // This adds a .comment section containing a version string.
24320b57cec5SDimitry Andric   if (!config->relocatable)
24330b57cec5SDimitry Andric     inputSections.push_back(createCommentSection());
24340b57cec5SDimitry Andric 
24350b57cec5SDimitry Andric   // Replace common symbols with regular symbols.
24360b57cec5SDimitry Andric   replaceCommonSymbols();
24370b57cec5SDimitry Andric 
243885868e8aSDimitry Andric   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
24390b57cec5SDimitry Andric   splitSections<ELFT>();
244085868e8aSDimitry Andric 
244185868e8aSDimitry Andric   // Garbage collection and removal of shared symbols from unused shared objects.
24420b57cec5SDimitry Andric   markLive<ELFT>();
24430b57cec5SDimitry Andric   demoteSharedSymbols();
244485868e8aSDimitry Andric 
244585868e8aSDimitry Andric   // Make copies of any input sections that need to be copied into each
244685868e8aSDimitry Andric   // partition.
244785868e8aSDimitry Andric   copySectionsIntoPartitions();
244885868e8aSDimitry Andric 
244985868e8aSDimitry Andric   // Create synthesized sections such as .got and .plt. This is called before
245085868e8aSDimitry Andric   // processSectionCommands() so that they can be placed by SECTIONS commands.
245185868e8aSDimitry Andric   createSyntheticSections<ELFT>();
245285868e8aSDimitry Andric 
245385868e8aSDimitry Andric   // Some input sections that are used for exception handling need to be moved
245485868e8aSDimitry Andric   // into synthetic sections. Do that now so that they aren't assigned to
245585868e8aSDimitry Andric   // output sections in the usual way.
245685868e8aSDimitry Andric   if (!config->relocatable)
245785868e8aSDimitry Andric     combineEhSections();
245885868e8aSDimitry Andric 
2459e8d8bef9SDimitry Andric   {
2460e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Assign sections");
2461e8d8bef9SDimitry Andric 
246285868e8aSDimitry Andric     // Create output sections described by SECTIONS commands.
246385868e8aSDimitry Andric     script->processSectionCommands();
246485868e8aSDimitry Andric 
2465e8d8bef9SDimitry Andric     // Linker scripts control how input sections are assigned to output
2466e8d8bef9SDimitry Andric     // sections. Input sections that were not handled by scripts are called
2467e8d8bef9SDimitry Andric     // "orphans", and they are assigned to output sections by the default rule.
2468e8d8bef9SDimitry Andric     // Process that.
246985868e8aSDimitry Andric     script->addOrphanSections();
2470e8d8bef9SDimitry Andric   }
2471e8d8bef9SDimitry Andric 
2472e8d8bef9SDimitry Andric   {
2473e8d8bef9SDimitry Andric     llvm::TimeTraceScope timeScope("Merge/finalize input sections");
247485868e8aSDimitry Andric 
247585868e8aSDimitry Andric     // Migrate InputSectionDescription::sectionBases to sections. This includes
247685868e8aSDimitry Andric     // merging MergeInputSections into a single MergeSyntheticSection. From this
247785868e8aSDimitry Andric     // point onwards InputSectionDescription::sections should be used instead of
247885868e8aSDimitry Andric     // sectionBases.
247985868e8aSDimitry Andric     for (BaseCommand *base : script->sectionCommands)
248085868e8aSDimitry Andric       if (auto *sec = dyn_cast<OutputSection>(base))
248185868e8aSDimitry Andric         sec->finalizeInputSections();
2482e8d8bef9SDimitry Andric     llvm::erase_if(inputSections, [](InputSectionBase *s) {
2483e8d8bef9SDimitry Andric       return isa<MergeInputSection>(s);
2484e8d8bef9SDimitry Andric     });
2485e8d8bef9SDimitry Andric   }
248685868e8aSDimitry Andric 
248785868e8aSDimitry Andric   // Two input sections with different output sections should not be folded.
248885868e8aSDimitry Andric   // ICF runs after processSectionCommands() so that we know the output sections.
24890b57cec5SDimitry Andric   if (config->icf != ICFLevel::None) {
24900b57cec5SDimitry Andric     findKeepUniqueSections<ELFT>(args);
24910b57cec5SDimitry Andric     doIcf<ELFT>();
24920b57cec5SDimitry Andric   }
24930b57cec5SDimitry Andric 
24940b57cec5SDimitry Andric   // Read the callgraph now that we know what was gced or icfed
24950b57cec5SDimitry Andric   if (config->callGraphProfileSort) {
24960b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
24970b57cec5SDimitry Andric       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
24980b57cec5SDimitry Andric         readCallGraph(*buffer);
24990b57cec5SDimitry Andric     readCallGraphsFromObjectFiles<ELFT>();
25000b57cec5SDimitry Andric   }
25010b57cec5SDimitry Andric 
25020b57cec5SDimitry Andric   // Write the result to the file.
25030b57cec5SDimitry Andric   writeResult<ELFT>();
25040b57cec5SDimitry Andric }
2505