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" 5281ad6265SDimitry Andric #include "llvm/Object/Archive.h" 53e8d8bef9SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h" 540b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 550b57cec5SDimitry Andric #include "llvm/Support/Compression.h" 5681ad6265SDimitry Andric #include "llvm/Support/FileSystem.h" 570b57cec5SDimitry Andric #include "llvm/Support/GlobPattern.h" 580b57cec5SDimitry Andric #include "llvm/Support/LEB128.h" 595ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h" 600b57cec5SDimitry Andric #include "llvm/Support/Path.h" 610b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h" 620b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h" 635ffd83dbSDimitry Andric #include "llvm/Support/TimeProfiler.h" 640b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 650b57cec5SDimitry Andric #include <cstdlib> 660b57cec5SDimitry Andric #include <utility> 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric using namespace llvm; 690b57cec5SDimitry Andric using namespace llvm::ELF; 700b57cec5SDimitry Andric using namespace llvm::object; 710b57cec5SDimitry Andric using namespace llvm::sys; 720b57cec5SDimitry Andric using namespace llvm::support; 735ffd83dbSDimitry Andric using namespace lld; 745ffd83dbSDimitry Andric using namespace lld::elf; 750b57cec5SDimitry Andric 760eae32dcSDimitry Andric std::unique_ptr<Configuration> elf::config; 7781ad6265SDimitry Andric std::unique_ptr<Ctx> elf::ctx; 780eae32dcSDimitry Andric std::unique_ptr<LinkerDriver> elf::driver; 790b57cec5SDimitry Andric 800b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args); 810b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args); 820b57cec5SDimitry Andric 831fd87a68SDimitry Andric void elf::errorOrWarn(const Twine &msg) { 841fd87a68SDimitry Andric if (config->noinhibitExec) 851fd87a68SDimitry Andric warn(msg); 861fd87a68SDimitry Andric else 871fd87a68SDimitry Andric error(msg); 881fd87a68SDimitry Andric } 891fd87a68SDimitry Andric 9004eeddc0SDimitry Andric bool elf::link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS, 9104eeddc0SDimitry Andric llvm::raw_ostream &stderrOS, bool exitEarly, 9204eeddc0SDimitry Andric bool disableOutput) { 9304eeddc0SDimitry Andric // This driver-specific context will be freed later by lldMain(). 9404eeddc0SDimitry Andric auto *ctx = new CommonLinkerContext; 95480093f4SDimitry Andric 9604eeddc0SDimitry Andric ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); 9704eeddc0SDimitry Andric ctx->e.cleanupCallback = []() { 980b57cec5SDimitry Andric inputSections.clear(); 990b57cec5SDimitry Andric outputSections.clear(); 10004eeddc0SDimitry Andric symAux.clear(); 1010b57cec5SDimitry Andric 1020b57cec5SDimitry Andric tar = nullptr; 10304eeddc0SDimitry Andric in.reset(); 1040b57cec5SDimitry Andric 10504eeddc0SDimitry Andric partitions.clear(); 10604eeddc0SDimitry Andric partitions.emplace_back(); 1070b57cec5SDimitry Andric 1080b57cec5SDimitry Andric SharedFile::vernauxNum = 0; 109e8d8bef9SDimitry Andric }; 11004eeddc0SDimitry Andric ctx->e.logName = args::getFilenameWithoutExe(args[0]); 11104eeddc0SDimitry Andric ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use " 11281ad6265SDimitry Andric "--error-limit=0 to see all errors)"; 113e8d8bef9SDimitry Andric 1140eae32dcSDimitry Andric config = std::make_unique<Configuration>(); 11581ad6265SDimitry Andric elf::ctx = std::make_unique<Ctx>(); 1160eae32dcSDimitry Andric driver = std::make_unique<LinkerDriver>(); 1170eae32dcSDimitry Andric script = std::make_unique<LinkerScript>(); 1180eae32dcSDimitry Andric symtab = std::make_unique<SymbolTable>(); 119e8d8bef9SDimitry Andric 12004eeddc0SDimitry Andric partitions.clear(); 12104eeddc0SDimitry Andric partitions.emplace_back(); 1220b57cec5SDimitry Andric 1230b57cec5SDimitry Andric config->progName = args[0]; 1240b57cec5SDimitry Andric 125e8d8bef9SDimitry Andric driver->linkerMain(args); 1260b57cec5SDimitry Andric 12704eeddc0SDimitry Andric return errorCount() == 0; 1280b57cec5SDimitry Andric } 1290b57cec5SDimitry Andric 1300b57cec5SDimitry Andric // Parses a linker -m option. 1310b57cec5SDimitry Andric static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) { 1320b57cec5SDimitry Andric uint8_t osabi = 0; 1330b57cec5SDimitry Andric StringRef s = emul; 1340b57cec5SDimitry Andric if (s.endswith("_fbsd")) { 1350b57cec5SDimitry Andric s = s.drop_back(5); 1360b57cec5SDimitry Andric osabi = ELFOSABI_FREEBSD; 1370b57cec5SDimitry Andric } 1380b57cec5SDimitry Andric 1390b57cec5SDimitry Andric std::pair<ELFKind, uint16_t> ret = 1400b57cec5SDimitry Andric StringSwitch<std::pair<ELFKind, uint16_t>>(s) 141fe6060f1SDimitry Andric .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64}) 142fe6060f1SDimitry Andric .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64}) 1430b57cec5SDimitry Andric .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 1440b57cec5SDimitry Andric .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 1450b57cec5SDimitry Andric .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 1460b57cec5SDimitry Andric .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 1470b57cec5SDimitry Andric .Case("elf32lriscv", {ELF32LEKind, EM_RISCV}) 1480b57cec5SDimitry Andric .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC}) 149e8d8bef9SDimitry Andric .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC}) 1500b57cec5SDimitry Andric .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 1510b57cec5SDimitry Andric .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 1520b57cec5SDimitry Andric .Case("elf64lriscv", {ELF64LEKind, EM_RISCV}) 1530b57cec5SDimitry Andric .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 1540b57cec5SDimitry Andric .Case("elf64lppc", {ELF64LEKind, EM_PPC64}) 1550b57cec5SDimitry Andric .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 1560b57cec5SDimitry Andric .Case("elf_i386", {ELF32LEKind, EM_386}) 1570b57cec5SDimitry Andric .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 1585ffd83dbSDimitry Andric .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9}) 159e8d8bef9SDimitry Andric .Case("msp430elf", {ELF32LEKind, EM_MSP430}) 1600b57cec5SDimitry Andric .Default({ELFNoneKind, EM_NONE}); 1610b57cec5SDimitry Andric 1620b57cec5SDimitry Andric if (ret.first == ELFNoneKind) 1630b57cec5SDimitry Andric error("unknown emulation: " + emul); 164e8d8bef9SDimitry Andric if (ret.second == EM_MSP430) 165e8d8bef9SDimitry Andric osabi = ELFOSABI_STANDALONE; 1660b57cec5SDimitry Andric return std::make_tuple(ret.first, ret.second, osabi); 1670b57cec5SDimitry Andric } 1680b57cec5SDimitry Andric 1690b57cec5SDimitry Andric // Returns slices of MB by parsing MB as an archive file. 1700b57cec5SDimitry Andric // Each slice consists of a member file in the archive. 1710b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 1720b57cec5SDimitry Andric MemoryBufferRef mb) { 1730b57cec5SDimitry Andric std::unique_ptr<Archive> file = 1740b57cec5SDimitry Andric CHECK(Archive::create(mb), 1750b57cec5SDimitry Andric mb.getBufferIdentifier() + ": failed to parse archive"); 1760b57cec5SDimitry Andric 1770b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> v; 1780b57cec5SDimitry Andric Error err = Error::success(); 1790b57cec5SDimitry Andric bool addToTar = file->isThin() && tar; 180480093f4SDimitry Andric for (const Archive::Child &c : file->children(err)) { 1810b57cec5SDimitry Andric MemoryBufferRef mbref = 1820b57cec5SDimitry Andric CHECK(c.getMemoryBufferRef(), 1830b57cec5SDimitry Andric mb.getBufferIdentifier() + 1840b57cec5SDimitry Andric ": could not get the buffer for a child of the archive"); 1850b57cec5SDimitry Andric if (addToTar) 1860b57cec5SDimitry Andric tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer()); 1870b57cec5SDimitry Andric v.push_back(std::make_pair(mbref, c.getChildOffset())); 1880b57cec5SDimitry Andric } 1890b57cec5SDimitry Andric if (err) 1900b57cec5SDimitry Andric fatal(mb.getBufferIdentifier() + ": Archive::children failed: " + 1910b57cec5SDimitry Andric toString(std::move(err))); 1920b57cec5SDimitry Andric 1930b57cec5SDimitry Andric // Take ownership of memory buffers created for members of thin archives. 1941fd87a68SDimitry Andric std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers(); 19581ad6265SDimitry Andric std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx->memoryBuffers)); 1960b57cec5SDimitry Andric 1970b57cec5SDimitry Andric return v; 1980b57cec5SDimitry Andric } 1990b57cec5SDimitry Andric 200*fcaf7f86SDimitry Andric static bool isBitcode(MemoryBufferRef mb) { 201*fcaf7f86SDimitry Andric return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode; 202*fcaf7f86SDimitry Andric } 203*fcaf7f86SDimitry Andric 2040b57cec5SDimitry Andric // Opens a file and create a file object. Path has to be resolved already. 2050b57cec5SDimitry Andric void LinkerDriver::addFile(StringRef path, bool withLOption) { 2060b57cec5SDimitry Andric using namespace sys::fs; 2070b57cec5SDimitry Andric 2080b57cec5SDimitry Andric Optional<MemoryBufferRef> buffer = readFile(path); 20981ad6265SDimitry Andric if (!buffer) 2100b57cec5SDimitry Andric return; 2110b57cec5SDimitry Andric MemoryBufferRef mbref = *buffer; 2120b57cec5SDimitry Andric 2130b57cec5SDimitry Andric if (config->formatBinary) { 2140b57cec5SDimitry Andric files.push_back(make<BinaryFile>(mbref)); 2150b57cec5SDimitry Andric return; 2160b57cec5SDimitry Andric } 2170b57cec5SDimitry Andric 2180b57cec5SDimitry Andric switch (identify_magic(mbref.getBuffer())) { 2190b57cec5SDimitry Andric case file_magic::unknown: 2200b57cec5SDimitry Andric readLinkerScript(mbref); 2210b57cec5SDimitry Andric return; 2220b57cec5SDimitry Andric case file_magic::archive: { 2230b57cec5SDimitry Andric if (inWholeArchive) { 224*fcaf7f86SDimitry Andric for (const auto &p : getArchiveMembers(mbref)) { 225*fcaf7f86SDimitry Andric if (isBitcode(p.first)) 226*fcaf7f86SDimitry Andric files.push_back(make<BitcodeFile>(p.first, path, p.second, false)); 227*fcaf7f86SDimitry Andric else 228*fcaf7f86SDimitry Andric files.push_back(createObjFile(p.first, path)); 229*fcaf7f86SDimitry Andric } 2300b57cec5SDimitry Andric return; 2310b57cec5SDimitry Andric } 2320b57cec5SDimitry Andric 23381ad6265SDimitry Andric auto members = getArchiveMembers(mbref); 23481ad6265SDimitry Andric archiveFiles.emplace_back(path, members.size()); 2350b57cec5SDimitry Andric 23681ad6265SDimitry Andric // Handle archives and --start-lib/--end-lib using the same code path. This 23781ad6265SDimitry Andric // scans all the ELF relocatable object files and bitcode files in the 23881ad6265SDimitry Andric // archive rather than just the index file, with the benefit that the 23981ad6265SDimitry Andric // symbols are only loaded once. For many projects archives see high 24081ad6265SDimitry Andric // utilization rates and it is a net performance win. --start-lib scans 24181ad6265SDimitry Andric // symbols in the same order that llvm-ar adds them to the index, so in the 24281ad6265SDimitry Andric // common case the semantics are identical. If the archive symbol table was 24381ad6265SDimitry Andric // created in a different order, or is incomplete, this strategy has 24481ad6265SDimitry Andric // different semantics. Such output differences are considered user error. 24581ad6265SDimitry Andric // 246d56accc7SDimitry Andric // All files within the archive get the same group ID to allow mutual 247d56accc7SDimitry Andric // references for --warn-backrefs. 248d56accc7SDimitry Andric bool saved = InputFile::isInGroup; 249d56accc7SDimitry Andric InputFile::isInGroup = true; 25081ad6265SDimitry Andric for (const std::pair<MemoryBufferRef, uint64_t> &p : members) { 25104eeddc0SDimitry Andric auto magic = identify_magic(p.first.getBuffer()); 252*fcaf7f86SDimitry Andric if (magic == file_magic::elf_relocatable) 253*fcaf7f86SDimitry Andric files.push_back(createObjFile(p.first, path, true)); 254*fcaf7f86SDimitry Andric else if (magic == file_magic::bitcode) 255*fcaf7f86SDimitry Andric files.push_back(make<BitcodeFile>(p.first, path, p.second, true)); 25604eeddc0SDimitry Andric else 25781ad6265SDimitry Andric warn(path + ": archive member '" + p.first.getBufferIdentifier() + 25804eeddc0SDimitry Andric "' is neither ET_REL nor LLVM bitcode"); 25904eeddc0SDimitry Andric } 260d56accc7SDimitry Andric InputFile::isInGroup = saved; 261d56accc7SDimitry Andric if (!saved) 262d56accc7SDimitry Andric ++InputFile::nextGroupId; 2630b57cec5SDimitry Andric return; 2640b57cec5SDimitry Andric } 2650b57cec5SDimitry Andric case file_magic::elf_shared_object: 2660b57cec5SDimitry Andric if (config->isStatic || config->relocatable) { 2670b57cec5SDimitry Andric error("attempted static link of dynamic object " + path); 2680b57cec5SDimitry Andric return; 2690b57cec5SDimitry Andric } 2700b57cec5SDimitry Andric 271349cc55cSDimitry Andric // Shared objects are identified by soname. soname is (if specified) 272349cc55cSDimitry Andric // DT_SONAME and falls back to filename. If a file was specified by -lfoo, 273349cc55cSDimitry Andric // the directory part is ignored. Note that path may be a temporary and 274349cc55cSDimitry Andric // cannot be stored into SharedFile::soName. 275349cc55cSDimitry Andric path = mbref.getBufferIdentifier(); 2760b57cec5SDimitry Andric files.push_back( 2770b57cec5SDimitry Andric make<SharedFile>(mbref, withLOption ? path::filename(path) : path)); 2780b57cec5SDimitry Andric return; 2790b57cec5SDimitry Andric case file_magic::bitcode: 280*fcaf7f86SDimitry Andric files.push_back(make<BitcodeFile>(mbref, "", 0, inLib)); 281*fcaf7f86SDimitry Andric break; 2820b57cec5SDimitry Andric case file_magic::elf_relocatable: 283*fcaf7f86SDimitry Andric files.push_back(createObjFile(mbref, "", inLib)); 2840b57cec5SDimitry Andric break; 2850b57cec5SDimitry Andric default: 2860b57cec5SDimitry Andric error(path + ": unknown file type"); 2870b57cec5SDimitry Andric } 2880b57cec5SDimitry Andric } 2890b57cec5SDimitry Andric 2900b57cec5SDimitry Andric // Add a given library by searching it from input search paths. 2910b57cec5SDimitry Andric void LinkerDriver::addLibrary(StringRef name) { 2920b57cec5SDimitry Andric if (Optional<std::string> path = searchLibrary(name)) 2930b57cec5SDimitry Andric addFile(*path, /*withLOption=*/true); 2940b57cec5SDimitry Andric else 295e8d8bef9SDimitry Andric error("unable to find library -l" + name, ErrorTag::LibNotFound, {name}); 2960b57cec5SDimitry Andric } 2970b57cec5SDimitry Andric 2980b57cec5SDimitry Andric // This function is called on startup. We need this for LTO since 2990b57cec5SDimitry Andric // LTO calls LLVM functions to compile bitcode files to native code. 3000b57cec5SDimitry Andric // Technically this can be delayed until we read bitcode files, but 3010b57cec5SDimitry Andric // we don't bother to do lazily because the initialization is fast. 3020b57cec5SDimitry Andric static void initLLVM() { 3030b57cec5SDimitry Andric InitializeAllTargets(); 3040b57cec5SDimitry Andric InitializeAllTargetMCs(); 3050b57cec5SDimitry Andric InitializeAllAsmPrinters(); 3060b57cec5SDimitry Andric InitializeAllAsmParsers(); 3070b57cec5SDimitry Andric } 3080b57cec5SDimitry Andric 3090b57cec5SDimitry Andric // Some command line options or some combinations of them are not allowed. 3100b57cec5SDimitry Andric // This function checks for such errors. 3110b57cec5SDimitry Andric static void checkOptions() { 3120b57cec5SDimitry Andric // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 3130b57cec5SDimitry Andric // table which is a relatively new feature. 3140b57cec5SDimitry Andric if (config->emachine == EM_MIPS && config->gnuHash) 3150b57cec5SDimitry Andric error("the .gnu.hash section is not compatible with the MIPS target"); 3160b57cec5SDimitry Andric 3170b57cec5SDimitry Andric if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64) 3180b57cec5SDimitry Andric error("--fix-cortex-a53-843419 is only supported on AArch64 targets"); 3190b57cec5SDimitry Andric 32085868e8aSDimitry Andric if (config->fixCortexA8 && config->emachine != EM_ARM) 32185868e8aSDimitry Andric error("--fix-cortex-a8 is only supported on ARM targets"); 32285868e8aSDimitry Andric 3230b57cec5SDimitry Andric if (config->tocOptimize && config->emachine != EM_PPC64) 324e8d8bef9SDimitry Andric error("--toc-optimize is only supported on PowerPC64 targets"); 325e8d8bef9SDimitry Andric 326e8d8bef9SDimitry Andric if (config->pcRelOptimize && config->emachine != EM_PPC64) 327e8d8bef9SDimitry Andric error("--pcrel-optimize is only supported on PowerPC64 targets"); 3280b57cec5SDimitry Andric 3290b57cec5SDimitry Andric if (config->pie && config->shared) 3300b57cec5SDimitry Andric error("-shared and -pie may not be used together"); 3310b57cec5SDimitry Andric 3320b57cec5SDimitry Andric if (!config->shared && !config->filterList.empty()) 3330b57cec5SDimitry Andric error("-F may not be used without -shared"); 3340b57cec5SDimitry Andric 3350b57cec5SDimitry Andric if (!config->shared && !config->auxiliaryList.empty()) 3360b57cec5SDimitry Andric error("-f may not be used without -shared"); 3370b57cec5SDimitry Andric 33885868e8aSDimitry Andric if (config->strip == StripPolicy::All && config->emitRelocs) 33985868e8aSDimitry Andric error("--strip-all and --emit-relocs may not be used together"); 34085868e8aSDimitry Andric 3410b57cec5SDimitry Andric if (config->zText && config->zIfuncNoplt) 3420b57cec5SDimitry Andric error("-z text and -z ifunc-noplt may not be used together"); 3430b57cec5SDimitry Andric 3440b57cec5SDimitry Andric if (config->relocatable) { 3450b57cec5SDimitry Andric if (config->shared) 3460b57cec5SDimitry Andric error("-r and -shared may not be used together"); 3470b57cec5SDimitry Andric if (config->gdbIndex) 3480b57cec5SDimitry Andric error("-r and --gdb-index may not be used together"); 3490b57cec5SDimitry Andric if (config->icf != ICFLevel::None) 3500b57cec5SDimitry Andric error("-r and --icf may not be used together"); 3510b57cec5SDimitry Andric if (config->pie) 3520b57cec5SDimitry Andric error("-r and -pie may not be used together"); 35385868e8aSDimitry Andric if (config->exportDynamic) 35485868e8aSDimitry Andric error("-r and --export-dynamic may not be used together"); 3550b57cec5SDimitry Andric } 3560b57cec5SDimitry Andric 3570b57cec5SDimitry Andric if (config->executeOnly) { 3580b57cec5SDimitry Andric if (config->emachine != EM_AARCH64) 359349cc55cSDimitry Andric error("--execute-only is only supported on AArch64 targets"); 3600b57cec5SDimitry Andric 3610b57cec5SDimitry Andric if (config->singleRoRx && !script->hasSectionsCommand) 362349cc55cSDimitry Andric error("--execute-only and --no-rosegment cannot be used together"); 3630b57cec5SDimitry Andric } 3640b57cec5SDimitry Andric 365480093f4SDimitry Andric if (config->zRetpolineplt && config->zForceIbt) 366480093f4SDimitry Andric error("-z force-ibt may not be used with -z retpolineplt"); 3670b57cec5SDimitry Andric 3680b57cec5SDimitry Andric if (config->emachine != EM_AARCH64) { 3695ffd83dbSDimitry Andric if (config->zPacPlt) 370480093f4SDimitry Andric error("-z pac-plt only supported on AArch64"); 3715ffd83dbSDimitry Andric if (config->zForceBti) 372480093f4SDimitry Andric error("-z force-bti only supported on AArch64"); 3730eae32dcSDimitry Andric if (config->zBtiReport != "none") 3740eae32dcSDimitry Andric error("-z bti-report only supported on AArch64"); 3750b57cec5SDimitry Andric } 3760eae32dcSDimitry Andric 3770eae32dcSDimitry Andric if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 3780eae32dcSDimitry Andric config->zCetReport != "none") 3790eae32dcSDimitry Andric error("-z cet-report only supported on X86 and X86_64"); 3800b57cec5SDimitry Andric } 3810b57cec5SDimitry Andric 3820b57cec5SDimitry Andric static const char *getReproduceOption(opt::InputArgList &args) { 3830b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 3840b57cec5SDimitry Andric return arg->getValue(); 3850b57cec5SDimitry Andric return getenv("LLD_REPRODUCE"); 3860b57cec5SDimitry Andric } 3870b57cec5SDimitry Andric 3880b57cec5SDimitry Andric static bool hasZOption(opt::InputArgList &args, StringRef key) { 3890b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_z)) 3900b57cec5SDimitry Andric if (key == arg->getValue()) 3910b57cec5SDimitry Andric return true; 3920b57cec5SDimitry Andric return false; 3930b57cec5SDimitry Andric } 3940b57cec5SDimitry Andric 3950b57cec5SDimitry Andric static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2, 3960b57cec5SDimitry Andric bool Default) { 3970b57cec5SDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 3980b57cec5SDimitry Andric if (k1 == arg->getValue()) 3990b57cec5SDimitry Andric return true; 4000b57cec5SDimitry Andric if (k2 == arg->getValue()) 4010b57cec5SDimitry Andric return false; 4020b57cec5SDimitry Andric } 4030b57cec5SDimitry Andric return Default; 4040b57cec5SDimitry Andric } 4050b57cec5SDimitry Andric 40685868e8aSDimitry Andric static SeparateSegmentKind getZSeparate(opt::InputArgList &args) { 40785868e8aSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 40885868e8aSDimitry Andric StringRef v = arg->getValue(); 40985868e8aSDimitry Andric if (v == "noseparate-code") 41085868e8aSDimitry Andric return SeparateSegmentKind::None; 41185868e8aSDimitry Andric if (v == "separate-code") 41285868e8aSDimitry Andric return SeparateSegmentKind::Code; 41385868e8aSDimitry Andric if (v == "separate-loadable-segments") 41485868e8aSDimitry Andric return SeparateSegmentKind::Loadable; 41585868e8aSDimitry Andric } 41685868e8aSDimitry Andric return SeparateSegmentKind::None; 41785868e8aSDimitry Andric } 41885868e8aSDimitry Andric 419480093f4SDimitry Andric static GnuStackKind getZGnuStack(opt::InputArgList &args) { 420480093f4SDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 421480093f4SDimitry Andric if (StringRef("execstack") == arg->getValue()) 422480093f4SDimitry Andric return GnuStackKind::Exec; 423480093f4SDimitry Andric if (StringRef("noexecstack") == arg->getValue()) 424480093f4SDimitry Andric return GnuStackKind::NoExec; 425480093f4SDimitry Andric if (StringRef("nognustack") == arg->getValue()) 426480093f4SDimitry Andric return GnuStackKind::None; 427480093f4SDimitry Andric } 428480093f4SDimitry Andric 429480093f4SDimitry Andric return GnuStackKind::NoExec; 430480093f4SDimitry Andric } 431480093f4SDimitry Andric 4325ffd83dbSDimitry Andric static uint8_t getZStartStopVisibility(opt::InputArgList &args) { 4335ffd83dbSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 4345ffd83dbSDimitry Andric std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 4355ffd83dbSDimitry Andric if (kv.first == "start-stop-visibility") { 4365ffd83dbSDimitry Andric if (kv.second == "default") 4375ffd83dbSDimitry Andric return STV_DEFAULT; 4385ffd83dbSDimitry Andric else if (kv.second == "internal") 4395ffd83dbSDimitry Andric return STV_INTERNAL; 4405ffd83dbSDimitry Andric else if (kv.second == "hidden") 4415ffd83dbSDimitry Andric return STV_HIDDEN; 4425ffd83dbSDimitry Andric else if (kv.second == "protected") 4435ffd83dbSDimitry Andric return STV_PROTECTED; 4445ffd83dbSDimitry Andric error("unknown -z start-stop-visibility= value: " + StringRef(kv.second)); 4455ffd83dbSDimitry Andric } 4465ffd83dbSDimitry Andric } 4475ffd83dbSDimitry Andric return STV_PROTECTED; 4485ffd83dbSDimitry Andric } 4495ffd83dbSDimitry Andric 45081ad6265SDimitry Andric constexpr const char *knownZFlags[] = { 45181ad6265SDimitry Andric "combreloc", 45281ad6265SDimitry Andric "copyreloc", 45381ad6265SDimitry Andric "defs", 45481ad6265SDimitry Andric "execstack", 45581ad6265SDimitry Andric "force-bti", 45681ad6265SDimitry Andric "force-ibt", 45781ad6265SDimitry Andric "global", 45881ad6265SDimitry Andric "hazardplt", 45981ad6265SDimitry Andric "ifunc-noplt", 46081ad6265SDimitry Andric "initfirst", 46181ad6265SDimitry Andric "interpose", 46281ad6265SDimitry Andric "keep-text-section-prefix", 46381ad6265SDimitry Andric "lazy", 46481ad6265SDimitry Andric "muldefs", 46581ad6265SDimitry Andric "nocombreloc", 46681ad6265SDimitry Andric "nocopyreloc", 46781ad6265SDimitry Andric "nodefaultlib", 46881ad6265SDimitry Andric "nodelete", 46981ad6265SDimitry Andric "nodlopen", 47081ad6265SDimitry Andric "noexecstack", 47181ad6265SDimitry Andric "nognustack", 47281ad6265SDimitry Andric "nokeep-text-section-prefix", 47381ad6265SDimitry Andric "nopack-relative-relocs", 47481ad6265SDimitry Andric "norelro", 47581ad6265SDimitry Andric "noseparate-code", 47681ad6265SDimitry Andric "nostart-stop-gc", 47781ad6265SDimitry Andric "notext", 47881ad6265SDimitry Andric "now", 47981ad6265SDimitry Andric "origin", 48081ad6265SDimitry Andric "pac-plt", 48181ad6265SDimitry Andric "pack-relative-relocs", 48281ad6265SDimitry Andric "rel", 48381ad6265SDimitry Andric "rela", 48481ad6265SDimitry Andric "relro", 48581ad6265SDimitry Andric "retpolineplt", 48681ad6265SDimitry Andric "rodynamic", 48781ad6265SDimitry Andric "separate-code", 48881ad6265SDimitry Andric "separate-loadable-segments", 48981ad6265SDimitry Andric "shstk", 49081ad6265SDimitry Andric "start-stop-gc", 49181ad6265SDimitry Andric "text", 49281ad6265SDimitry Andric "undefs", 49381ad6265SDimitry Andric "wxneeded", 49481ad6265SDimitry Andric }; 49581ad6265SDimitry Andric 4960b57cec5SDimitry Andric static bool isKnownZFlag(StringRef s) { 49781ad6265SDimitry Andric return llvm::is_contained(knownZFlags, s) || 49881ad6265SDimitry Andric s.startswith("common-page-size=") || s.startswith("bti-report=") || 49981ad6265SDimitry Andric s.startswith("cet-report=") || 5005ffd83dbSDimitry Andric s.startswith("dead-reloc-in-nonalloc=") || 5015ffd83dbSDimitry Andric s.startswith("max-page-size=") || s.startswith("stack-size=") || 5025ffd83dbSDimitry Andric s.startswith("start-stop-visibility="); 5030b57cec5SDimitry Andric } 5040b57cec5SDimitry Andric 5054824e7fdSDimitry Andric // Report a warning for an unknown -z option. 5060b57cec5SDimitry Andric static void checkZOptions(opt::InputArgList &args) { 5070b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_z)) 5080b57cec5SDimitry Andric if (!isKnownZFlag(arg->getValue())) 5094824e7fdSDimitry Andric warn("unknown -z value: " + StringRef(arg->getValue())); 5100b57cec5SDimitry Andric } 5110b57cec5SDimitry Andric 512753f127fSDimitry Andric constexpr const char *saveTempsValues[] = { 513753f127fSDimitry Andric "resolution", "preopt", "promote", "internalize", "import", 514753f127fSDimitry Andric "opt", "precodegen", "prelink", "combinedindex"}; 515753f127fSDimitry Andric 516e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 5170b57cec5SDimitry Andric ELFOptTable parser; 5180b57cec5SDimitry Andric opt::InputArgList args = parser.parse(argsArr.slice(1)); 5190b57cec5SDimitry Andric 52081ad6265SDimitry Andric // Interpret these flags early because error()/warn() depend on them. 5210b57cec5SDimitry Andric errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20); 5224824e7fdSDimitry Andric errorHandler().fatalWarnings = 5234824e7fdSDimitry Andric args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false); 5240b57cec5SDimitry Andric checkZOptions(args); 5250b57cec5SDimitry Andric 5260b57cec5SDimitry Andric // Handle -help 5270b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 5280b57cec5SDimitry Andric printHelp(); 5290b57cec5SDimitry Andric return; 5300b57cec5SDimitry Andric } 5310b57cec5SDimitry Andric 5320b57cec5SDimitry Andric // Handle -v or -version. 5330b57cec5SDimitry Andric // 5340b57cec5SDimitry Andric // A note about "compatible with GNU linkers" message: this is a hack for 535349cc55cSDimitry Andric // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as 536349cc55cSDimitry Andric // a GNU compatible linker. See 537349cc55cSDimitry Andric // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>. 5380b57cec5SDimitry Andric // 5390b57cec5SDimitry Andric // This is somewhat ugly hack, but in reality, we had no choice other 5400b57cec5SDimitry Andric // than doing this. Considering the very long release cycle of Libtool, 5410b57cec5SDimitry Andric // it is not easy to improve it to recognize LLD as a GNU compatible 5420b57cec5SDimitry Andric // linker in a timely manner. Even if we can make it, there are still a 5430b57cec5SDimitry Andric // lot of "configure" scripts out there that are generated by old version 5440b57cec5SDimitry Andric // of Libtool. We cannot convince every software developer to migrate to 5450b57cec5SDimitry Andric // the latest version and re-generate scripts. So we have this hack. 5460b57cec5SDimitry Andric if (args.hasArg(OPT_v) || args.hasArg(OPT_version)) 5470b57cec5SDimitry Andric message(getLLDVersion() + " (compatible with GNU linkers)"); 5480b57cec5SDimitry Andric 5490b57cec5SDimitry Andric if (const char *path = getReproduceOption(args)) { 5500b57cec5SDimitry Andric // Note that --reproduce is a debug option so you can ignore it 5510b57cec5SDimitry Andric // if you are trying to understand the whole picture of the code. 5520b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 5530b57cec5SDimitry Andric TarWriter::create(path, path::stem(path)); 5540b57cec5SDimitry Andric if (errOrWriter) { 5550b57cec5SDimitry Andric tar = std::move(*errOrWriter); 5560b57cec5SDimitry Andric tar->append("response.txt", createResponseFile(args)); 5570b57cec5SDimitry Andric tar->append("version.txt", getLLDVersion() + "\n"); 558e8d8bef9SDimitry Andric StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 559e8d8bef9SDimitry Andric if (!ltoSampleProfile.empty()) 560e8d8bef9SDimitry Andric readFile(ltoSampleProfile); 5610b57cec5SDimitry Andric } else { 5620b57cec5SDimitry Andric error("--reproduce: " + toString(errOrWriter.takeError())); 5630b57cec5SDimitry Andric } 5640b57cec5SDimitry Andric } 5650b57cec5SDimitry Andric 5660b57cec5SDimitry Andric readConfigs(args); 5670b57cec5SDimitry Andric 5680b57cec5SDimitry Andric // The behavior of -v or --version is a bit strange, but this is 5690b57cec5SDimitry Andric // needed for compatibility with GNU linkers. 5700b57cec5SDimitry Andric if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT)) 5710b57cec5SDimitry Andric return; 5720b57cec5SDimitry Andric if (args.hasArg(OPT_version)) 5730b57cec5SDimitry Andric return; 5740b57cec5SDimitry Andric 5755ffd83dbSDimitry Andric // Initialize time trace profiler. 5765ffd83dbSDimitry Andric if (config->timeTraceEnabled) 5775ffd83dbSDimitry Andric timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName); 5785ffd83dbSDimitry Andric 5795ffd83dbSDimitry Andric { 5805ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("ExecuteLinker"); 5815ffd83dbSDimitry Andric 5820b57cec5SDimitry Andric initLLVM(); 5830b57cec5SDimitry Andric createFiles(args); 5840b57cec5SDimitry Andric if (errorCount()) 5850b57cec5SDimitry Andric return; 5860b57cec5SDimitry Andric 5870b57cec5SDimitry Andric inferMachineType(); 5880b57cec5SDimitry Andric setConfigs(args); 5890b57cec5SDimitry Andric checkOptions(); 5900b57cec5SDimitry Andric if (errorCount()) 5910b57cec5SDimitry Andric return; 5920b57cec5SDimitry Andric 5930b57cec5SDimitry Andric // The Target instance handles target-specific stuff, such as applying 5940b57cec5SDimitry Andric // relocations or writing a PLT section. It also contains target-dependent 5950b57cec5SDimitry Andric // values such as a default image base address. 5960b57cec5SDimitry Andric target = getTarget(); 5970b57cec5SDimitry Andric 5981fd87a68SDimitry Andric link(args); 5990b57cec5SDimitry Andric } 6000b57cec5SDimitry Andric 6015ffd83dbSDimitry Andric if (config->timeTraceEnabled) { 602349cc55cSDimitry Andric checkError(timeTraceProfilerWrite( 60381ad6265SDimitry Andric args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile)); 6045ffd83dbSDimitry Andric timeTraceProfilerCleanup(); 6055ffd83dbSDimitry Andric } 6065ffd83dbSDimitry Andric } 6075ffd83dbSDimitry Andric 6080b57cec5SDimitry Andric static std::string getRpath(opt::InputArgList &args) { 6090b57cec5SDimitry Andric std::vector<StringRef> v = args::getStrings(args, OPT_rpath); 6100b57cec5SDimitry Andric return llvm::join(v.begin(), v.end(), ":"); 6110b57cec5SDimitry Andric } 6120b57cec5SDimitry Andric 6130b57cec5SDimitry Andric // Determines what we should do if there are remaining unresolved 6140b57cec5SDimitry Andric // symbols after the name resolution. 615e8d8bef9SDimitry Andric static void setUnresolvedSymbolPolicy(opt::InputArgList &args) { 6160b57cec5SDimitry Andric UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols, 6170b57cec5SDimitry Andric OPT_warn_unresolved_symbols, true) 6180b57cec5SDimitry Andric ? UnresolvedPolicy::ReportError 6190b57cec5SDimitry Andric : UnresolvedPolicy::Warn; 620349cc55cSDimitry Andric // -shared implies --unresolved-symbols=ignore-all because missing 621e8d8bef9SDimitry Andric // symbols are likely to be resolved at runtime. 622e8d8bef9SDimitry Andric bool diagRegular = !config->shared, diagShlib = !config->shared; 6230b57cec5SDimitry Andric 624e8d8bef9SDimitry Andric for (const opt::Arg *arg : args) { 6250b57cec5SDimitry Andric switch (arg->getOption().getID()) { 6260b57cec5SDimitry Andric case OPT_unresolved_symbols: { 6270b57cec5SDimitry Andric StringRef s = arg->getValue(); 628e8d8bef9SDimitry Andric if (s == "ignore-all") { 629e8d8bef9SDimitry Andric diagRegular = false; 630e8d8bef9SDimitry Andric diagShlib = false; 631e8d8bef9SDimitry Andric } else if (s == "ignore-in-object-files") { 632e8d8bef9SDimitry Andric diagRegular = false; 633e8d8bef9SDimitry Andric diagShlib = true; 634e8d8bef9SDimitry Andric } else if (s == "ignore-in-shared-libs") { 635e8d8bef9SDimitry Andric diagRegular = true; 636e8d8bef9SDimitry Andric diagShlib = false; 637e8d8bef9SDimitry Andric } else if (s == "report-all") { 638e8d8bef9SDimitry Andric diagRegular = true; 639e8d8bef9SDimitry Andric diagShlib = true; 640e8d8bef9SDimitry Andric } else { 6410b57cec5SDimitry Andric error("unknown --unresolved-symbols value: " + s); 642e8d8bef9SDimitry Andric } 643e8d8bef9SDimitry Andric break; 6440b57cec5SDimitry Andric } 6450b57cec5SDimitry Andric case OPT_no_undefined: 646e8d8bef9SDimitry Andric diagRegular = true; 647e8d8bef9SDimitry Andric break; 6480b57cec5SDimitry Andric case OPT_z: 6490b57cec5SDimitry Andric if (StringRef(arg->getValue()) == "defs") 650e8d8bef9SDimitry Andric diagRegular = true; 651e8d8bef9SDimitry Andric else if (StringRef(arg->getValue()) == "undefs") 652e8d8bef9SDimitry Andric diagRegular = false; 653e8d8bef9SDimitry Andric break; 654e8d8bef9SDimitry Andric case OPT_allow_shlib_undefined: 655e8d8bef9SDimitry Andric diagShlib = false; 656e8d8bef9SDimitry Andric break; 657e8d8bef9SDimitry Andric case OPT_no_allow_shlib_undefined: 658e8d8bef9SDimitry Andric diagShlib = true; 659e8d8bef9SDimitry Andric break; 6600b57cec5SDimitry Andric } 6610b57cec5SDimitry Andric } 6620b57cec5SDimitry Andric 663e8d8bef9SDimitry Andric config->unresolvedSymbols = 664e8d8bef9SDimitry Andric diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore; 665e8d8bef9SDimitry Andric config->unresolvedSymbolsInShlib = 666e8d8bef9SDimitry Andric diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore; 6670b57cec5SDimitry Andric } 6680b57cec5SDimitry Andric 6690b57cec5SDimitry Andric static Target2Policy getTarget2(opt::InputArgList &args) { 6700b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_target2, "got-rel"); 6710b57cec5SDimitry Andric if (s == "rel") 6720b57cec5SDimitry Andric return Target2Policy::Rel; 6730b57cec5SDimitry Andric if (s == "abs") 6740b57cec5SDimitry Andric return Target2Policy::Abs; 6750b57cec5SDimitry Andric if (s == "got-rel") 6760b57cec5SDimitry Andric return Target2Policy::GotRel; 6770b57cec5SDimitry Andric error("unknown --target2 option: " + s); 6780b57cec5SDimitry Andric return Target2Policy::GotRel; 6790b57cec5SDimitry Andric } 6800b57cec5SDimitry Andric 6810b57cec5SDimitry Andric static bool isOutputFormatBinary(opt::InputArgList &args) { 6820b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_oformat, "elf"); 6830b57cec5SDimitry Andric if (s == "binary") 6840b57cec5SDimitry Andric return true; 6850b57cec5SDimitry Andric if (!s.startswith("elf")) 6860b57cec5SDimitry Andric error("unknown --oformat value: " + s); 6870b57cec5SDimitry Andric return false; 6880b57cec5SDimitry Andric } 6890b57cec5SDimitry Andric 6900b57cec5SDimitry Andric static DiscardPolicy getDiscard(opt::InputArgList &args) { 6910b57cec5SDimitry Andric auto *arg = 6920b57cec5SDimitry Andric args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 6930b57cec5SDimitry Andric if (!arg) 6940b57cec5SDimitry Andric return DiscardPolicy::Default; 6950b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_discard_all) 6960b57cec5SDimitry Andric return DiscardPolicy::All; 6970b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_discard_locals) 6980b57cec5SDimitry Andric return DiscardPolicy::Locals; 6990b57cec5SDimitry Andric return DiscardPolicy::None; 7000b57cec5SDimitry Andric } 7010b57cec5SDimitry Andric 7020b57cec5SDimitry Andric static StringRef getDynamicLinker(opt::InputArgList &args) { 7030b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 70455e4f9d5SDimitry Andric if (!arg) 7050b57cec5SDimitry Andric return ""; 70655e4f9d5SDimitry Andric if (arg->getOption().getID() == OPT_no_dynamic_linker) { 70755e4f9d5SDimitry Andric // --no-dynamic-linker suppresses undefined weak symbols in .dynsym 70855e4f9d5SDimitry Andric config->noDynamicLinker = true; 70955e4f9d5SDimitry Andric return ""; 71055e4f9d5SDimitry Andric } 7110b57cec5SDimitry Andric return arg->getValue(); 7120b57cec5SDimitry Andric } 7130b57cec5SDimitry Andric 71481ad6265SDimitry Andric static int getMemtagMode(opt::InputArgList &args) { 71581ad6265SDimitry Andric StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode); 71681ad6265SDimitry Andric if (!config->androidMemtagHeap && !config->androidMemtagStack) { 71781ad6265SDimitry Andric if (!memtagModeArg.empty()) 71881ad6265SDimitry Andric error("when using --android-memtag-mode, at least one of " 71981ad6265SDimitry Andric "--android-memtag-heap or " 72081ad6265SDimitry Andric "--android-memtag-stack is required"); 72181ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 72281ad6265SDimitry Andric } 72381ad6265SDimitry Andric 72481ad6265SDimitry Andric if (memtagModeArg == "sync" || memtagModeArg.empty()) 72581ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_SYNC; 72681ad6265SDimitry Andric if (memtagModeArg == "async") 72781ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_ASYNC; 72881ad6265SDimitry Andric if (memtagModeArg == "none") 72981ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 73081ad6265SDimitry Andric 73181ad6265SDimitry Andric error("unknown --android-memtag-mode value: \"" + memtagModeArg + 73281ad6265SDimitry Andric "\", should be one of {async, sync, none}"); 73381ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 73481ad6265SDimitry Andric } 73581ad6265SDimitry Andric 7360b57cec5SDimitry Andric static ICFLevel getICF(opt::InputArgList &args) { 7370b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all); 7380b57cec5SDimitry Andric if (!arg || arg->getOption().getID() == OPT_icf_none) 7390b57cec5SDimitry Andric return ICFLevel::None; 7400b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_icf_safe) 7410b57cec5SDimitry Andric return ICFLevel::Safe; 7420b57cec5SDimitry Andric return ICFLevel::All; 7430b57cec5SDimitry Andric } 7440b57cec5SDimitry Andric 7450b57cec5SDimitry Andric static StripPolicy getStrip(opt::InputArgList &args) { 7460b57cec5SDimitry Andric if (args.hasArg(OPT_relocatable)) 7470b57cec5SDimitry Andric return StripPolicy::None; 7480b57cec5SDimitry Andric 7490b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug); 7500b57cec5SDimitry Andric if (!arg) 7510b57cec5SDimitry Andric return StripPolicy::None; 7520b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_strip_all) 7530b57cec5SDimitry Andric return StripPolicy::All; 7540b57cec5SDimitry Andric return StripPolicy::Debug; 7550b57cec5SDimitry Andric } 7560b57cec5SDimitry Andric 7570b57cec5SDimitry Andric static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args, 7580b57cec5SDimitry Andric const opt::Arg &arg) { 7590b57cec5SDimitry Andric uint64_t va = 0; 7600b57cec5SDimitry Andric if (s.startswith("0x")) 7610b57cec5SDimitry Andric s = s.drop_front(2); 7620b57cec5SDimitry Andric if (!to_integer(s, va, 16)) 7630b57cec5SDimitry Andric error("invalid argument: " + arg.getAsString(args)); 7640b57cec5SDimitry Andric return va; 7650b57cec5SDimitry Andric } 7660b57cec5SDimitry Andric 7670b57cec5SDimitry Andric static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) { 7680b57cec5SDimitry Andric StringMap<uint64_t> ret; 7690b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section_start)) { 7700b57cec5SDimitry Andric StringRef name; 7710b57cec5SDimitry Andric StringRef addr; 7720b57cec5SDimitry Andric std::tie(name, addr) = StringRef(arg->getValue()).split('='); 7730b57cec5SDimitry Andric ret[name] = parseSectionAddress(addr, args, *arg); 7740b57cec5SDimitry Andric } 7750b57cec5SDimitry Andric 7760b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Ttext)) 7770b57cec5SDimitry Andric ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg); 7780b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Tdata)) 7790b57cec5SDimitry Andric ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg); 7800b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Tbss)) 7810b57cec5SDimitry Andric ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg); 7820b57cec5SDimitry Andric return ret; 7830b57cec5SDimitry Andric } 7840b57cec5SDimitry Andric 7850b57cec5SDimitry Andric static SortSectionPolicy getSortSection(opt::InputArgList &args) { 7860b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_sort_section); 7870b57cec5SDimitry Andric if (s == "alignment") 7880b57cec5SDimitry Andric return SortSectionPolicy::Alignment; 7890b57cec5SDimitry Andric if (s == "name") 7900b57cec5SDimitry Andric return SortSectionPolicy::Name; 7910b57cec5SDimitry Andric if (!s.empty()) 7920b57cec5SDimitry Andric error("unknown --sort-section rule: " + s); 7930b57cec5SDimitry Andric return SortSectionPolicy::Default; 7940b57cec5SDimitry Andric } 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) { 7970b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_orphan_handling, "place"); 7980b57cec5SDimitry Andric if (s == "warn") 7990b57cec5SDimitry Andric return OrphanHandlingPolicy::Warn; 8000b57cec5SDimitry Andric if (s == "error") 8010b57cec5SDimitry Andric return OrphanHandlingPolicy::Error; 8020b57cec5SDimitry Andric if (s != "place") 8030b57cec5SDimitry Andric error("unknown --orphan-handling mode: " + s); 8040b57cec5SDimitry Andric return OrphanHandlingPolicy::Place; 8050b57cec5SDimitry Andric } 8060b57cec5SDimitry Andric 8070b57cec5SDimitry Andric // Parse --build-id or --build-id=<style>. We handle "tree" as a 8080b57cec5SDimitry Andric // synonym for "sha1" because all our hash functions including 809349cc55cSDimitry Andric // --build-id=sha1 are actually tree hashes for performance reasons. 8100b57cec5SDimitry Andric static std::pair<BuildIdKind, std::vector<uint8_t>> 8110b57cec5SDimitry Andric getBuildId(opt::InputArgList &args) { 8120b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq); 8130b57cec5SDimitry Andric if (!arg) 8140b57cec5SDimitry Andric return {BuildIdKind::None, {}}; 8150b57cec5SDimitry Andric 8160b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_build_id) 8170b57cec5SDimitry Andric return {BuildIdKind::Fast, {}}; 8180b57cec5SDimitry Andric 8190b57cec5SDimitry Andric StringRef s = arg->getValue(); 8200b57cec5SDimitry Andric if (s == "fast") 8210b57cec5SDimitry Andric return {BuildIdKind::Fast, {}}; 8220b57cec5SDimitry Andric if (s == "md5") 8230b57cec5SDimitry Andric return {BuildIdKind::Md5, {}}; 8240b57cec5SDimitry Andric if (s == "sha1" || s == "tree") 8250b57cec5SDimitry Andric return {BuildIdKind::Sha1, {}}; 8260b57cec5SDimitry Andric if (s == "uuid") 8270b57cec5SDimitry Andric return {BuildIdKind::Uuid, {}}; 8280b57cec5SDimitry Andric if (s.startswith("0x")) 8290b57cec5SDimitry Andric return {BuildIdKind::Hexstring, parseHex(s.substr(2))}; 8300b57cec5SDimitry Andric 8310b57cec5SDimitry Andric if (s != "none") 8320b57cec5SDimitry Andric error("unknown --build-id style: " + s); 8330b57cec5SDimitry Andric return {BuildIdKind::None, {}}; 8340b57cec5SDimitry Andric } 8350b57cec5SDimitry Andric 8360b57cec5SDimitry Andric static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) { 8370b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none"); 8380b57cec5SDimitry Andric if (s == "android") 8390b57cec5SDimitry Andric return {true, false}; 8400b57cec5SDimitry Andric if (s == "relr") 8410b57cec5SDimitry Andric return {false, true}; 8420b57cec5SDimitry Andric if (s == "android+relr") 8430b57cec5SDimitry Andric return {true, true}; 8440b57cec5SDimitry Andric 8450b57cec5SDimitry Andric if (s != "none") 846349cc55cSDimitry Andric error("unknown --pack-dyn-relocs format: " + s); 8470b57cec5SDimitry Andric return {false, false}; 8480b57cec5SDimitry Andric } 8490b57cec5SDimitry Andric 8500b57cec5SDimitry Andric static void readCallGraph(MemoryBufferRef mb) { 8510b57cec5SDimitry Andric // Build a map from symbol name to section 8520b57cec5SDimitry Andric DenseMap<StringRef, Symbol *> map; 85381ad6265SDimitry Andric for (ELFFileBase *file : ctx->objectFiles) 8540b57cec5SDimitry Andric for (Symbol *sym : file->getSymbols()) 8550b57cec5SDimitry Andric map[sym->getName()] = sym; 8560b57cec5SDimitry Andric 8570b57cec5SDimitry Andric auto findSection = [&](StringRef name) -> InputSectionBase * { 8580b57cec5SDimitry Andric Symbol *sym = map.lookup(name); 8590b57cec5SDimitry Andric if (!sym) { 8600b57cec5SDimitry Andric if (config->warnSymbolOrdering) 8610b57cec5SDimitry Andric warn(mb.getBufferIdentifier() + ": no such symbol: " + name); 8620b57cec5SDimitry Andric return nullptr; 8630b57cec5SDimitry Andric } 8640b57cec5SDimitry Andric maybeWarnUnorderableSymbol(sym); 8650b57cec5SDimitry Andric 8660b57cec5SDimitry Andric if (Defined *dr = dyn_cast_or_null<Defined>(sym)) 8670b57cec5SDimitry Andric return dyn_cast_or_null<InputSectionBase>(dr->section); 8680b57cec5SDimitry Andric return nullptr; 8690b57cec5SDimitry Andric }; 8700b57cec5SDimitry Andric 8710b57cec5SDimitry Andric for (StringRef line : args::getLines(mb)) { 8720b57cec5SDimitry Andric SmallVector<StringRef, 3> fields; 8730b57cec5SDimitry Andric line.split(fields, ' '); 8740b57cec5SDimitry Andric uint64_t count; 8750b57cec5SDimitry Andric 8760b57cec5SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 8770b57cec5SDimitry Andric error(mb.getBufferIdentifier() + ": parse error"); 8780b57cec5SDimitry Andric return; 8790b57cec5SDimitry Andric } 8800b57cec5SDimitry Andric 8810b57cec5SDimitry Andric if (InputSectionBase *from = findSection(fields[0])) 8820b57cec5SDimitry Andric if (InputSectionBase *to = findSection(fields[1])) 8830b57cec5SDimitry Andric config->callGraphProfile[std::make_pair(from, to)] += count; 8840b57cec5SDimitry Andric } 8850b57cec5SDimitry Andric } 8860b57cec5SDimitry Andric 887fe6060f1SDimitry Andric // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns 888fe6060f1SDimitry Andric // true and populates cgProfile and symbolIndices. 889fe6060f1SDimitry Andric template <class ELFT> 890fe6060f1SDimitry Andric static bool 891fe6060f1SDimitry Andric processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices, 892fe6060f1SDimitry Andric ArrayRef<typename ELFT::CGProfile> &cgProfile, 893fe6060f1SDimitry Andric ObjFile<ELFT> *inputObj) { 894fe6060f1SDimitry Andric if (inputObj->cgProfileSectionIndex == SHN_UNDEF) 895fe6060f1SDimitry Andric return false; 896fe6060f1SDimitry Andric 8970eae32dcSDimitry Andric ArrayRef<Elf_Shdr_Impl<ELFT>> objSections = 8980eae32dcSDimitry Andric inputObj->template getELFShdrs<ELFT>(); 8990eae32dcSDimitry Andric symbolIndices.clear(); 9000eae32dcSDimitry Andric const ELFFile<ELFT> &obj = inputObj->getObj(); 901fe6060f1SDimitry Andric cgProfile = 902fe6060f1SDimitry Andric check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>( 903fe6060f1SDimitry Andric objSections[inputObj->cgProfileSectionIndex])); 904fe6060f1SDimitry Andric 905fe6060f1SDimitry Andric for (size_t i = 0, e = objSections.size(); i < e; ++i) { 906fe6060f1SDimitry Andric const Elf_Shdr_Impl<ELFT> &sec = objSections[i]; 907fe6060f1SDimitry Andric if (sec.sh_info == inputObj->cgProfileSectionIndex) { 908fe6060f1SDimitry Andric if (sec.sh_type == SHT_RELA) { 909fe6060f1SDimitry Andric ArrayRef<typename ELFT::Rela> relas = 910fe6060f1SDimitry Andric CHECK(obj.relas(sec), "could not retrieve cg profile rela section"); 911fe6060f1SDimitry Andric for (const typename ELFT::Rela &rel : relas) 912fe6060f1SDimitry Andric symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 913fe6060f1SDimitry Andric break; 914fe6060f1SDimitry Andric } 915fe6060f1SDimitry Andric if (sec.sh_type == SHT_REL) { 916fe6060f1SDimitry Andric ArrayRef<typename ELFT::Rel> rels = 917fe6060f1SDimitry Andric CHECK(obj.rels(sec), "could not retrieve cg profile rel section"); 918fe6060f1SDimitry Andric for (const typename ELFT::Rel &rel : rels) 919fe6060f1SDimitry Andric symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 920fe6060f1SDimitry Andric break; 921fe6060f1SDimitry Andric } 922fe6060f1SDimitry Andric } 923fe6060f1SDimitry Andric } 924fe6060f1SDimitry Andric if (symbolIndices.empty()) 925fe6060f1SDimitry Andric warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't"); 926fe6060f1SDimitry Andric return !symbolIndices.empty(); 927fe6060f1SDimitry Andric } 928fe6060f1SDimitry Andric 9290b57cec5SDimitry Andric template <class ELFT> static void readCallGraphsFromObjectFiles() { 930fe6060f1SDimitry Andric SmallVector<uint32_t, 32> symbolIndices; 931fe6060f1SDimitry Andric ArrayRef<typename ELFT::CGProfile> cgProfile; 93281ad6265SDimitry Andric for (auto file : ctx->objectFiles) { 9330b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(file); 934fe6060f1SDimitry Andric if (!processCallGraphRelocations(symbolIndices, cgProfile, obj)) 935fe6060f1SDimitry Andric continue; 9360b57cec5SDimitry Andric 937fe6060f1SDimitry Andric if (symbolIndices.size() != cgProfile.size() * 2) 938fe6060f1SDimitry Andric fatal("number of relocations doesn't match Weights"); 939fe6060f1SDimitry Andric 940fe6060f1SDimitry Andric for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) { 941fe6060f1SDimitry Andric const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i]; 942fe6060f1SDimitry Andric uint32_t fromIndex = symbolIndices[i * 2]; 943fe6060f1SDimitry Andric uint32_t toIndex = symbolIndices[i * 2 + 1]; 944fe6060f1SDimitry Andric auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex)); 945fe6060f1SDimitry Andric auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex)); 9460b57cec5SDimitry Andric if (!fromSym || !toSym) 9470b57cec5SDimitry Andric continue; 9480b57cec5SDimitry Andric 9490b57cec5SDimitry Andric auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section); 9500b57cec5SDimitry Andric auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section); 9510b57cec5SDimitry Andric if (from && to) 9520b57cec5SDimitry Andric config->callGraphProfile[{from, to}] += cgpe.cgp_weight; 9530b57cec5SDimitry Andric } 9540b57cec5SDimitry Andric } 9550b57cec5SDimitry Andric } 9560b57cec5SDimitry Andric 9570b57cec5SDimitry Andric static bool getCompressDebugSections(opt::InputArgList &args) { 9580b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none"); 9590b57cec5SDimitry Andric if (s == "none") 9600b57cec5SDimitry Andric return false; 9610b57cec5SDimitry Andric if (s != "zlib") 9620b57cec5SDimitry Andric error("unknown --compress-debug-sections value: " + s); 963753f127fSDimitry Andric if (!compression::zlib::isAvailable()) 9640b57cec5SDimitry Andric error("--compress-debug-sections: zlib is not available"); 9650b57cec5SDimitry Andric return true; 9660b57cec5SDimitry Andric } 9670b57cec5SDimitry Andric 96885868e8aSDimitry Andric static StringRef getAliasSpelling(opt::Arg *arg) { 96985868e8aSDimitry Andric if (const opt::Arg *alias = arg->getAlias()) 97085868e8aSDimitry Andric return alias->getSpelling(); 97185868e8aSDimitry Andric return arg->getSpelling(); 97285868e8aSDimitry Andric } 97385868e8aSDimitry Andric 9740b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 9750b57cec5SDimitry Andric unsigned id) { 9760b57cec5SDimitry Andric auto *arg = args.getLastArg(id); 9770b57cec5SDimitry Andric if (!arg) 9780b57cec5SDimitry Andric return {"", ""}; 9790b57cec5SDimitry Andric 9800b57cec5SDimitry Andric StringRef s = arg->getValue(); 9810b57cec5SDimitry Andric std::pair<StringRef, StringRef> ret = s.split(';'); 9820b57cec5SDimitry Andric if (ret.second.empty()) 98385868e8aSDimitry Andric error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s); 9840b57cec5SDimitry Andric return ret; 9850b57cec5SDimitry Andric } 9860b57cec5SDimitry Andric 9870b57cec5SDimitry Andric // Parse the symbol ordering file and warn for any duplicate entries. 9880b57cec5SDimitry Andric static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) { 9890b57cec5SDimitry Andric SetVector<StringRef> names; 9900b57cec5SDimitry Andric for (StringRef s : args::getLines(mb)) 9910b57cec5SDimitry Andric if (!names.insert(s) && config->warnSymbolOrdering) 9920b57cec5SDimitry Andric warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s); 9930b57cec5SDimitry Andric 9940b57cec5SDimitry Andric return names.takeVector(); 9950b57cec5SDimitry Andric } 9960b57cec5SDimitry Andric 9975ffd83dbSDimitry Andric static bool getIsRela(opt::InputArgList &args) { 9985ffd83dbSDimitry Andric // If -z rel or -z rela is specified, use the last option. 9995ffd83dbSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 10005ffd83dbSDimitry Andric StringRef s(arg->getValue()); 10015ffd83dbSDimitry Andric if (s == "rel") 10025ffd83dbSDimitry Andric return false; 10035ffd83dbSDimitry Andric if (s == "rela") 10045ffd83dbSDimitry Andric return true; 10055ffd83dbSDimitry Andric } 10065ffd83dbSDimitry Andric 10075ffd83dbSDimitry Andric // Otherwise use the psABI defined relocation entry format. 10085ffd83dbSDimitry Andric uint16_t m = config->emachine; 10095ffd83dbSDimitry Andric return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC || 10105ffd83dbSDimitry Andric m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64; 10115ffd83dbSDimitry Andric } 10125ffd83dbSDimitry Andric 10130b57cec5SDimitry Andric static void parseClangOption(StringRef opt, const Twine &msg) { 10140b57cec5SDimitry Andric std::string err; 10150b57cec5SDimitry Andric raw_string_ostream os(err); 10160b57cec5SDimitry Andric 10170b57cec5SDimitry Andric const char *argv[] = {config->progName.data(), opt.data()}; 10180b57cec5SDimitry Andric if (cl::ParseCommandLineOptions(2, argv, "", &os)) 10190b57cec5SDimitry Andric return; 10200b57cec5SDimitry Andric os.flush(); 10210b57cec5SDimitry Andric error(msg + ": " + StringRef(err).trim()); 10220b57cec5SDimitry Andric } 10230b57cec5SDimitry Andric 10240eae32dcSDimitry Andric // Checks the parameter of the bti-report and cet-report options. 10250eae32dcSDimitry Andric static bool isValidReportString(StringRef arg) { 10260eae32dcSDimitry Andric return arg == "none" || arg == "warning" || arg == "error"; 10270eae32dcSDimitry Andric } 10280eae32dcSDimitry Andric 10290b57cec5SDimitry Andric // Initializes Config members by the command line options. 10300b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args) { 10310b57cec5SDimitry Andric errorHandler().verbose = args.hasArg(OPT_verbose); 10320b57cec5SDimitry Andric errorHandler().vsDiagnostics = 10330b57cec5SDimitry Andric args.hasArg(OPT_visual_studio_diagnostics_format, false); 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric config->allowMultipleDefinition = 10360b57cec5SDimitry Andric args.hasFlag(OPT_allow_multiple_definition, 10370b57cec5SDimitry Andric OPT_no_allow_multiple_definition, false) || 10380b57cec5SDimitry Andric hasZOption(args, "muldefs"); 103981ad6265SDimitry Andric config->androidMemtagHeap = 104081ad6265SDimitry Andric args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false); 104181ad6265SDimitry Andric config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack, 104281ad6265SDimitry Andric OPT_no_android_memtag_stack, false); 104381ad6265SDimitry Andric config->androidMemtagMode = getMemtagMode(args); 10440b57cec5SDimitry Andric config->auxiliaryList = args::getStrings(args, OPT_auxiliary); 10456e75b2fbSDimitry Andric if (opt::Arg *arg = 10466e75b2fbSDimitry Andric args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions, 10476e75b2fbSDimitry Andric OPT_Bsymbolic_functions, OPT_Bsymbolic)) { 10486e75b2fbSDimitry Andric if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions)) 10496e75b2fbSDimitry Andric config->bsymbolic = BsymbolicKind::NonWeakFunctions; 10506e75b2fbSDimitry Andric else if (arg->getOption().matches(OPT_Bsymbolic_functions)) 10516e75b2fbSDimitry Andric config->bsymbolic = BsymbolicKind::Functions; 1052fe6060f1SDimitry Andric else if (arg->getOption().matches(OPT_Bsymbolic)) 10536e75b2fbSDimitry Andric config->bsymbolic = BsymbolicKind::All; 1054fe6060f1SDimitry Andric } 10550b57cec5SDimitry Andric config->checkSections = 10560b57cec5SDimitry Andric args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 10570b57cec5SDimitry Andric config->chroot = args.getLastArgValue(OPT_chroot); 10580b57cec5SDimitry Andric config->compressDebugSections = getCompressDebugSections(args); 1059fe6060f1SDimitry Andric config->cref = args.hasArg(OPT_cref); 10605ffd83dbSDimitry Andric config->optimizeBBJumps = 10615ffd83dbSDimitry Andric args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false); 10620b57cec5SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true); 1063e8d8bef9SDimitry Andric config->dependencyFile = args.getLastArgValue(OPT_dependency_file); 10640b57cec5SDimitry Andric config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true); 10650b57cec5SDimitry Andric config->disableVerify = args.hasArg(OPT_disable_verify); 10660b57cec5SDimitry Andric config->discard = getDiscard(args); 10670b57cec5SDimitry Andric config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq); 10680b57cec5SDimitry Andric config->dynamicLinker = getDynamicLinker(args); 10690b57cec5SDimitry Andric config->ehFrameHdr = 10700b57cec5SDimitry Andric args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 10710b57cec5SDimitry Andric config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false); 10720b57cec5SDimitry Andric config->emitRelocs = args.hasArg(OPT_emit_relocs); 10730b57cec5SDimitry Andric config->callGraphProfileSort = args.hasFlag( 10740b57cec5SDimitry Andric OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true); 10750b57cec5SDimitry Andric config->enableNewDtags = 10760b57cec5SDimitry Andric args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 10770b57cec5SDimitry Andric config->entry = args.getLastArgValue(OPT_entry); 1078e8d8bef9SDimitry Andric 1079e8d8bef9SDimitry Andric errorHandler().errorHandlingScript = 1080e8d8bef9SDimitry Andric args.getLastArgValue(OPT_error_handling_script); 1081e8d8bef9SDimitry Andric 10820b57cec5SDimitry Andric config->executeOnly = 10830b57cec5SDimitry Andric args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 10840b57cec5SDimitry Andric config->exportDynamic = 108581ad6265SDimitry Andric args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) || 108681ad6265SDimitry Andric args.hasArg(OPT_shared); 10870b57cec5SDimitry Andric config->filterList = args::getStrings(args, OPT_filter); 10880b57cec5SDimitry Andric config->fini = args.getLastArgValue(OPT_fini, "_fini"); 10895ffd83dbSDimitry Andric config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) && 10905ffd83dbSDimitry Andric !args.hasArg(OPT_relocatable); 10915ffd83dbSDimitry Andric config->fixCortexA8 = 10925ffd83dbSDimitry Andric args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable); 1093e8d8bef9SDimitry Andric config->fortranCommon = 109481ad6265SDimitry Andric args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false); 10950b57cec5SDimitry Andric config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 10960b57cec5SDimitry Andric config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 10970b57cec5SDimitry Andric config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 10980b57cec5SDimitry Andric config->icf = getICF(args); 10990b57cec5SDimitry Andric config->ignoreDataAddressEquality = 11000b57cec5SDimitry Andric args.hasArg(OPT_ignore_data_address_equality); 11010b57cec5SDimitry Andric config->ignoreFunctionAddressEquality = 11020b57cec5SDimitry Andric args.hasArg(OPT_ignore_function_address_equality); 11030b57cec5SDimitry Andric config->init = args.getLastArgValue(OPT_init, "_init"); 11040b57cec5SDimitry Andric config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline); 11050b57cec5SDimitry Andric config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 11060b57cec5SDimitry Andric config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 1107349cc55cSDimitry Andric config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1108349cc55cSDimitry Andric OPT_no_lto_pgo_warn_mismatch, true); 11090b57cec5SDimitry Andric config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager); 11105ffd83dbSDimitry Andric config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm); 11110b57cec5SDimitry Andric config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes); 11125ffd83dbSDimitry Andric config->ltoWholeProgramVisibility = 1113e8d8bef9SDimitry Andric args.hasFlag(OPT_lto_whole_program_visibility, 1114e8d8bef9SDimitry Andric OPT_no_lto_whole_program_visibility, false); 11150b57cec5SDimitry Andric config->ltoo = args::getInteger(args, OPT_lto_O, 2); 111685868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq); 11170b57cec5SDimitry Andric config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1); 11180b57cec5SDimitry Andric config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 11195ffd83dbSDimitry Andric config->ltoBasicBlockSections = 1120e8d8bef9SDimitry Andric args.getLastArgValue(OPT_lto_basic_block_sections); 11215ffd83dbSDimitry Andric config->ltoUniqueBasicBlockSectionNames = 1122e8d8bef9SDimitry Andric args.hasFlag(OPT_lto_unique_basic_block_section_names, 1123e8d8bef9SDimitry Andric OPT_no_lto_unique_basic_block_section_names, false); 11240b57cec5SDimitry Andric config->mapFile = args.getLastArgValue(OPT_Map); 11250b57cec5SDimitry Andric config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0); 11260b57cec5SDimitry Andric config->mergeArmExidx = 11270b57cec5SDimitry Andric args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 1128480093f4SDimitry Andric config->mmapOutputFile = 1129480093f4SDimitry Andric args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true); 11300b57cec5SDimitry Andric config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 11310b57cec5SDimitry Andric config->noinhibitExec = args.hasArg(OPT_noinhibit_exec); 11320b57cec5SDimitry Andric config->nostdlib = args.hasArg(OPT_nostdlib); 11330b57cec5SDimitry Andric config->oFormatBinary = isOutputFormatBinary(args); 11340b57cec5SDimitry Andric config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false); 113581ad6265SDimitry Andric config->opaquePointers = args.hasFlag( 113681ad6265SDimitry Andric OPT_plugin_opt_opaque_pointers, OPT_plugin_opt_no_opaque_pointers, true); 11370b57cec5SDimitry Andric config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename); 113881ad6265SDimitry Andric config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file); 1139e8d8bef9SDimitry Andric 1140e8d8bef9SDimitry Andric // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 1141e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) { 1142e8d8bef9SDimitry Andric auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue()); 1143e8d8bef9SDimitry Andric if (!resultOrErr) 1144e8d8bef9SDimitry Andric error(arg->getSpelling() + ": invalid argument '" + arg->getValue() + 1145e8d8bef9SDimitry Andric "', only integer or 'auto' is supported"); 1146e8d8bef9SDimitry Andric else 1147e8d8bef9SDimitry Andric config->optRemarksHotnessThreshold = *resultOrErr; 1148e8d8bef9SDimitry Andric } 1149e8d8bef9SDimitry Andric 11500b57cec5SDimitry Andric config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes); 11510b57cec5SDimitry Andric config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness); 11520b57cec5SDimitry Andric config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format); 11530b57cec5SDimitry Andric config->optimize = args::getInteger(args, OPT_O, 1); 11540b57cec5SDimitry Andric config->orphanHandling = getOrphanHandling(args); 11550b57cec5SDimitry Andric config->outputFile = args.getLastArgValue(OPT_o); 11560b57cec5SDimitry Andric config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false); 11570b57cec5SDimitry Andric config->printIcfSections = 11580b57cec5SDimitry Andric args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 11590b57cec5SDimitry Andric config->printGcSections = 11600b57cec5SDimitry Andric args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 11615ffd83dbSDimitry Andric config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats); 11620b57cec5SDimitry Andric config->printSymbolOrder = 11630b57cec5SDimitry Andric args.getLastArgValue(OPT_print_symbol_order); 1164349cc55cSDimitry Andric config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true); 11650b57cec5SDimitry Andric config->rpath = getRpath(args); 11660b57cec5SDimitry Andric config->relocatable = args.hasArg(OPT_relocatable); 1167753f127fSDimitry Andric 1168753f127fSDimitry Andric if (args.hasArg(OPT_save_temps)) { 1169753f127fSDimitry Andric // --save-temps implies saving all temps. 1170753f127fSDimitry Andric for (const char *s : saveTempsValues) 1171753f127fSDimitry Andric config->saveTempsArgs.insert(s); 1172753f127fSDimitry Andric } else { 1173753f127fSDimitry Andric for (auto *arg : args.filtered(OPT_save_temps_eq)) { 1174753f127fSDimitry Andric StringRef s = arg->getValue(); 1175753f127fSDimitry Andric if (llvm::is_contained(saveTempsValues, s)) 1176753f127fSDimitry Andric config->saveTempsArgs.insert(s); 1177753f127fSDimitry Andric else 1178753f127fSDimitry Andric error("unknown --save-temps value: " + s); 1179753f127fSDimitry Andric } 1180753f127fSDimitry Andric } 1181753f127fSDimitry Andric 11820b57cec5SDimitry Andric config->searchPaths = args::getStrings(args, OPT_library_path); 11830b57cec5SDimitry Andric config->sectionStartMap = getSectionStartMap(args); 11840b57cec5SDimitry Andric config->shared = args.hasArg(OPT_shared); 11855ffd83dbSDimitry Andric config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true); 11860b57cec5SDimitry Andric config->soName = args.getLastArgValue(OPT_soname); 11870b57cec5SDimitry Andric config->sortSection = getSortSection(args); 11880b57cec5SDimitry Andric config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384); 11890b57cec5SDimitry Andric config->strip = getStrip(args); 11900b57cec5SDimitry Andric config->sysroot = args.getLastArgValue(OPT_sysroot); 11910b57cec5SDimitry Andric config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 11920b57cec5SDimitry Andric config->target2 = getTarget2(args); 11930b57cec5SDimitry Andric config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir); 11940b57cec5SDimitry Andric config->thinLTOCachePolicy = CHECK( 11950b57cec5SDimitry Andric parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)), 11960b57cec5SDimitry Andric "--thinlto-cache-policy: invalid cache policy"); 119785868e8aSDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 119881ad6265SDimitry Andric config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) || 119981ad6265SDimitry Andric args.hasArg(OPT_thinlto_index_only) || 120081ad6265SDimitry Andric args.hasArg(OPT_thinlto_index_only_eq); 120185868e8aSDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 120285868e8aSDimitry Andric args.hasArg(OPT_thinlto_index_only_eq); 120385868e8aSDimitry Andric config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq); 12040b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 120585868e8aSDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq); 12060b57cec5SDimitry Andric config->thinLTOPrefixReplace = 120785868e8aSDimitry Andric getOldNewOptions(args, OPT_thinlto_prefix_replace_eq); 120881ad6265SDimitry Andric if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) { 120981ad6265SDimitry Andric if (args.hasArg(OPT_thinlto_object_suffix_replace_eq)) 121081ad6265SDimitry Andric error("--thinlto-object-suffix-replace is not supported with " 121181ad6265SDimitry Andric "--thinlto-emit-index-files"); 121281ad6265SDimitry Andric else if (args.hasArg(OPT_thinlto_prefix_replace_eq)) 121381ad6265SDimitry Andric error("--thinlto-prefix-replace is not supported with " 121481ad6265SDimitry Andric "--thinlto-emit-index-files"); 121581ad6265SDimitry Andric } 12165ffd83dbSDimitry Andric config->thinLTOModulesToCompile = 12175ffd83dbSDimitry Andric args::getStrings(args, OPT_thinlto_single_module_eq); 121881ad6265SDimitry Andric config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq); 12195ffd83dbSDimitry Andric config->timeTraceGranularity = 12205ffd83dbSDimitry Andric args::getInteger(args, OPT_time_trace_granularity, 500); 12210b57cec5SDimitry Andric config->trace = args.hasArg(OPT_trace); 12220b57cec5SDimitry Andric config->undefined = args::getStrings(args, OPT_undefined); 12230b57cec5SDimitry Andric config->undefinedVersion = 12240b57cec5SDimitry Andric args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true); 12255ffd83dbSDimitry Andric config->unique = args.hasArg(OPT_unique); 12260b57cec5SDimitry Andric config->useAndroidRelrTags = args.hasFlag( 12270b57cec5SDimitry Andric OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 12280b57cec5SDimitry Andric config->warnBackrefs = 12290b57cec5SDimitry Andric args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 12300b57cec5SDimitry Andric config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 12310b57cec5SDimitry Andric config->warnSymbolOrdering = 12320b57cec5SDimitry Andric args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 1233349cc55cSDimitry Andric config->whyExtract = args.getLastArgValue(OPT_why_extract); 12340b57cec5SDimitry Andric config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true); 12350b57cec5SDimitry Andric config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true); 12365ffd83dbSDimitry Andric config->zForceBti = hasZOption(args, "force-bti"); 1237480093f4SDimitry Andric config->zForceIbt = hasZOption(args, "force-ibt"); 12380b57cec5SDimitry Andric config->zGlobal = hasZOption(args, "global"); 1239480093f4SDimitry Andric config->zGnustack = getZGnuStack(args); 12400b57cec5SDimitry Andric config->zHazardplt = hasZOption(args, "hazardplt"); 12410b57cec5SDimitry Andric config->zIfuncNoplt = hasZOption(args, "ifunc-noplt"); 12420b57cec5SDimitry Andric config->zInitfirst = hasZOption(args, "initfirst"); 12430b57cec5SDimitry Andric config->zInterpose = hasZOption(args, "interpose"); 12440b57cec5SDimitry Andric config->zKeepTextSectionPrefix = getZFlag( 12450b57cec5SDimitry Andric args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 12460b57cec5SDimitry Andric config->zNodefaultlib = hasZOption(args, "nodefaultlib"); 12470b57cec5SDimitry Andric config->zNodelete = hasZOption(args, "nodelete"); 12480b57cec5SDimitry Andric config->zNodlopen = hasZOption(args, "nodlopen"); 12490b57cec5SDimitry Andric config->zNow = getZFlag(args, "now", "lazy", false); 12500b57cec5SDimitry Andric config->zOrigin = hasZOption(args, "origin"); 12515ffd83dbSDimitry Andric config->zPacPlt = hasZOption(args, "pac-plt"); 12520b57cec5SDimitry Andric config->zRelro = getZFlag(args, "relro", "norelro", true); 12530b57cec5SDimitry Andric config->zRetpolineplt = hasZOption(args, "retpolineplt"); 12540b57cec5SDimitry Andric config->zRodynamic = hasZOption(args, "rodynamic"); 125585868e8aSDimitry Andric config->zSeparate = getZSeparate(args); 1256480093f4SDimitry Andric config->zShstk = hasZOption(args, "shstk"); 12570b57cec5SDimitry Andric config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0); 1258fe6060f1SDimitry Andric config->zStartStopGC = 1259fe6060f1SDimitry Andric getZFlag(args, "start-stop-gc", "nostart-stop-gc", true); 12605ffd83dbSDimitry Andric config->zStartStopVisibility = getZStartStopVisibility(args); 12610b57cec5SDimitry Andric config->zText = getZFlag(args, "text", "notext", true); 12620b57cec5SDimitry Andric config->zWxneeded = hasZOption(args, "wxneeded"); 1263e8d8bef9SDimitry Andric setUnresolvedSymbolPolicy(args); 12644824e7fdSDimitry Andric config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no"; 1265fe6060f1SDimitry Andric 1266fe6060f1SDimitry Andric if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) { 1267fe6060f1SDimitry Andric if (arg->getOption().matches(OPT_eb)) 1268fe6060f1SDimitry Andric config->optEB = true; 1269fe6060f1SDimitry Andric else 1270fe6060f1SDimitry Andric config->optEL = true; 1271fe6060f1SDimitry Andric } 1272fe6060f1SDimitry Andric 1273fe6060f1SDimitry Andric for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) { 1274fe6060f1SDimitry Andric constexpr StringRef errPrefix = "--shuffle-sections=: "; 1275fe6060f1SDimitry Andric std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 1276fe6060f1SDimitry Andric if (kv.first.empty() || kv.second.empty()) { 1277fe6060f1SDimitry Andric error(errPrefix + "expected <section_glob>=<seed>, but got '" + 1278fe6060f1SDimitry Andric arg->getValue() + "'"); 1279fe6060f1SDimitry Andric continue; 1280fe6060f1SDimitry Andric } 1281fe6060f1SDimitry Andric // Signed so that <section_glob>=-1 is allowed. 1282fe6060f1SDimitry Andric int64_t v; 1283fe6060f1SDimitry Andric if (!to_integer(kv.second, v)) 1284fe6060f1SDimitry Andric error(errPrefix + "expected an integer, but got '" + kv.second + "'"); 1285fe6060f1SDimitry Andric else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1286fe6060f1SDimitry Andric config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v)); 1287fe6060f1SDimitry Andric else 1288fe6060f1SDimitry Andric error(errPrefix + toString(pat.takeError())); 1289fe6060f1SDimitry Andric } 12900b57cec5SDimitry Andric 12910eae32dcSDimitry Andric auto reports = {std::make_pair("bti-report", &config->zBtiReport), 12920eae32dcSDimitry Andric std::make_pair("cet-report", &config->zCetReport)}; 12930eae32dcSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_z)) { 12940eae32dcSDimitry Andric std::pair<StringRef, StringRef> option = 12950eae32dcSDimitry Andric StringRef(arg->getValue()).split('='); 12960eae32dcSDimitry Andric for (auto reportArg : reports) { 12970eae32dcSDimitry Andric if (option.first != reportArg.first) 12980eae32dcSDimitry Andric continue; 12990eae32dcSDimitry Andric if (!isValidReportString(option.second)) { 13000eae32dcSDimitry Andric error(Twine("-z ") + reportArg.first + "= parameter " + option.second + 13010eae32dcSDimitry Andric " is not recognized"); 13020eae32dcSDimitry Andric continue; 13030eae32dcSDimitry Andric } 13040eae32dcSDimitry Andric *reportArg.second = option.second; 13050eae32dcSDimitry Andric } 13060eae32dcSDimitry Andric } 13070eae32dcSDimitry Andric 13085ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_z)) { 13095ffd83dbSDimitry Andric std::pair<StringRef, StringRef> option = 13105ffd83dbSDimitry Andric StringRef(arg->getValue()).split('='); 13115ffd83dbSDimitry Andric if (option.first != "dead-reloc-in-nonalloc") 13125ffd83dbSDimitry Andric continue; 13135ffd83dbSDimitry Andric constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: "; 13145ffd83dbSDimitry Andric std::pair<StringRef, StringRef> kv = option.second.split('='); 13155ffd83dbSDimitry Andric if (kv.first.empty() || kv.second.empty()) { 13165ffd83dbSDimitry Andric error(errPrefix + "expected <section_glob>=<value>"); 13175ffd83dbSDimitry Andric continue; 13185ffd83dbSDimitry Andric } 13195ffd83dbSDimitry Andric uint64_t v; 13205ffd83dbSDimitry Andric if (!to_integer(kv.second, v)) 13215ffd83dbSDimitry Andric error(errPrefix + "expected a non-negative integer, but got '" + 13225ffd83dbSDimitry Andric kv.second + "'"); 13235ffd83dbSDimitry Andric else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 13245ffd83dbSDimitry Andric config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v); 13255ffd83dbSDimitry Andric else 13265ffd83dbSDimitry Andric error(errPrefix + toString(pat.takeError())); 13275ffd83dbSDimitry Andric } 13285ffd83dbSDimitry Andric 1329e8d8bef9SDimitry Andric cl::ResetAllOptionOccurrences(); 1330e8d8bef9SDimitry Andric 13310b57cec5SDimitry Andric // Parse LTO options. 13320b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq)) 133304eeddc0SDimitry Andric parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())), 13340b57cec5SDimitry Andric arg->getSpelling()); 13350b57cec5SDimitry Andric 13365ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus)) 13375ffd83dbSDimitry Andric parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling()); 13385ffd83dbSDimitry Andric 13395ffd83dbSDimitry Andric // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or 13405ffd83dbSDimitry Andric // relative path. Just ignore. If not ended with "lto-wrapper", consider it an 13415ffd83dbSDimitry Andric // unsupported LLVMgold.so option and error. 13425ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) 13435ffd83dbSDimitry Andric if (!StringRef(arg->getValue()).endswith("lto-wrapper")) 13445ffd83dbSDimitry Andric error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() + 13455ffd83dbSDimitry Andric "'"); 13460b57cec5SDimitry Andric 134781ad6265SDimitry Andric config->passPlugins = args::getStrings(args, OPT_load_pass_plugins); 134881ad6265SDimitry Andric 13490b57cec5SDimitry Andric // Parse -mllvm options. 13500b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_mllvm)) 13510b57cec5SDimitry Andric parseClangOption(arg->getValue(), arg->getSpelling()); 13520b57cec5SDimitry Andric 13535ffd83dbSDimitry Andric // --threads= takes a positive integer and provides the default value for 13545ffd83dbSDimitry Andric // --thinlto-jobs=. 13555ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 13565ffd83dbSDimitry Andric StringRef v(arg->getValue()); 13575ffd83dbSDimitry Andric unsigned threads = 0; 13585ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 13595ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 13605ffd83dbSDimitry Andric arg->getValue() + "'"); 13615ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 13625ffd83dbSDimitry Andric config->thinLTOJobs = v; 13635ffd83dbSDimitry Andric } 13645ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_thinlto_jobs)) 13655ffd83dbSDimitry Andric config->thinLTOJobs = arg->getValue(); 13665ffd83dbSDimitry Andric 13670b57cec5SDimitry Andric if (config->ltoo > 3) 13680b57cec5SDimitry Andric error("invalid optimization level for LTO: " + Twine(config->ltoo)); 13690b57cec5SDimitry Andric if (config->ltoPartitions == 0) 13700b57cec5SDimitry Andric error("--lto-partitions: number of threads must be > 0"); 13715ffd83dbSDimitry Andric if (!get_threadpool_strategy(config->thinLTOJobs)) 13725ffd83dbSDimitry Andric error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 13730b57cec5SDimitry Andric 13740b57cec5SDimitry Andric if (config->splitStackAdjustSize < 0) 13750b57cec5SDimitry Andric error("--split-stack-adjust-size: size must be >= 0"); 13760b57cec5SDimitry Andric 1377480093f4SDimitry Andric // The text segment is traditionally the first segment, whose address equals 1378480093f4SDimitry Andric // the base address. However, lld places the R PT_LOAD first. -Ttext-segment 1379480093f4SDimitry Andric // is an old-fashioned option that does not play well with lld's layout. 1380480093f4SDimitry Andric // Suggest --image-base as a likely alternative. 1381480093f4SDimitry Andric if (args.hasArg(OPT_Ttext_segment)) 1382480093f4SDimitry Andric error("-Ttext-segment is not supported. Use --image-base if you " 1383480093f4SDimitry Andric "intend to set the base address"); 1384480093f4SDimitry Andric 13850b57cec5SDimitry Andric // Parse ELF{32,64}{LE,BE} and CPU type. 13860b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_m)) { 13870b57cec5SDimitry Andric StringRef s = arg->getValue(); 13880b57cec5SDimitry Andric std::tie(config->ekind, config->emachine, config->osabi) = 13890b57cec5SDimitry Andric parseEmulation(s); 13900b57cec5SDimitry Andric config->mipsN32Abi = 13910b57cec5SDimitry Andric (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32")); 13920b57cec5SDimitry Andric config->emulation = s; 13930b57cec5SDimitry Andric } 13940b57cec5SDimitry Andric 1395349cc55cSDimitry Andric // Parse --hash-style={sysv,gnu,both}. 13960b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_hash_style)) { 13970b57cec5SDimitry Andric StringRef s = arg->getValue(); 13980b57cec5SDimitry Andric if (s == "sysv") 13990b57cec5SDimitry Andric config->sysvHash = true; 14000b57cec5SDimitry Andric else if (s == "gnu") 14010b57cec5SDimitry Andric config->gnuHash = true; 14020b57cec5SDimitry Andric else if (s == "both") 14030b57cec5SDimitry Andric config->sysvHash = config->gnuHash = true; 14040b57cec5SDimitry Andric else 1405349cc55cSDimitry Andric error("unknown --hash-style: " + s); 14060b57cec5SDimitry Andric } 14070b57cec5SDimitry Andric 14080b57cec5SDimitry Andric if (args.hasArg(OPT_print_map)) 14090b57cec5SDimitry Andric config->mapFile = "-"; 14100b57cec5SDimitry Andric 14110b57cec5SDimitry Andric // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 14120b57cec5SDimitry Andric // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 14130b57cec5SDimitry Andric // it. 14140b57cec5SDimitry Andric if (config->nmagic || config->omagic) 14150b57cec5SDimitry Andric config->zRelro = false; 14160b57cec5SDimitry Andric 14170b57cec5SDimitry Andric std::tie(config->buildId, config->buildIdVector) = getBuildId(args); 14180b57cec5SDimitry Andric 141981ad6265SDimitry Andric if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) { 142081ad6265SDimitry Andric config->relrGlibc = true; 142181ad6265SDimitry Andric config->relrPackDynRelocs = true; 142281ad6265SDimitry Andric } else { 14230b57cec5SDimitry Andric std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) = 14240b57cec5SDimitry Andric getPackDynRelocs(args); 142581ad6265SDimitry Andric } 14260b57cec5SDimitry Andric 14270b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){ 14280b57cec5SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 14290b57cec5SDimitry Andric error("--symbol-ordering-file and --call-graph-order-file " 14300b57cec5SDimitry Andric "may not be used together"); 14310b57cec5SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){ 14320b57cec5SDimitry Andric config->symbolOrderingFile = getSymbolOrderingFile(*buffer); 14330b57cec5SDimitry Andric // Also need to disable CallGraphProfileSort to prevent 14340b57cec5SDimitry Andric // LLD order symbols with CGProfile 14350b57cec5SDimitry Andric config->callGraphProfileSort = false; 14360b57cec5SDimitry Andric } 14370b57cec5SDimitry Andric } 14380b57cec5SDimitry Andric 143985868e8aSDimitry Andric assert(config->versionDefinitions.empty()); 144085868e8aSDimitry Andric config->versionDefinitions.push_back( 14416e75b2fbSDimitry Andric {"local", (uint16_t)VER_NDX_LOCAL, {}, {}}); 14426e75b2fbSDimitry Andric config->versionDefinitions.push_back( 14436e75b2fbSDimitry Andric {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}}); 144485868e8aSDimitry Andric 14450b57cec5SDimitry Andric // If --retain-symbol-file is used, we'll keep only the symbols listed in 14460b57cec5SDimitry Andric // the file and discard all others. 14470b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) { 14486e75b2fbSDimitry Andric config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back( 144985868e8aSDimitry Andric {"*", /*isExternCpp=*/false, /*hasWildcard=*/true}); 14500b57cec5SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 14510b57cec5SDimitry Andric for (StringRef s : args::getLines(*buffer)) 14526e75b2fbSDimitry Andric config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back( 145385868e8aSDimitry Andric {s, /*isExternCpp=*/false, /*hasWildcard=*/false}); 14540b57cec5SDimitry Andric } 14550b57cec5SDimitry Andric 14565ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) { 14575ffd83dbSDimitry Andric StringRef pattern(arg->getValue()); 14585ffd83dbSDimitry Andric if (Expected<GlobPattern> pat = GlobPattern::create(pattern)) 14595ffd83dbSDimitry Andric config->warnBackrefsExclude.push_back(std::move(*pat)); 14605ffd83dbSDimitry Andric else 14615ffd83dbSDimitry Andric error(arg->getSpelling() + ": " + toString(pat.takeError())); 14625ffd83dbSDimitry Andric } 14635ffd83dbSDimitry Andric 1464349cc55cSDimitry Andric // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols 1465349cc55cSDimitry Andric // which should be exported. For -shared, references to matched non-local 1466349cc55cSDimitry Andric // STV_DEFAULT symbols are not bound to definitions within the shared object, 1467349cc55cSDimitry Andric // even if other options express a symbolic intention: -Bsymbolic, 14685ffd83dbSDimitry Andric // -Bsymbolic-functions (if STT_FUNC), --dynamic-list. 14690b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export_dynamic_symbol)) 14700b57cec5SDimitry Andric config->dynamicList.push_back( 14715ffd83dbSDimitry Andric {arg->getValue(), /*isExternCpp=*/false, 14725ffd83dbSDimitry Andric /*hasWildcard=*/hasWildcard(arg->getValue())}); 14730b57cec5SDimitry Andric 1474349cc55cSDimitry Andric // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol 1475349cc55cSDimitry Andric // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic 1476349cc55cSDimitry Andric // like semantics. 1477349cc55cSDimitry Andric config->symbolic = 1478349cc55cSDimitry Andric config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list); 1479349cc55cSDimitry Andric for (auto *arg : 1480349cc55cSDimitry Andric args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list)) 1481349cc55cSDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1482349cc55cSDimitry Andric readDynamicList(*buffer); 1483349cc55cSDimitry Andric 14840b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_version_script)) 14850b57cec5SDimitry Andric if (Optional<std::string> path = searchScript(arg->getValue())) { 14860b57cec5SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(*path)) 14870b57cec5SDimitry Andric readVersionScript(*buffer); 14880b57cec5SDimitry Andric } else { 14890b57cec5SDimitry Andric error(Twine("cannot find version script ") + arg->getValue()); 14900b57cec5SDimitry Andric } 14910b57cec5SDimitry Andric } 14920b57cec5SDimitry Andric 14930b57cec5SDimitry Andric // Some Config members do not directly correspond to any particular 14940b57cec5SDimitry Andric // command line options, but computed based on other Config values. 14950b57cec5SDimitry Andric // This function initialize such members. See Config.h for the details 14960b57cec5SDimitry Andric // of these values. 14970b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args) { 14980b57cec5SDimitry Andric ELFKind k = config->ekind; 14990b57cec5SDimitry Andric uint16_t m = config->emachine; 15000b57cec5SDimitry Andric 15010b57cec5SDimitry Andric config->copyRelocs = (config->relocatable || config->emitRelocs); 15020b57cec5SDimitry Andric config->is64 = (k == ELF64LEKind || k == ELF64BEKind); 15030b57cec5SDimitry Andric config->isLE = (k == ELF32LEKind || k == ELF64LEKind); 15040b57cec5SDimitry Andric config->endianness = config->isLE ? endianness::little : endianness::big; 15050b57cec5SDimitry Andric config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS); 15060b57cec5SDimitry Andric config->isPic = config->pie || config->shared; 15070b57cec5SDimitry Andric config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic); 15080b57cec5SDimitry Andric config->wordsize = config->is64 ? 8 : 4; 15090b57cec5SDimitry Andric 15100b57cec5SDimitry Andric // ELF defines two different ways to store relocation addends as shown below: 15110b57cec5SDimitry Andric // 15125ffd83dbSDimitry Andric // Rel: Addends are stored to the location where relocations are applied. It 15135ffd83dbSDimitry Andric // cannot pack the full range of addend values for all relocation types, but 15145ffd83dbSDimitry Andric // this only affects relocation types that we don't support emitting as 15155ffd83dbSDimitry Andric // dynamic relocations (see getDynRel). 15160b57cec5SDimitry Andric // Rela: Addends are stored as part of relocation entry. 15170b57cec5SDimitry Andric // 15180b57cec5SDimitry Andric // In other words, Rela makes it easy to read addends at the price of extra 15195ffd83dbSDimitry Andric // 4 or 8 byte for each relocation entry. 15200b57cec5SDimitry Andric // 15215ffd83dbSDimitry Andric // We pick the format for dynamic relocations according to the psABI for each 15225ffd83dbSDimitry Andric // processor, but a contrary choice can be made if the dynamic loader 15235ffd83dbSDimitry Andric // supports. 15245ffd83dbSDimitry Andric config->isRela = getIsRela(args); 15250b57cec5SDimitry Andric 15260b57cec5SDimitry Andric // If the output uses REL relocations we must store the dynamic relocation 15270b57cec5SDimitry Andric // addends to the output sections. We also store addends for RELA relocations 15280b57cec5SDimitry Andric // if --apply-dynamic-relocs is used. 15290b57cec5SDimitry Andric // We default to not writing the addends when using RELA relocations since 15300b57cec5SDimitry Andric // any standard conforming tool can find it in r_addend. 15310b57cec5SDimitry Andric config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs, 15320b57cec5SDimitry Andric OPT_no_apply_dynamic_relocs, false) || 15330b57cec5SDimitry Andric !config->isRela; 1534fe6060f1SDimitry Andric // Validation of dynamic relocation addends is on by default for assertions 1535fe6060f1SDimitry Andric // builds (for supported targets) and disabled otherwise. Ideally we would 1536fe6060f1SDimitry Andric // enable the debug checks for all targets, but currently not all targets 1537fe6060f1SDimitry Andric // have support for reading Elf_Rel addends, so we only enable for a subset. 1538fe6060f1SDimitry Andric #ifndef NDEBUG 1539fe6060f1SDimitry Andric bool checkDynamicRelocsDefault = m == EM_ARM || m == EM_386 || m == EM_MIPS || 1540fe6060f1SDimitry Andric m == EM_X86_64 || m == EM_RISCV; 1541fe6060f1SDimitry Andric #else 1542fe6060f1SDimitry Andric bool checkDynamicRelocsDefault = false; 1543fe6060f1SDimitry Andric #endif 1544fe6060f1SDimitry Andric config->checkDynamicRelocs = 1545fe6060f1SDimitry Andric args.hasFlag(OPT_check_dynamic_relocations, 1546fe6060f1SDimitry Andric OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault); 15470b57cec5SDimitry Andric config->tocOptimize = 15480b57cec5SDimitry Andric args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64); 1549e8d8bef9SDimitry Andric config->pcRelOptimize = 1550e8d8bef9SDimitry Andric args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64); 15510b57cec5SDimitry Andric } 15520b57cec5SDimitry Andric 15530b57cec5SDimitry Andric static bool isFormatBinary(StringRef s) { 15540b57cec5SDimitry Andric if (s == "binary") 15550b57cec5SDimitry Andric return true; 15560b57cec5SDimitry Andric if (s == "elf" || s == "default") 15570b57cec5SDimitry Andric return false; 1558349cc55cSDimitry Andric error("unknown --format value: " + s + 15590b57cec5SDimitry Andric " (supported formats: elf, default, binary)"); 15600b57cec5SDimitry Andric return false; 15610b57cec5SDimitry Andric } 15620b57cec5SDimitry Andric 15630b57cec5SDimitry Andric void LinkerDriver::createFiles(opt::InputArgList &args) { 1564e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Load input files"); 15650b57cec5SDimitry Andric // For --{push,pop}-state. 15660b57cec5SDimitry Andric std::vector<std::tuple<bool, bool, bool>> stack; 15670b57cec5SDimitry Andric 15680b57cec5SDimitry Andric // Iterate over argv to process input files and positional arguments. 1569e8d8bef9SDimitry Andric InputFile::isInGroup = false; 157081ad6265SDimitry Andric bool hasInput = false; 15710b57cec5SDimitry Andric for (auto *arg : args) { 15720b57cec5SDimitry Andric switch (arg->getOption().getID()) { 15730b57cec5SDimitry Andric case OPT_library: 15740b57cec5SDimitry Andric addLibrary(arg->getValue()); 157581ad6265SDimitry Andric hasInput = true; 15760b57cec5SDimitry Andric break; 15770b57cec5SDimitry Andric case OPT_INPUT: 15780b57cec5SDimitry Andric addFile(arg->getValue(), /*withLOption=*/false); 157981ad6265SDimitry Andric hasInput = true; 15800b57cec5SDimitry Andric break; 15810b57cec5SDimitry Andric case OPT_defsym: { 15820b57cec5SDimitry Andric StringRef from; 15830b57cec5SDimitry Andric StringRef to; 15840b57cec5SDimitry Andric std::tie(from, to) = StringRef(arg->getValue()).split('='); 15850b57cec5SDimitry Andric if (from.empty() || to.empty()) 1586349cc55cSDimitry Andric error("--defsym: syntax error: " + StringRef(arg->getValue())); 15870b57cec5SDimitry Andric else 1588349cc55cSDimitry Andric readDefsym(from, MemoryBufferRef(to, "--defsym")); 15890b57cec5SDimitry Andric break; 15900b57cec5SDimitry Andric } 15910b57cec5SDimitry Andric case OPT_script: 15920b57cec5SDimitry Andric if (Optional<std::string> path = searchScript(arg->getValue())) { 15930b57cec5SDimitry Andric if (Optional<MemoryBufferRef> mb = readFile(*path)) 15940b57cec5SDimitry Andric readLinkerScript(*mb); 15950b57cec5SDimitry Andric break; 15960b57cec5SDimitry Andric } 15970b57cec5SDimitry Andric error(Twine("cannot find linker script ") + arg->getValue()); 15980b57cec5SDimitry Andric break; 15990b57cec5SDimitry Andric case OPT_as_needed: 16000b57cec5SDimitry Andric config->asNeeded = true; 16010b57cec5SDimitry Andric break; 16020b57cec5SDimitry Andric case OPT_format: 16030b57cec5SDimitry Andric config->formatBinary = isFormatBinary(arg->getValue()); 16040b57cec5SDimitry Andric break; 16050b57cec5SDimitry Andric case OPT_no_as_needed: 16060b57cec5SDimitry Andric config->asNeeded = false; 16070b57cec5SDimitry Andric break; 16080b57cec5SDimitry Andric case OPT_Bstatic: 16090b57cec5SDimitry Andric case OPT_omagic: 16100b57cec5SDimitry Andric case OPT_nmagic: 16110b57cec5SDimitry Andric config->isStatic = true; 16120b57cec5SDimitry Andric break; 16130b57cec5SDimitry Andric case OPT_Bdynamic: 16140b57cec5SDimitry Andric config->isStatic = false; 16150b57cec5SDimitry Andric break; 16160b57cec5SDimitry Andric case OPT_whole_archive: 16170b57cec5SDimitry Andric inWholeArchive = true; 16180b57cec5SDimitry Andric break; 16190b57cec5SDimitry Andric case OPT_no_whole_archive: 16200b57cec5SDimitry Andric inWholeArchive = false; 16210b57cec5SDimitry Andric break; 16220b57cec5SDimitry Andric case OPT_just_symbols: 16230b57cec5SDimitry Andric if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) { 1624*fcaf7f86SDimitry Andric files.push_back(createObjFile(*mb)); 16250b57cec5SDimitry Andric files.back()->justSymbols = true; 16260b57cec5SDimitry Andric } 16270b57cec5SDimitry Andric break; 16280b57cec5SDimitry Andric case OPT_start_group: 16290b57cec5SDimitry Andric if (InputFile::isInGroup) 16300b57cec5SDimitry Andric error("nested --start-group"); 16310b57cec5SDimitry Andric InputFile::isInGroup = true; 16320b57cec5SDimitry Andric break; 16330b57cec5SDimitry Andric case OPT_end_group: 16340b57cec5SDimitry Andric if (!InputFile::isInGroup) 16350b57cec5SDimitry Andric error("stray --end-group"); 16360b57cec5SDimitry Andric InputFile::isInGroup = false; 16370b57cec5SDimitry Andric ++InputFile::nextGroupId; 16380b57cec5SDimitry Andric break; 16390b57cec5SDimitry Andric case OPT_start_lib: 16400b57cec5SDimitry Andric if (inLib) 16410b57cec5SDimitry Andric error("nested --start-lib"); 16420b57cec5SDimitry Andric if (InputFile::isInGroup) 16430b57cec5SDimitry Andric error("may not nest --start-lib in --start-group"); 16440b57cec5SDimitry Andric inLib = true; 16450b57cec5SDimitry Andric InputFile::isInGroup = true; 16460b57cec5SDimitry Andric break; 16470b57cec5SDimitry Andric case OPT_end_lib: 16480b57cec5SDimitry Andric if (!inLib) 16490b57cec5SDimitry Andric error("stray --end-lib"); 16500b57cec5SDimitry Andric inLib = false; 16510b57cec5SDimitry Andric InputFile::isInGroup = false; 16520b57cec5SDimitry Andric ++InputFile::nextGroupId; 16530b57cec5SDimitry Andric break; 16540b57cec5SDimitry Andric case OPT_push_state: 16550b57cec5SDimitry Andric stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive); 16560b57cec5SDimitry Andric break; 16570b57cec5SDimitry Andric case OPT_pop_state: 16580b57cec5SDimitry Andric if (stack.empty()) { 16590b57cec5SDimitry Andric error("unbalanced --push-state/--pop-state"); 16600b57cec5SDimitry Andric break; 16610b57cec5SDimitry Andric } 16620b57cec5SDimitry Andric std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back(); 16630b57cec5SDimitry Andric stack.pop_back(); 16640b57cec5SDimitry Andric break; 16650b57cec5SDimitry Andric } 16660b57cec5SDimitry Andric } 16670b57cec5SDimitry Andric 166881ad6265SDimitry Andric if (files.empty() && !hasInput && errorCount() == 0) 16690b57cec5SDimitry Andric error("no input files"); 16700b57cec5SDimitry Andric } 16710b57cec5SDimitry Andric 16720b57cec5SDimitry Andric // If -m <machine_type> was not given, infer it from object files. 16730b57cec5SDimitry Andric void LinkerDriver::inferMachineType() { 16740b57cec5SDimitry Andric if (config->ekind != ELFNoneKind) 16750b57cec5SDimitry Andric return; 16760b57cec5SDimitry Andric 16770b57cec5SDimitry Andric for (InputFile *f : files) { 16780b57cec5SDimitry Andric if (f->ekind == ELFNoneKind) 16790b57cec5SDimitry Andric continue; 16800b57cec5SDimitry Andric config->ekind = f->ekind; 16810b57cec5SDimitry Andric config->emachine = f->emachine; 16820b57cec5SDimitry Andric config->osabi = f->osabi; 16830b57cec5SDimitry Andric config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f); 16840b57cec5SDimitry Andric return; 16850b57cec5SDimitry Andric } 16860b57cec5SDimitry Andric error("target emulation unknown: -m or at least one .o file required"); 16870b57cec5SDimitry Andric } 16880b57cec5SDimitry Andric 16890b57cec5SDimitry Andric // Parse -z max-page-size=<value>. The default value is defined by 16900b57cec5SDimitry Andric // each target. 16910b57cec5SDimitry Andric static uint64_t getMaxPageSize(opt::InputArgList &args) { 16920b57cec5SDimitry Andric uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size", 16930b57cec5SDimitry Andric target->defaultMaxPageSize); 16940b57cec5SDimitry Andric if (!isPowerOf2_64(val)) 16950b57cec5SDimitry Andric error("max-page-size: value isn't a power of 2"); 16960b57cec5SDimitry Andric if (config->nmagic || config->omagic) { 16970b57cec5SDimitry Andric if (val != target->defaultMaxPageSize) 16980b57cec5SDimitry Andric warn("-z max-page-size set, but paging disabled by omagic or nmagic"); 16990b57cec5SDimitry Andric return 1; 17000b57cec5SDimitry Andric } 17010b57cec5SDimitry Andric return val; 17020b57cec5SDimitry Andric } 17030b57cec5SDimitry Andric 17040b57cec5SDimitry Andric // Parse -z common-page-size=<value>. The default value is defined by 17050b57cec5SDimitry Andric // each target. 17060b57cec5SDimitry Andric static uint64_t getCommonPageSize(opt::InputArgList &args) { 17070b57cec5SDimitry Andric uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size", 17080b57cec5SDimitry Andric target->defaultCommonPageSize); 17090b57cec5SDimitry Andric if (!isPowerOf2_64(val)) 17100b57cec5SDimitry Andric error("common-page-size: value isn't a power of 2"); 17110b57cec5SDimitry Andric if (config->nmagic || config->omagic) { 17120b57cec5SDimitry Andric if (val != target->defaultCommonPageSize) 17130b57cec5SDimitry Andric warn("-z common-page-size set, but paging disabled by omagic or nmagic"); 17140b57cec5SDimitry Andric return 1; 17150b57cec5SDimitry Andric } 17160b57cec5SDimitry Andric // commonPageSize can't be larger than maxPageSize. 17170b57cec5SDimitry Andric if (val > config->maxPageSize) 17180b57cec5SDimitry Andric val = config->maxPageSize; 17190b57cec5SDimitry Andric return val; 17200b57cec5SDimitry Andric } 17210b57cec5SDimitry Andric 1722349cc55cSDimitry Andric // Parses --image-base option. 17230b57cec5SDimitry Andric static Optional<uint64_t> getImageBase(opt::InputArgList &args) { 17240b57cec5SDimitry Andric // Because we are using "Config->maxPageSize" here, this function has to be 17250b57cec5SDimitry Andric // called after the variable is initialized. 17260b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_image_base); 17270b57cec5SDimitry Andric if (!arg) 17280b57cec5SDimitry Andric return None; 17290b57cec5SDimitry Andric 17300b57cec5SDimitry Andric StringRef s = arg->getValue(); 17310b57cec5SDimitry Andric uint64_t v; 17320b57cec5SDimitry Andric if (!to_integer(s, v)) { 1733349cc55cSDimitry Andric error("--image-base: number expected, but got " + s); 17340b57cec5SDimitry Andric return 0; 17350b57cec5SDimitry Andric } 17360b57cec5SDimitry Andric if ((v % config->maxPageSize) != 0) 1737349cc55cSDimitry Andric warn("--image-base: address isn't multiple of page size: " + s); 17380b57cec5SDimitry Andric return v; 17390b57cec5SDimitry Andric } 17400b57cec5SDimitry Andric 17410b57cec5SDimitry Andric // Parses `--exclude-libs=lib,lib,...`. 17420b57cec5SDimitry Andric // The library names may be delimited by commas or colons. 17430b57cec5SDimitry Andric static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) { 17440b57cec5SDimitry Andric DenseSet<StringRef> ret; 17450b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_exclude_libs)) { 17460b57cec5SDimitry Andric StringRef s = arg->getValue(); 17470b57cec5SDimitry Andric for (;;) { 17480b57cec5SDimitry Andric size_t pos = s.find_first_of(",:"); 17490b57cec5SDimitry Andric if (pos == StringRef::npos) 17500b57cec5SDimitry Andric break; 17510b57cec5SDimitry Andric ret.insert(s.substr(0, pos)); 17520b57cec5SDimitry Andric s = s.substr(pos + 1); 17530b57cec5SDimitry Andric } 17540b57cec5SDimitry Andric ret.insert(s); 17550b57cec5SDimitry Andric } 17560b57cec5SDimitry Andric return ret; 17570b57cec5SDimitry Andric } 17580b57cec5SDimitry Andric 1759349cc55cSDimitry Andric // Handles the --exclude-libs option. If a static library file is specified 1760349cc55cSDimitry Andric // by the --exclude-libs option, all public symbols from the archive become 17610b57cec5SDimitry Andric // private unless otherwise specified by version scripts or something. 17620b57cec5SDimitry Andric // A special library name "ALL" means all archive files. 17630b57cec5SDimitry Andric // 17640b57cec5SDimitry Andric // This is not a popular option, but some programs such as bionic libc use it. 17650b57cec5SDimitry Andric static void excludeLibs(opt::InputArgList &args) { 17660b57cec5SDimitry Andric DenseSet<StringRef> libs = getExcludeLibs(args); 17670b57cec5SDimitry Andric bool all = libs.count("ALL"); 17680b57cec5SDimitry Andric 17690b57cec5SDimitry Andric auto visit = [&](InputFile *file) { 177081ad6265SDimitry Andric if (file->archiveName.empty() || 177181ad6265SDimitry Andric !(all || libs.count(path::filename(file->archiveName)))) 177281ad6265SDimitry Andric return; 177381ad6265SDimitry Andric ArrayRef<Symbol *> symbols = file->getSymbols(); 177481ad6265SDimitry Andric if (isa<ELFFileBase>(file)) 177581ad6265SDimitry Andric symbols = cast<ELFFileBase>(file)->getGlobalSymbols(); 177681ad6265SDimitry Andric for (Symbol *sym : symbols) 177781ad6265SDimitry Andric if (!sym->isUndefined() && sym->file == file) 17780b57cec5SDimitry Andric sym->versionId = VER_NDX_LOCAL; 17790b57cec5SDimitry Andric }; 17800b57cec5SDimitry Andric 178181ad6265SDimitry Andric for (ELFFileBase *file : ctx->objectFiles) 17820b57cec5SDimitry Andric visit(file); 17830b57cec5SDimitry Andric 178481ad6265SDimitry Andric for (BitcodeFile *file : ctx->bitcodeFiles) 17850b57cec5SDimitry Andric visit(file); 17860b57cec5SDimitry Andric } 17870b57cec5SDimitry Andric 17885ffd83dbSDimitry Andric // Force Sym to be entered in the output. 1789349cc55cSDimitry Andric static void handleUndefined(Symbol *sym, const char *option) { 17900b57cec5SDimitry Andric // Since a symbol may not be used inside the program, LTO may 17910b57cec5SDimitry Andric // eliminate it. Mark the symbol as "used" to prevent it. 17920b57cec5SDimitry Andric sym->isUsedInRegularObj = true; 17930b57cec5SDimitry Andric 1794349cc55cSDimitry Andric if (!sym->isLazy()) 1795349cc55cSDimitry Andric return; 17964824e7fdSDimitry Andric sym->extract(); 1797349cc55cSDimitry Andric if (!config->whyExtract.empty()) 179881ad6265SDimitry Andric ctx->whyExtractRecords.emplace_back(option, sym->file, *sym); 17990b57cec5SDimitry Andric } 18000b57cec5SDimitry Andric 1801480093f4SDimitry Andric // As an extension to GNU linkers, lld supports a variant of `-u` 18020b57cec5SDimitry Andric // which accepts wildcard patterns. All symbols that match a given 18030b57cec5SDimitry Andric // pattern are handled as if they were given by `-u`. 18040b57cec5SDimitry Andric static void handleUndefinedGlob(StringRef arg) { 18050b57cec5SDimitry Andric Expected<GlobPattern> pat = GlobPattern::create(arg); 18060b57cec5SDimitry Andric if (!pat) { 18070b57cec5SDimitry Andric error("--undefined-glob: " + toString(pat.takeError())); 18080b57cec5SDimitry Andric return; 18090b57cec5SDimitry Andric } 18100b57cec5SDimitry Andric 18114824e7fdSDimitry Andric // Calling sym->extract() in the loop is not safe because it may add new 18124824e7fdSDimitry Andric // symbols to the symbol table, invalidating the current iterator. 18131fd87a68SDimitry Andric SmallVector<Symbol *, 0> syms; 18144824e7fdSDimitry Andric for (Symbol *sym : symtab->symbols()) 181504eeddc0SDimitry Andric if (!sym->isPlaceholder() && pat->match(sym->getName())) 18160b57cec5SDimitry Andric syms.push_back(sym); 18170b57cec5SDimitry Andric 18180b57cec5SDimitry Andric for (Symbol *sym : syms) 1819349cc55cSDimitry Andric handleUndefined(sym, "--undefined-glob"); 18200b57cec5SDimitry Andric } 18210b57cec5SDimitry Andric 18220b57cec5SDimitry Andric static void handleLibcall(StringRef name) { 18230b57cec5SDimitry Andric Symbol *sym = symtab->find(name); 18240b57cec5SDimitry Andric if (!sym || !sym->isLazy()) 18250b57cec5SDimitry Andric return; 18260b57cec5SDimitry Andric 18270b57cec5SDimitry Andric MemoryBufferRef mb; 182881ad6265SDimitry Andric mb = cast<LazyObject>(sym)->file->mb; 18290b57cec5SDimitry Andric 18300b57cec5SDimitry Andric if (isBitcode(mb)) 18314824e7fdSDimitry Andric sym->extract(); 18320b57cec5SDimitry Andric } 18330b57cec5SDimitry Andric 183481ad6265SDimitry Andric static void writeArchiveStats() { 183581ad6265SDimitry Andric if (config->printArchiveStats.empty()) 183681ad6265SDimitry Andric return; 183781ad6265SDimitry Andric 183881ad6265SDimitry Andric std::error_code ec; 183981ad6265SDimitry Andric raw_fd_ostream os(config->printArchiveStats, ec, sys::fs::OF_None); 184081ad6265SDimitry Andric if (ec) { 184181ad6265SDimitry Andric error("--print-archive-stats=: cannot open " + config->printArchiveStats + 184281ad6265SDimitry Andric ": " + ec.message()); 184381ad6265SDimitry Andric return; 184481ad6265SDimitry Andric } 184581ad6265SDimitry Andric 184681ad6265SDimitry Andric os << "members\textracted\tarchive\n"; 184781ad6265SDimitry Andric 184881ad6265SDimitry Andric SmallVector<StringRef, 0> archives; 184981ad6265SDimitry Andric DenseMap<CachedHashStringRef, unsigned> all, extracted; 185081ad6265SDimitry Andric for (ELFFileBase *file : ctx->objectFiles) 185181ad6265SDimitry Andric if (file->archiveName.size()) 185281ad6265SDimitry Andric ++extracted[CachedHashStringRef(file->archiveName)]; 185381ad6265SDimitry Andric for (BitcodeFile *file : ctx->bitcodeFiles) 185481ad6265SDimitry Andric if (file->archiveName.size()) 185581ad6265SDimitry Andric ++extracted[CachedHashStringRef(file->archiveName)]; 185681ad6265SDimitry Andric for (std::pair<StringRef, unsigned> f : driver->archiveFiles) { 185781ad6265SDimitry Andric unsigned &v = extracted[CachedHashString(f.first)]; 185881ad6265SDimitry Andric os << f.second << '\t' << v << '\t' << f.first << '\n'; 185981ad6265SDimitry Andric // If the archive occurs multiple times, other instances have a count of 0. 186081ad6265SDimitry Andric v = 0; 186181ad6265SDimitry Andric } 186281ad6265SDimitry Andric } 186381ad6265SDimitry Andric 186481ad6265SDimitry Andric static void writeWhyExtract() { 186581ad6265SDimitry Andric if (config->whyExtract.empty()) 186681ad6265SDimitry Andric return; 186781ad6265SDimitry Andric 186881ad6265SDimitry Andric std::error_code ec; 186981ad6265SDimitry Andric raw_fd_ostream os(config->whyExtract, ec, sys::fs::OF_None); 187081ad6265SDimitry Andric if (ec) { 187181ad6265SDimitry Andric error("cannot open --why-extract= file " + config->whyExtract + ": " + 187281ad6265SDimitry Andric ec.message()); 187381ad6265SDimitry Andric return; 187481ad6265SDimitry Andric } 187581ad6265SDimitry Andric 187681ad6265SDimitry Andric os << "reference\textracted\tsymbol\n"; 187781ad6265SDimitry Andric for (auto &entry : ctx->whyExtractRecords) { 187881ad6265SDimitry Andric os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t' 187981ad6265SDimitry Andric << toString(std::get<2>(entry)) << '\n'; 188081ad6265SDimitry Andric } 188181ad6265SDimitry Andric } 188281ad6265SDimitry Andric 188381ad6265SDimitry Andric static void reportBackrefs() { 188481ad6265SDimitry Andric for (auto &ref : ctx->backwardReferences) { 188581ad6265SDimitry Andric const Symbol &sym = *ref.first; 188681ad6265SDimitry Andric std::string to = toString(ref.second.second); 188781ad6265SDimitry Andric // Some libraries have known problems and can cause noise. Filter them out 188881ad6265SDimitry Andric // with --warn-backrefs-exclude=. The value may look like (for --start-lib) 188981ad6265SDimitry Andric // *.o or (archive member) *.a(*.o). 189081ad6265SDimitry Andric bool exclude = false; 189181ad6265SDimitry Andric for (const llvm::GlobPattern &pat : config->warnBackrefsExclude) 189281ad6265SDimitry Andric if (pat.match(to)) { 189381ad6265SDimitry Andric exclude = true; 189481ad6265SDimitry Andric break; 189581ad6265SDimitry Andric } 189681ad6265SDimitry Andric if (!exclude) 189781ad6265SDimitry Andric warn("backward reference detected: " + sym.getName() + " in " + 189881ad6265SDimitry Andric toString(ref.second.first) + " refers to " + to); 189981ad6265SDimitry Andric } 190081ad6265SDimitry Andric } 190181ad6265SDimitry Andric 1902e8d8bef9SDimitry Andric // Handle --dependency-file=<path>. If that option is given, lld creates a 1903e8d8bef9SDimitry Andric // file at a given path with the following contents: 1904e8d8bef9SDimitry Andric // 1905e8d8bef9SDimitry Andric // <output-file>: <input-file> ... 1906e8d8bef9SDimitry Andric // 1907e8d8bef9SDimitry Andric // <input-file>: 1908e8d8bef9SDimitry Andric // 1909e8d8bef9SDimitry Andric // where <output-file> is a pathname of an output file and <input-file> 1910e8d8bef9SDimitry Andric // ... is a list of pathnames of all input files. `make` command can read a 1911e8d8bef9SDimitry Andric // file in the above format and interpret it as a dependency info. We write 1912e8d8bef9SDimitry Andric // phony targets for every <input-file> to avoid an error when that file is 1913e8d8bef9SDimitry Andric // removed. 1914e8d8bef9SDimitry Andric // 1915e8d8bef9SDimitry Andric // This option is useful if you want to make your final executable to depend 1916e8d8bef9SDimitry Andric // on all input files including system libraries. Here is why. 1917e8d8bef9SDimitry Andric // 1918e8d8bef9SDimitry Andric // When you write a Makefile, you usually write it so that the final 1919e8d8bef9SDimitry Andric // executable depends on all user-generated object files. Normally, you 1920e8d8bef9SDimitry Andric // don't make your executable to depend on system libraries (such as libc) 1921e8d8bef9SDimitry Andric // because you don't know the exact paths of libraries, even though system 1922e8d8bef9SDimitry Andric // libraries that are linked to your executable statically are technically a 1923e8d8bef9SDimitry Andric // part of your program. By using --dependency-file option, you can make 1924e8d8bef9SDimitry Andric // lld to dump dependency info so that you can maintain exact dependencies 1925e8d8bef9SDimitry Andric // easily. 1926e8d8bef9SDimitry Andric static void writeDependencyFile() { 1927e8d8bef9SDimitry Andric std::error_code ec; 1928fe6060f1SDimitry Andric raw_fd_ostream os(config->dependencyFile, ec, sys::fs::OF_None); 1929e8d8bef9SDimitry Andric if (ec) { 1930e8d8bef9SDimitry Andric error("cannot open " + config->dependencyFile + ": " + ec.message()); 1931e8d8bef9SDimitry Andric return; 1932e8d8bef9SDimitry Andric } 1933e8d8bef9SDimitry Andric 1934e8d8bef9SDimitry Andric // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja: 1935e8d8bef9SDimitry Andric // * A space is escaped by a backslash which itself must be escaped. 1936e8d8bef9SDimitry Andric // * A hash sign is escaped by a single backslash. 1937e8d8bef9SDimitry Andric // * $ is escapes as $$. 1938e8d8bef9SDimitry Andric auto printFilename = [](raw_fd_ostream &os, StringRef filename) { 1939e8d8bef9SDimitry Andric llvm::SmallString<256> nativePath; 1940e8d8bef9SDimitry Andric llvm::sys::path::native(filename.str(), nativePath); 1941e8d8bef9SDimitry Andric llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true); 1942e8d8bef9SDimitry Andric for (unsigned i = 0, e = nativePath.size(); i != e; ++i) { 1943e8d8bef9SDimitry Andric if (nativePath[i] == '#') { 1944e8d8bef9SDimitry Andric os << '\\'; 1945e8d8bef9SDimitry Andric } else if (nativePath[i] == ' ') { 1946e8d8bef9SDimitry Andric os << '\\'; 1947e8d8bef9SDimitry Andric unsigned j = i; 1948e8d8bef9SDimitry Andric while (j > 0 && nativePath[--j] == '\\') 1949e8d8bef9SDimitry Andric os << '\\'; 1950e8d8bef9SDimitry Andric } else if (nativePath[i] == '$') { 1951e8d8bef9SDimitry Andric os << '$'; 1952e8d8bef9SDimitry Andric } 1953e8d8bef9SDimitry Andric os << nativePath[i]; 1954e8d8bef9SDimitry Andric } 1955e8d8bef9SDimitry Andric }; 1956e8d8bef9SDimitry Andric 1957e8d8bef9SDimitry Andric os << config->outputFile << ":"; 1958e8d8bef9SDimitry Andric for (StringRef path : config->dependencyFiles) { 1959e8d8bef9SDimitry Andric os << " \\\n "; 1960e8d8bef9SDimitry Andric printFilename(os, path); 1961e8d8bef9SDimitry Andric } 1962e8d8bef9SDimitry Andric os << "\n"; 1963e8d8bef9SDimitry Andric 1964e8d8bef9SDimitry Andric for (StringRef path : config->dependencyFiles) { 1965e8d8bef9SDimitry Andric os << "\n"; 1966e8d8bef9SDimitry Andric printFilename(os, path); 1967e8d8bef9SDimitry Andric os << ":\n"; 1968e8d8bef9SDimitry Andric } 1969e8d8bef9SDimitry Andric } 1970e8d8bef9SDimitry Andric 19710b57cec5SDimitry Andric // Replaces common symbols with defined symbols reside in .bss sections. 19720b57cec5SDimitry Andric // This function is called after all symbol names are resolved. As a 19730b57cec5SDimitry Andric // result, the passes after the symbol resolution won't see any 19740b57cec5SDimitry Andric // symbols of type CommonSymbol. 19750b57cec5SDimitry Andric static void replaceCommonSymbols() { 1976e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Replace common symbols"); 197781ad6265SDimitry Andric for (ELFFileBase *file : ctx->objectFiles) { 19780eae32dcSDimitry Andric if (!file->hasCommonSyms) 19790eae32dcSDimitry Andric continue; 19800eae32dcSDimitry Andric for (Symbol *sym : file->getGlobalSymbols()) { 19810b57cec5SDimitry Andric auto *s = dyn_cast<CommonSymbol>(sym); 19820b57cec5SDimitry Andric if (!s) 1983480093f4SDimitry Andric continue; 19840b57cec5SDimitry Andric 19850b57cec5SDimitry Andric auto *bss = make<BssSection>("COMMON", s->size, s->alignment); 19860b57cec5SDimitry Andric bss->file = s->file; 19870b57cec5SDimitry Andric inputSections.push_back(bss); 198881ad6265SDimitry Andric s->replace(Defined{s->file, StringRef(), s->binding, s->stOther, s->type, 19890b57cec5SDimitry Andric /*value=*/0, s->size, bss}); 1990480093f4SDimitry Andric } 19910b57cec5SDimitry Andric } 19920eae32dcSDimitry Andric } 19930b57cec5SDimitry Andric 199481ad6265SDimitry Andric // If all references to a DSO happen to be weak, the DSO is not added to 199581ad6265SDimitry Andric // DT_NEEDED. If that happens, replace ShardSymbol with Undefined to avoid 199681ad6265SDimitry Andric // dangling references to an unneeded DSO. Use a weak binding to avoid 199781ad6265SDimitry Andric // --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols. 199881ad6265SDimitry Andric static void demoteSharedAndLazySymbols() { 199981ad6265SDimitry Andric llvm::TimeTraceScope timeScope("Demote shared and lazy symbols"); 2000480093f4SDimitry Andric for (Symbol *sym : symtab->symbols()) { 20010b57cec5SDimitry Andric auto *s = dyn_cast<SharedSymbol>(sym); 200281ad6265SDimitry Andric if (!(s && !cast<SharedFile>(s->file)->isNeeded) && !sym->isLazy()) 2003480093f4SDimitry Andric continue; 20040b57cec5SDimitry Andric 2005349cc55cSDimitry Andric bool used = sym->used; 200681ad6265SDimitry Andric uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK); 2007349cc55cSDimitry Andric sym->replace( 200881ad6265SDimitry Andric Undefined{nullptr, sym->getName(), binding, sym->stOther, sym->type}); 2009349cc55cSDimitry Andric sym->used = used; 2010349cc55cSDimitry Andric sym->versionId = VER_NDX_GLOBAL; 2011480093f4SDimitry Andric } 20120b57cec5SDimitry Andric } 20130b57cec5SDimitry Andric 20140b57cec5SDimitry Andric // The section referred to by `s` is considered address-significant. Set the 20150b57cec5SDimitry Andric // keepUnique flag on the section if appropriate. 20160b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 20170b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 20180b57cec5SDimitry Andric if (d->section) 20190b57cec5SDimitry Andric // We don't need to keep text sections unique under --icf=all even if they 20200b57cec5SDimitry Andric // are address-significant. 20210b57cec5SDimitry Andric if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR)) 20220b57cec5SDimitry Andric d->section->keepUnique = true; 20230b57cec5SDimitry Andric } 20240b57cec5SDimitry Andric 20250b57cec5SDimitry Andric // Record sections that define symbols mentioned in --keep-unique <symbol> 20260b57cec5SDimitry Andric // and symbols referred to by address-significance tables. These sections are 20270b57cec5SDimitry Andric // ineligible for ICF. 20280b57cec5SDimitry Andric template <class ELFT> 20290b57cec5SDimitry Andric static void findKeepUniqueSections(opt::InputArgList &args) { 20300b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_keep_unique)) { 20310b57cec5SDimitry Andric StringRef name = arg->getValue(); 20320b57cec5SDimitry Andric auto *d = dyn_cast_or_null<Defined>(symtab->find(name)); 20330b57cec5SDimitry Andric if (!d || !d->section) { 20340b57cec5SDimitry Andric warn("could not find symbol " + name + " to keep unique"); 20350b57cec5SDimitry Andric continue; 20360b57cec5SDimitry Andric } 20370b57cec5SDimitry Andric d->section->keepUnique = true; 20380b57cec5SDimitry Andric } 20390b57cec5SDimitry Andric 20400b57cec5SDimitry Andric // --icf=all --ignore-data-address-equality means that we can ignore 20410b57cec5SDimitry Andric // the dynsym and address-significance tables entirely. 20420b57cec5SDimitry Andric if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality) 20430b57cec5SDimitry Andric return; 20440b57cec5SDimitry Andric 20450b57cec5SDimitry Andric // Symbols in the dynsym could be address-significant in other executables 20460b57cec5SDimitry Andric // or DSOs, so we conservatively mark them as address-significant. 2047480093f4SDimitry Andric for (Symbol *sym : symtab->symbols()) 20480b57cec5SDimitry Andric if (sym->includeInDynsym()) 20490b57cec5SDimitry Andric markAddrsig(sym); 20500b57cec5SDimitry Andric 20510b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 20520b57cec5SDimitry Andric // referenced symbol as address-significant. 205381ad6265SDimitry Andric for (InputFile *f : ctx->objectFiles) { 20540b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(f); 20550b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 20560b57cec5SDimitry Andric if (obj->addrsigSec) { 20570b57cec5SDimitry Andric ArrayRef<uint8_t> contents = 2058e8d8bef9SDimitry Andric check(obj->getObj().getSectionContents(*obj->addrsigSec)); 20590b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 20600b57cec5SDimitry Andric while (cur != contents.end()) { 20610b57cec5SDimitry Andric unsigned size; 20620b57cec5SDimitry Andric const char *err; 20630b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 20640b57cec5SDimitry Andric if (err) 20650b57cec5SDimitry Andric fatal(toString(f) + ": could not decode addrsig section: " + err); 20660b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 20670b57cec5SDimitry Andric cur += size; 20680b57cec5SDimitry Andric } 20690b57cec5SDimitry Andric } else { 20700b57cec5SDimitry Andric // If an object file does not have an address-significance table, 20710b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 20720b57cec5SDimitry Andric for (Symbol *s : syms) 20730b57cec5SDimitry Andric markAddrsig(s); 20740b57cec5SDimitry Andric } 20750b57cec5SDimitry Andric } 20760b57cec5SDimitry Andric } 20770b57cec5SDimitry Andric 20780b57cec5SDimitry Andric // This function reads a symbol partition specification section. These sections 20790b57cec5SDimitry Andric // are used to control which partition a symbol is allocated to. See 20800b57cec5SDimitry Andric // https://lld.llvm.org/Partitions.html for more details on partitions. 20810b57cec5SDimitry Andric template <typename ELFT> 20820b57cec5SDimitry Andric static void readSymbolPartitionSection(InputSectionBase *s) { 20830b57cec5SDimitry Andric // Read the relocation that refers to the partition's entry point symbol. 20840b57cec5SDimitry Andric Symbol *sym; 2085349cc55cSDimitry Andric const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>(); 2086349cc55cSDimitry Andric if (rels.areRelocsRel()) 2087349cc55cSDimitry Andric sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]); 20880b57cec5SDimitry Andric else 2089349cc55cSDimitry Andric sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]); 20900b57cec5SDimitry Andric if (!isa<Defined>(sym) || !sym->includeInDynsym()) 20910b57cec5SDimitry Andric return; 20920b57cec5SDimitry Andric 209381ad6265SDimitry Andric StringRef partName = reinterpret_cast<const char *>(s->rawData.data()); 20940b57cec5SDimitry Andric for (Partition &part : partitions) { 20950b57cec5SDimitry Andric if (part.name == partName) { 20960b57cec5SDimitry Andric sym->partition = part.getNumber(); 20970b57cec5SDimitry Andric return; 20980b57cec5SDimitry Andric } 20990b57cec5SDimitry Andric } 21000b57cec5SDimitry Andric 21010b57cec5SDimitry Andric // Forbid partitions from being used on incompatible targets, and forbid them 21020b57cec5SDimitry Andric // from being used together with various linker features that assume a single 21030b57cec5SDimitry Andric // set of output sections. 21040b57cec5SDimitry Andric if (script->hasSectionsCommand) 21050b57cec5SDimitry Andric error(toString(s->file) + 21060b57cec5SDimitry Andric ": partitions cannot be used with the SECTIONS command"); 21070b57cec5SDimitry Andric if (script->hasPhdrsCommands()) 21080b57cec5SDimitry Andric error(toString(s->file) + 21090b57cec5SDimitry Andric ": partitions cannot be used with the PHDRS command"); 21100b57cec5SDimitry Andric if (!config->sectionStartMap.empty()) 21110b57cec5SDimitry Andric error(toString(s->file) + ": partitions cannot be used with " 21120b57cec5SDimitry Andric "--section-start, -Ttext, -Tdata or -Tbss"); 21130b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 21140b57cec5SDimitry Andric error(toString(s->file) + ": partitions cannot be used on this target"); 21150b57cec5SDimitry Andric 21160b57cec5SDimitry Andric // Impose a limit of no more than 254 partitions. This limit comes from the 21170b57cec5SDimitry Andric // sizes of the Partition fields in InputSectionBase and Symbol, as well as 21180b57cec5SDimitry Andric // the amount of space devoted to the partition number in RankFlags. 21190b57cec5SDimitry Andric if (partitions.size() == 254) 21200b57cec5SDimitry Andric fatal("may not have more than 254 partitions"); 21210b57cec5SDimitry Andric 21220b57cec5SDimitry Andric partitions.emplace_back(); 21230b57cec5SDimitry Andric Partition &newPart = partitions.back(); 21240b57cec5SDimitry Andric newPart.name = partName; 21250b57cec5SDimitry Andric sym->partition = newPart.getNumber(); 21260b57cec5SDimitry Andric } 21270b57cec5SDimitry Andric 2128fe6060f1SDimitry Andric static Symbol *addUnusedUndefined(StringRef name, 2129fe6060f1SDimitry Andric uint8_t binding = STB_GLOBAL) { 213081ad6265SDimitry Andric return symtab->addSymbol(Undefined{nullptr, name, binding, STV_DEFAULT, 0}); 21315ffd83dbSDimitry Andric } 21325ffd83dbSDimitry Andric 213304eeddc0SDimitry Andric static void markBuffersAsDontNeed(bool skipLinkedOutput) { 213404eeddc0SDimitry Andric // With --thinlto-index-only, all buffers are nearly unused from now on 213504eeddc0SDimitry Andric // (except symbol/section names used by infrequent passes). Mark input file 213604eeddc0SDimitry Andric // buffers as MADV_DONTNEED so that these pages can be reused by the expensive 213704eeddc0SDimitry Andric // thin link, saving memory. 213804eeddc0SDimitry Andric if (skipLinkedOutput) { 213981ad6265SDimitry Andric for (MemoryBuffer &mb : llvm::make_pointee_range(ctx->memoryBuffers)) 214004eeddc0SDimitry Andric mb.dontNeedIfMmap(); 214104eeddc0SDimitry Andric return; 214204eeddc0SDimitry Andric } 214304eeddc0SDimitry Andric 214404eeddc0SDimitry Andric // Otherwise, just mark MemoryBuffers backing BitcodeFiles. 214504eeddc0SDimitry Andric DenseSet<const char *> bufs; 214681ad6265SDimitry Andric for (BitcodeFile *file : ctx->bitcodeFiles) 214704eeddc0SDimitry Andric bufs.insert(file->mb.getBufferStart()); 214881ad6265SDimitry Andric for (BitcodeFile *file : ctx->lazyBitcodeFiles) 214904eeddc0SDimitry Andric bufs.insert(file->mb.getBufferStart()); 215081ad6265SDimitry Andric for (MemoryBuffer &mb : llvm::make_pointee_range(ctx->memoryBuffers)) 215104eeddc0SDimitry Andric if (bufs.count(mb.getBufferStart())) 215204eeddc0SDimitry Andric mb.dontNeedIfMmap(); 215304eeddc0SDimitry Andric } 215404eeddc0SDimitry Andric 21550b57cec5SDimitry Andric // This function is where all the optimizations of link-time 21560b57cec5SDimitry Andric // optimization takes place. When LTO is in use, some input files are 21570b57cec5SDimitry Andric // not in native object file format but in the LLVM bitcode format. 21580b57cec5SDimitry Andric // This function compiles bitcode files into a few big native files 21590b57cec5SDimitry Andric // using LLVM functions and replaces bitcode symbols with the results. 21600b57cec5SDimitry Andric // Because all bitcode files that the program consists of are passed to 21610b57cec5SDimitry Andric // the compiler at once, it can do a whole-program optimization. 216204eeddc0SDimitry Andric template <class ELFT> 216304eeddc0SDimitry Andric void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) { 21645ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("LTO"); 21650b57cec5SDimitry Andric // Compile bitcode files and replace bitcode symbols. 21660b57cec5SDimitry Andric lto.reset(new BitcodeCompiler); 216781ad6265SDimitry Andric for (BitcodeFile *file : ctx->bitcodeFiles) 21680b57cec5SDimitry Andric lto->add(*file); 21690b57cec5SDimitry Andric 217081ad6265SDimitry Andric if (!ctx->bitcodeFiles.empty()) 217104eeddc0SDimitry Andric markBuffersAsDontNeed(skipLinkedOutput); 217204eeddc0SDimitry Andric 21730b57cec5SDimitry Andric for (InputFile *file : lto->compile()) { 21740b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(file); 21750b57cec5SDimitry Andric obj->parse(/*ignoreComdats=*/true); 21765ffd83dbSDimitry Andric 21775ffd83dbSDimitry Andric // Parse '@' in symbol names for non-relocatable output. 21785ffd83dbSDimitry Andric if (!config->relocatable) 21790b57cec5SDimitry Andric for (Symbol *sym : obj->getGlobalSymbols()) 218004eeddc0SDimitry Andric if (sym->hasVersionSuffix) 21810b57cec5SDimitry Andric sym->parseSymbolVersion(); 218281ad6265SDimitry Andric ctx->objectFiles.push_back(obj); 21830b57cec5SDimitry Andric } 21840b57cec5SDimitry Andric } 21850b57cec5SDimitry Andric 21860b57cec5SDimitry Andric // The --wrap option is a feature to rename symbols so that you can write 2187349cc55cSDimitry Andric // wrappers for existing functions. If you pass `--wrap=foo`, all 2188e8d8bef9SDimitry Andric // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are 2189e8d8bef9SDimitry Andric // expected to write `__wrap_foo` function as a wrapper). The original 2190e8d8bef9SDimitry Andric // symbol becomes accessible as `__real_foo`, so you can call that from your 21910b57cec5SDimitry Andric // wrapper. 21920b57cec5SDimitry Andric // 2193349cc55cSDimitry Andric // This data structure is instantiated for each --wrap option. 21940b57cec5SDimitry Andric struct WrappedSymbol { 21950b57cec5SDimitry Andric Symbol *sym; 21960b57cec5SDimitry Andric Symbol *real; 21970b57cec5SDimitry Andric Symbol *wrap; 21980b57cec5SDimitry Andric }; 21990b57cec5SDimitry Andric 2200349cc55cSDimitry Andric // Handles --wrap option. 22010b57cec5SDimitry Andric // 22020b57cec5SDimitry Andric // This function instantiates wrapper symbols. At this point, they seem 22030b57cec5SDimitry Andric // like they are not being used at all, so we explicitly set some flags so 22040b57cec5SDimitry Andric // that LTO won't eliminate them. 22050b57cec5SDimitry Andric static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) { 22060b57cec5SDimitry Andric std::vector<WrappedSymbol> v; 22070b57cec5SDimitry Andric DenseSet<StringRef> seen; 22080b57cec5SDimitry Andric 22090b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wrap)) { 22100b57cec5SDimitry Andric StringRef name = arg->getValue(); 22110b57cec5SDimitry Andric if (!seen.insert(name).second) 22120b57cec5SDimitry Andric continue; 22130b57cec5SDimitry Andric 22140b57cec5SDimitry Andric Symbol *sym = symtab->find(name); 22150b57cec5SDimitry Andric if (!sym) 22160b57cec5SDimitry Andric continue; 22170b57cec5SDimitry Andric 221804eeddc0SDimitry Andric Symbol *real = addUnusedUndefined(saver().save("__real_" + name)); 2219fe6060f1SDimitry Andric Symbol *wrap = 222004eeddc0SDimitry Andric addUnusedUndefined(saver().save("__wrap_" + name), sym->binding); 22210b57cec5SDimitry Andric v.push_back({sym, real, wrap}); 22220b57cec5SDimitry Andric 22230b57cec5SDimitry Andric // We want to tell LTO not to inline symbols to be overwritten 22240b57cec5SDimitry Andric // because LTO doesn't know the final symbol contents after renaming. 222581ad6265SDimitry Andric real->scriptDefined = true; 222681ad6265SDimitry Andric sym->scriptDefined = true; 22270b57cec5SDimitry Andric 222881ad6265SDimitry Andric // If a symbol is referenced in any object file, bitcode file or shared 222981ad6265SDimitry Andric // object, mark its redirection target (foo for __real_foo and __wrap_foo 223081ad6265SDimitry Andric // for foo) as referenced after redirection, which will be used to tell LTO 223181ad6265SDimitry Andric // to not eliminate the redirection target. If the object file defining the 223281ad6265SDimitry Andric // symbol also references it, we cannot easily distinguish the case from 223381ad6265SDimitry Andric // cases where the symbol is not referenced. Retain the redirection target 223481ad6265SDimitry Andric // in this case because we choose to wrap symbol references regardless of 223581ad6265SDimitry Andric // whether the symbol is defined 2236e8d8bef9SDimitry Andric // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358). 223781ad6265SDimitry Andric if (real->referenced || real->isDefined()) 223881ad6265SDimitry Andric sym->referencedAfterWrap = true; 2239e8d8bef9SDimitry Andric if (sym->referenced || sym->isDefined()) 224081ad6265SDimitry Andric wrap->referencedAfterWrap = true; 22410b57cec5SDimitry Andric } 22420b57cec5SDimitry Andric return v; 22430b57cec5SDimitry Andric } 22440b57cec5SDimitry Andric 2245349cc55cSDimitry Andric // Do renaming for --wrap and foo@v1 by updating pointers to symbols. 22460b57cec5SDimitry Andric // 22470b57cec5SDimitry Andric // When this function is executed, only InputFiles and symbol table 22480b57cec5SDimitry Andric // contain pointers to symbol objects. We visit them to replace pointers, 22490b57cec5SDimitry Andric // so that wrapped symbols are swapped as instructed by the command line. 2250e8d8bef9SDimitry Andric static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) { 2251e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Redirect symbols"); 22520b57cec5SDimitry Andric DenseMap<Symbol *, Symbol *> map; 22530b57cec5SDimitry Andric for (const WrappedSymbol &w : wrapped) { 22540b57cec5SDimitry Andric map[w.sym] = w.wrap; 22550b57cec5SDimitry Andric map[w.real] = w.sym; 22560b57cec5SDimitry Andric } 2257e8d8bef9SDimitry Andric for (Symbol *sym : symtab->symbols()) { 225804eeddc0SDimitry Andric // Enumerate symbols with a non-default version (foo@v1). hasVersionSuffix 225904eeddc0SDimitry Andric // filters out most symbols but is not sufficient. 226004eeddc0SDimitry Andric if (!sym->hasVersionSuffix) 226104eeddc0SDimitry Andric continue; 2262e8d8bef9SDimitry Andric const char *suffix1 = sym->getVersionSuffix(); 2263e8d8bef9SDimitry Andric if (suffix1[0] != '@' || suffix1[1] == '@') 2264e8d8bef9SDimitry Andric continue; 2265e8d8bef9SDimitry Andric 22666e75b2fbSDimitry Andric // Check the existing symbol foo. We have two special cases to handle: 22676e75b2fbSDimitry Andric // 22686e75b2fbSDimitry Andric // * There is a definition of foo@v1 and foo@@v1. 22696e75b2fbSDimitry Andric // * There is a definition of foo@v1 and foo. 227004eeddc0SDimitry Andric Defined *sym2 = dyn_cast_or_null<Defined>(symtab->find(sym->getName())); 22716e75b2fbSDimitry Andric if (!sym2) 2272e8d8bef9SDimitry Andric continue; 22736e75b2fbSDimitry Andric const char *suffix2 = sym2->getVersionSuffix(); 22746e75b2fbSDimitry Andric if (suffix2[0] == '@' && suffix2[1] == '@' && 22756e75b2fbSDimitry Andric strcmp(suffix1 + 1, suffix2 + 2) == 0) { 2276e8d8bef9SDimitry Andric // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1. 22776e75b2fbSDimitry Andric map.try_emplace(sym, sym2); 2278e8d8bef9SDimitry Andric // If both foo@v1 and foo@@v1 are defined and non-weak, report a duplicate 2279e8d8bef9SDimitry Andric // definition error. 228081ad6265SDimitry Andric if (sym->isDefined()) 228181ad6265SDimitry Andric sym2->checkDuplicate(cast<Defined>(*sym)); 22826e75b2fbSDimitry Andric sym2->resolve(*sym); 2283e8d8bef9SDimitry Andric // Eliminate foo@v1 from the symbol table. 2284e8d8bef9SDimitry Andric sym->symbolKind = Symbol::PlaceholderKind; 228504eeddc0SDimitry Andric sym->isUsedInRegularObj = false; 22866e75b2fbSDimitry Andric } else if (auto *sym1 = dyn_cast<Defined>(sym)) { 22876e75b2fbSDimitry Andric if (sym2->versionId > VER_NDX_GLOBAL 22886e75b2fbSDimitry Andric ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1 22896e75b2fbSDimitry Andric : sym1->section == sym2->section && sym1->value == sym2->value) { 22906e75b2fbSDimitry Andric // Due to an assembler design flaw, if foo is defined, .symver foo, 22916e75b2fbSDimitry Andric // foo@v1 defines both foo and foo@v1. Unless foo is bound to a 2292349cc55cSDimitry Andric // different version, GNU ld makes foo@v1 canonical and eliminates foo. 22936e75b2fbSDimitry Andric // Emulate its behavior, otherwise we would have foo or foo@@v1 beside 22946e75b2fbSDimitry Andric // foo@v1. foo@v1 and foo combining does not apply if they are not 22956e75b2fbSDimitry Andric // defined in the same place. 22966e75b2fbSDimitry Andric map.try_emplace(sym2, sym); 22976e75b2fbSDimitry Andric sym2->symbolKind = Symbol::PlaceholderKind; 229804eeddc0SDimitry Andric sym2->isUsedInRegularObj = false; 22996e75b2fbSDimitry Andric } 23006e75b2fbSDimitry Andric } 2301e8d8bef9SDimitry Andric } 2302e8d8bef9SDimitry Andric 2303e8d8bef9SDimitry Andric if (map.empty()) 2304e8d8bef9SDimitry Andric return; 23050b57cec5SDimitry Andric 23060b57cec5SDimitry Andric // Update pointers in input files. 230781ad6265SDimitry Andric parallelForEach(ctx->objectFiles, [&](ELFFileBase *file) { 23080eae32dcSDimitry Andric for (Symbol *&sym : file->getMutableGlobalSymbols()) 23090eae32dcSDimitry Andric if (Symbol *s = map.lookup(sym)) 23100eae32dcSDimitry Andric sym = s; 23110b57cec5SDimitry Andric }); 23120b57cec5SDimitry Andric 23130b57cec5SDimitry Andric // Update pointers in the symbol table. 23140b57cec5SDimitry Andric for (const WrappedSymbol &w : wrapped) 23150b57cec5SDimitry Andric symtab->wrap(w.sym, w.real, w.wrap); 23160b57cec5SDimitry Andric } 23170b57cec5SDimitry Andric 23180eae32dcSDimitry Andric static void checkAndReportMissingFeature(StringRef config, uint32_t features, 23190eae32dcSDimitry Andric uint32_t mask, const Twine &report) { 23200eae32dcSDimitry Andric if (!(features & mask)) { 23210eae32dcSDimitry Andric if (config == "error") 23220eae32dcSDimitry Andric error(report); 23230eae32dcSDimitry Andric else if (config == "warning") 23240eae32dcSDimitry Andric warn(report); 23250eae32dcSDimitry Andric } 23260eae32dcSDimitry Andric } 23270eae32dcSDimitry Andric 23280b57cec5SDimitry Andric // To enable CET (x86's hardware-assited control flow enforcement), each 23290b57cec5SDimitry Andric // source file must be compiled with -fcf-protection. Object files compiled 23300b57cec5SDimitry Andric // with the flag contain feature flags indicating that they are compatible 23310b57cec5SDimitry Andric // with CET. We enable the feature only when all object files are compatible 23320b57cec5SDimitry Andric // with CET. 23330b57cec5SDimitry Andric // 23340b57cec5SDimitry Andric // This is also the case with AARCH64's BTI and PAC which use the similar 23350b57cec5SDimitry Andric // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism. 23361fd87a68SDimitry Andric static uint32_t getAndFeatures() { 23370b57cec5SDimitry Andric if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 23380b57cec5SDimitry Andric config->emachine != EM_AARCH64) 23390b57cec5SDimitry Andric return 0; 23400b57cec5SDimitry Andric 23410b57cec5SDimitry Andric uint32_t ret = -1; 234281ad6265SDimitry Andric for (ELFFileBase *f : ctx->objectFiles) { 23431fd87a68SDimitry Andric uint32_t features = f->andFeatures; 23440eae32dcSDimitry Andric 23450eae32dcSDimitry Andric checkAndReportMissingFeature( 23460eae32dcSDimitry Andric config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI, 23470eae32dcSDimitry Andric toString(f) + ": -z bti-report: file does not have " 23480eae32dcSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 23490eae32dcSDimitry Andric 23500eae32dcSDimitry Andric checkAndReportMissingFeature( 23510eae32dcSDimitry Andric config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT, 23520eae32dcSDimitry Andric toString(f) + ": -z cet-report: file does not have " 23530eae32dcSDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 23540eae32dcSDimitry Andric 23550eae32dcSDimitry Andric checkAndReportMissingFeature( 23560eae32dcSDimitry Andric config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK, 23570eae32dcSDimitry Andric toString(f) + ": -z cet-report: file does not have " 23580eae32dcSDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_SHSTK property"); 23590eae32dcSDimitry Andric 23605ffd83dbSDimitry Andric if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) { 23610eae32dcSDimitry Andric features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI; 23620eae32dcSDimitry Andric if (config->zBtiReport == "none") 23635ffd83dbSDimitry Andric warn(toString(f) + ": -z force-bti: file does not have " 23645ffd83dbSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 2365480093f4SDimitry Andric } else if (config->zForceIbt && 2366480093f4SDimitry Andric !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) { 23670eae32dcSDimitry Andric if (config->zCetReport == "none") 2368480093f4SDimitry Andric warn(toString(f) + ": -z force-ibt: file does not have " 2369480093f4SDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 2370480093f4SDimitry Andric features |= GNU_PROPERTY_X86_FEATURE_1_IBT; 2371480093f4SDimitry Andric } 23725ffd83dbSDimitry Andric if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) { 23735ffd83dbSDimitry Andric warn(toString(f) + ": -z pac-plt: file does not have " 23745ffd83dbSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property"); 23755ffd83dbSDimitry Andric features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC; 23765ffd83dbSDimitry Andric } 23770b57cec5SDimitry Andric ret &= features; 23780b57cec5SDimitry Andric } 23790b57cec5SDimitry Andric 2380480093f4SDimitry Andric // Force enable Shadow Stack. 2381480093f4SDimitry Andric if (config->zShstk) 2382480093f4SDimitry Andric ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK; 23830b57cec5SDimitry Andric 23840b57cec5SDimitry Andric return ret; 23850b57cec5SDimitry Andric } 23860b57cec5SDimitry Andric 238781ad6265SDimitry Andric static void initializeLocalSymbols(ELFFileBase *file) { 238881ad6265SDimitry Andric switch (config->ekind) { 238981ad6265SDimitry Andric case ELF32LEKind: 239081ad6265SDimitry Andric cast<ObjFile<ELF32LE>>(file)->initializeLocalSymbols(); 239181ad6265SDimitry Andric break; 239281ad6265SDimitry Andric case ELF32BEKind: 239381ad6265SDimitry Andric cast<ObjFile<ELF32BE>>(file)->initializeLocalSymbols(); 239481ad6265SDimitry Andric break; 239581ad6265SDimitry Andric case ELF64LEKind: 239681ad6265SDimitry Andric cast<ObjFile<ELF64LE>>(file)->initializeLocalSymbols(); 239781ad6265SDimitry Andric break; 239881ad6265SDimitry Andric case ELF64BEKind: 239981ad6265SDimitry Andric cast<ObjFile<ELF64BE>>(file)->initializeLocalSymbols(); 240081ad6265SDimitry Andric break; 240181ad6265SDimitry Andric default: 240281ad6265SDimitry Andric llvm_unreachable(""); 240381ad6265SDimitry Andric } 240481ad6265SDimitry Andric } 240581ad6265SDimitry Andric 240681ad6265SDimitry Andric static void postParseObjectFile(ELFFileBase *file) { 240781ad6265SDimitry Andric switch (config->ekind) { 240881ad6265SDimitry Andric case ELF32LEKind: 240981ad6265SDimitry Andric cast<ObjFile<ELF32LE>>(file)->postParse(); 241081ad6265SDimitry Andric break; 241181ad6265SDimitry Andric case ELF32BEKind: 241281ad6265SDimitry Andric cast<ObjFile<ELF32BE>>(file)->postParse(); 241381ad6265SDimitry Andric break; 241481ad6265SDimitry Andric case ELF64LEKind: 241581ad6265SDimitry Andric cast<ObjFile<ELF64LE>>(file)->postParse(); 241681ad6265SDimitry Andric break; 241781ad6265SDimitry Andric case ELF64BEKind: 241881ad6265SDimitry Andric cast<ObjFile<ELF64BE>>(file)->postParse(); 241981ad6265SDimitry Andric break; 242081ad6265SDimitry Andric default: 242181ad6265SDimitry Andric llvm_unreachable(""); 242281ad6265SDimitry Andric } 242381ad6265SDimitry Andric } 242481ad6265SDimitry Andric 24250b57cec5SDimitry Andric // Do actual linking. Note that when this function is called, 24260b57cec5SDimitry Andric // all linker scripts have already been parsed. 24271fd87a68SDimitry Andric void LinkerDriver::link(opt::InputArgList &args) { 24285ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link")); 2429349cc55cSDimitry Andric // If a --hash-style option was not given, set to a default value, 24300b57cec5SDimitry Andric // which varies depending on the target. 24310b57cec5SDimitry Andric if (!args.hasArg(OPT_hash_style)) { 24320b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 24330b57cec5SDimitry Andric config->sysvHash = true; 24340b57cec5SDimitry Andric else 24350b57cec5SDimitry Andric config->sysvHash = config->gnuHash = true; 24360b57cec5SDimitry Andric } 24370b57cec5SDimitry Andric 24380b57cec5SDimitry Andric // Default output filename is "a.out" by the Unix tradition. 24390b57cec5SDimitry Andric if (config->outputFile.empty()) 24400b57cec5SDimitry Andric config->outputFile = "a.out"; 24410b57cec5SDimitry Andric 24420b57cec5SDimitry Andric // Fail early if the output file or map file is not writable. If a user has a 24430b57cec5SDimitry Andric // long link, e.g. due to a large LTO link, they do not wish to run it and 24440b57cec5SDimitry Andric // find that it failed because there was a mistake in their command-line. 2445e8d8bef9SDimitry Andric { 2446e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Create output files"); 24470b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) 2448e8d8bef9SDimitry Andric error("cannot open output file " + config->outputFile + ": " + 2449e8d8bef9SDimitry Andric e.message()); 24500b57cec5SDimitry Andric if (auto e = tryCreateFile(config->mapFile)) 24510b57cec5SDimitry Andric error("cannot open map file " + config->mapFile + ": " + e.message()); 2452349cc55cSDimitry Andric if (auto e = tryCreateFile(config->whyExtract)) 2453349cc55cSDimitry Andric error("cannot open --why-extract= file " + config->whyExtract + ": " + 2454349cc55cSDimitry Andric e.message()); 2455e8d8bef9SDimitry Andric } 24560b57cec5SDimitry Andric if (errorCount()) 24570b57cec5SDimitry Andric return; 24580b57cec5SDimitry Andric 24590b57cec5SDimitry Andric // Use default entry point name if no name was given via the command 24600b57cec5SDimitry Andric // line nor linker scripts. For some reason, MIPS entry point name is 24610b57cec5SDimitry Andric // different from others. 24620b57cec5SDimitry Andric config->warnMissingEntry = 24630b57cec5SDimitry Andric (!config->entry.empty() || (!config->shared && !config->relocatable)); 24640b57cec5SDimitry Andric if (config->entry.empty() && !config->relocatable) 24650b57cec5SDimitry Andric config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start"; 24660b57cec5SDimitry Andric 24670b57cec5SDimitry Andric // Handle --trace-symbol. 24680b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_trace_symbol)) 24690b57cec5SDimitry Andric symtab->insert(arg->getValue())->traced = true; 24700b57cec5SDimitry Andric 24715ffd83dbSDimitry Andric // Handle -u/--undefined before input files. If both a.a and b.so define foo, 24724824e7fdSDimitry Andric // -u foo a.a b.so will extract a.a. 24735ffd83dbSDimitry Andric for (StringRef name : config->undefined) 2474e8d8bef9SDimitry Andric addUnusedUndefined(name)->referenced = true; 24755ffd83dbSDimitry Andric 24760b57cec5SDimitry Andric // Add all files to the symbol table. This will add almost all 24770b57cec5SDimitry Andric // symbols that we need to the symbol table. This process might 24780b57cec5SDimitry Andric // add files to the link, via autolinking, these files are always 24790b57cec5SDimitry Andric // appended to the Files vector. 24805ffd83dbSDimitry Andric { 24815ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("Parse input files"); 2482e8d8bef9SDimitry Andric for (size_t i = 0; i < files.size(); ++i) { 2483e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName()); 24840b57cec5SDimitry Andric parseFile(files[i]); 24855ffd83dbSDimitry Andric } 2486e8d8bef9SDimitry Andric } 24870b57cec5SDimitry Andric 24880b57cec5SDimitry Andric // Now that we have every file, we can decide if we will need a 24890b57cec5SDimitry Andric // dynamic symbol table. 24900b57cec5SDimitry Andric // We need one if we were asked to export dynamic symbols or if we are 24910b57cec5SDimitry Andric // producing a shared library. 24920b57cec5SDimitry Andric // We also need one if any shared libraries are used and for pie executables 24930b57cec5SDimitry Andric // (probably because the dynamic linker needs it). 24940b57cec5SDimitry Andric config->hasDynSymTab = 249581ad6265SDimitry Andric !ctx->sharedFiles.empty() || config->isPic || config->exportDynamic; 24960b57cec5SDimitry Andric 24970b57cec5SDimitry Andric // Some symbols (such as __ehdr_start) are defined lazily only when there 24980b57cec5SDimitry Andric // are undefined symbols for them, so we add these to trigger that logic. 249981ad6265SDimitry Andric for (StringRef name : script->referencedSymbols) { 250081ad6265SDimitry Andric Symbol *sym = addUnusedUndefined(name); 250181ad6265SDimitry Andric sym->isUsedInRegularObj = true; 250281ad6265SDimitry Andric sym->referenced = true; 250381ad6265SDimitry Andric } 25040b57cec5SDimitry Andric 25055ffd83dbSDimitry Andric // Prevent LTO from removing any definition referenced by -u. 25065ffd83dbSDimitry Andric for (StringRef name : config->undefined) 25075ffd83dbSDimitry Andric if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name))) 25085ffd83dbSDimitry Andric sym->isUsedInRegularObj = true; 25090b57cec5SDimitry Andric 25100b57cec5SDimitry Andric // If an entry symbol is in a static archive, pull out that file now. 25110b57cec5SDimitry Andric if (Symbol *sym = symtab->find(config->entry)) 2512349cc55cSDimitry Andric handleUndefined(sym, "--entry"); 25130b57cec5SDimitry Andric 25140b57cec5SDimitry Andric // Handle the `--undefined-glob <pattern>` options. 25150b57cec5SDimitry Andric for (StringRef pat : args::getStrings(args, OPT_undefined_glob)) 25160b57cec5SDimitry Andric handleUndefinedGlob(pat); 25170b57cec5SDimitry Andric 2518480093f4SDimitry Andric // Mark -init and -fini symbols so that the LTO doesn't eliminate them. 25195ffd83dbSDimitry Andric if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init))) 2520480093f4SDimitry Andric sym->isUsedInRegularObj = true; 25215ffd83dbSDimitry Andric if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini))) 2522480093f4SDimitry Andric sym->isUsedInRegularObj = true; 2523480093f4SDimitry Andric 25240b57cec5SDimitry Andric // If any of our inputs are bitcode files, the LTO code generator may create 25250b57cec5SDimitry Andric // references to certain library functions that might not be explicit in the 25260b57cec5SDimitry Andric // bitcode file's symbol table. If any of those library functions are defined 25270b57cec5SDimitry Andric // in a bitcode file in an archive member, we need to arrange to use LTO to 25280b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 25290b57cec5SDimitry Andric // 25300b57cec5SDimitry Andric // However, adding all libcall symbols to the link can have undesired 25310b57cec5SDimitry Andric // consequences. For example, the libgcc implementation of 25320b57cec5SDimitry Andric // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 25330b57cec5SDimitry Andric // that aborts the program if the Linux kernel does not support 64-bit 25340b57cec5SDimitry Andric // atomics, which would prevent the program from running even if it does not 25350b57cec5SDimitry Andric // use 64-bit atomics. 25360b57cec5SDimitry Andric // 25370b57cec5SDimitry Andric // Therefore, we only add libcall symbols to the link before LTO if we have 25380b57cec5SDimitry Andric // to, i.e. if the symbol's definition is in bitcode. Any other required 25390b57cec5SDimitry Andric // libcall symbols will be added to the link after LTO when we add the LTO 25400b57cec5SDimitry Andric // object file to the link. 254181ad6265SDimitry Andric if (!ctx->bitcodeFiles.empty()) 254285868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 25430b57cec5SDimitry Andric handleLibcall(s); 25440b57cec5SDimitry Andric 254581ad6265SDimitry Andric // Archive members defining __wrap symbols may be extracted. 254681ad6265SDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 254781ad6265SDimitry Andric 254881ad6265SDimitry Andric // No more lazy bitcode can be extracted at this point. Do post parse work 254981ad6265SDimitry Andric // like checking duplicate symbols. 255081ad6265SDimitry Andric parallelForEach(ctx->objectFiles, initializeLocalSymbols); 255181ad6265SDimitry Andric parallelForEach(ctx->objectFiles, postParseObjectFile); 255281ad6265SDimitry Andric parallelForEach(ctx->bitcodeFiles, 255381ad6265SDimitry Andric [](BitcodeFile *file) { file->postParse(); }); 255481ad6265SDimitry Andric for (auto &it : ctx->nonPrevailingSyms) { 255581ad6265SDimitry Andric Symbol &sym = *it.first; 255681ad6265SDimitry Andric sym.replace(Undefined{sym.file, sym.getName(), sym.binding, sym.stOther, 255781ad6265SDimitry Andric sym.type, it.second}); 255881ad6265SDimitry Andric cast<Undefined>(sym).nonPrevailing = true; 255981ad6265SDimitry Andric } 256081ad6265SDimitry Andric ctx->nonPrevailingSyms.clear(); 256181ad6265SDimitry Andric for (const DuplicateSymbol &d : ctx->duplicates) 256281ad6265SDimitry Andric reportDuplicate(*d.sym, d.file, d.section, d.value); 256381ad6265SDimitry Andric ctx->duplicates.clear(); 256481ad6265SDimitry Andric 25650b57cec5SDimitry Andric // Return if there were name resolution errors. 25660b57cec5SDimitry Andric if (errorCount()) 25670b57cec5SDimitry Andric return; 25680b57cec5SDimitry Andric 25690b57cec5SDimitry Andric // We want to declare linker script's symbols early, 25700b57cec5SDimitry Andric // so that we can version them. 25710b57cec5SDimitry Andric // They also might be exported if referenced by DSOs. 25720b57cec5SDimitry Andric script->declareSymbols(); 25730b57cec5SDimitry Andric 2574e8d8bef9SDimitry Andric // Handle --exclude-libs. This is before scanVersionScript() due to a 2575e8d8bef9SDimitry Andric // workaround for Android ndk: for a defined versioned symbol in an archive 2576e8d8bef9SDimitry Andric // without a version node in the version script, Android does not expect a 2577e8d8bef9SDimitry Andric // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295). 2578e8d8bef9SDimitry Andric // GNU ld errors in this case. 25790b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_libs)) 25800b57cec5SDimitry Andric excludeLibs(args); 25810b57cec5SDimitry Andric 25820b57cec5SDimitry Andric // Create elfHeader early. We need a dummy section in 25830b57cec5SDimitry Andric // addReservedSymbols to mark the created symbols as not absolute. 25840b57cec5SDimitry Andric Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC); 25850b57cec5SDimitry Andric 25860b57cec5SDimitry Andric // We need to create some reserved symbols such as _end. Create them. 25870b57cec5SDimitry Andric if (!config->relocatable) 25880b57cec5SDimitry Andric addReservedSymbols(); 25890b57cec5SDimitry Andric 25900b57cec5SDimitry Andric // Apply version scripts. 25910b57cec5SDimitry Andric // 25920b57cec5SDimitry Andric // For a relocatable output, version scripts don't make sense, and 25930b57cec5SDimitry Andric // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 25940b57cec5SDimitry Andric // name "foo@ver1") rather do harm, so we don't call this if -r is given. 2595e8d8bef9SDimitry Andric if (!config->relocatable) { 2596e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Process symbol versions"); 25970b57cec5SDimitry Andric symtab->scanVersionScript(); 2598e8d8bef9SDimitry Andric } 25990b57cec5SDimitry Andric 260004eeddc0SDimitry Andric // Skip the normal linked output if some LTO options are specified. 260104eeddc0SDimitry Andric // 260204eeddc0SDimitry Andric // For --thinlto-index-only, index file creation is performed in 260304eeddc0SDimitry Andric // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and 260404eeddc0SDimitry Andric // --plugin-opt=emit-asm create output files in bitcode or assembly code, 260504eeddc0SDimitry Andric // respectively. When only certain thinLTO modules are specified for 260604eeddc0SDimitry Andric // compilation, the intermediate object file are the expected output. 260704eeddc0SDimitry Andric const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM || 260804eeddc0SDimitry Andric config->ltoEmitAsm || 260904eeddc0SDimitry Andric !config->thinLTOModulesToCompile.empty(); 261004eeddc0SDimitry Andric 26110b57cec5SDimitry Andric // Do link-time optimization if given files are LLVM bitcode files. 26120b57cec5SDimitry Andric // This compiles bitcode files into real object files. 26130b57cec5SDimitry Andric // 26140b57cec5SDimitry Andric // With this the symbol table should be complete. After this, no new names 26150b57cec5SDimitry Andric // except a few linker-synthesized ones will be added to the symbol table. 261681ad6265SDimitry Andric const size_t numObjsBeforeLTO = ctx->objectFiles.size(); 26171fd87a68SDimitry Andric invokeELFT(compileBitcodeFiles, skipLinkedOutput); 261804eeddc0SDimitry Andric 261981ad6265SDimitry Andric // Symbol resolution finished. Report backward reference problems, 262081ad6265SDimitry Andric // --print-archive-stats=, and --why-extract=. 262104eeddc0SDimitry Andric reportBackrefs(); 262281ad6265SDimitry Andric writeArchiveStats(); 262381ad6265SDimitry Andric writeWhyExtract(); 262404eeddc0SDimitry Andric if (errorCount()) 262504eeddc0SDimitry Andric return; 262604eeddc0SDimitry Andric 262704eeddc0SDimitry Andric // Bail out if normal linked output is skipped due to LTO. 262804eeddc0SDimitry Andric if (skipLinkedOutput) 262904eeddc0SDimitry Andric return; 26305ffd83dbSDimitry Andric 263181ad6265SDimitry Andric // compileBitcodeFiles may have produced lto.tmp object files. After this, no 263281ad6265SDimitry Andric // more file will be added. 263381ad6265SDimitry Andric auto newObjectFiles = makeArrayRef(ctx->objectFiles).slice(numObjsBeforeLTO); 263481ad6265SDimitry Andric parallelForEach(newObjectFiles, initializeLocalSymbols); 263581ad6265SDimitry Andric parallelForEach(newObjectFiles, postParseObjectFile); 263681ad6265SDimitry Andric for (const DuplicateSymbol &d : ctx->duplicates) 263781ad6265SDimitry Andric reportDuplicate(*d.sym, d.file, d.section, d.value); 263881ad6265SDimitry Andric 2639e8d8bef9SDimitry Andric // Handle --exclude-libs again because lto.tmp may reference additional 2640e8d8bef9SDimitry Andric // libcalls symbols defined in an excluded archive. This may override 2641e8d8bef9SDimitry Andric // versionId set by scanVersionScript(). 2642e8d8bef9SDimitry Andric if (args.hasArg(OPT_exclude_libs)) 2643e8d8bef9SDimitry Andric excludeLibs(args); 2644e8d8bef9SDimitry Andric 2645349cc55cSDimitry Andric // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1. 2646e8d8bef9SDimitry Andric redirectSymbols(wrapped); 26470b57cec5SDimitry Andric 264804eeddc0SDimitry Andric // Replace common symbols with regular symbols. 264904eeddc0SDimitry Andric replaceCommonSymbols(); 265004eeddc0SDimitry Andric 2651e8d8bef9SDimitry Andric { 2652e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Aggregate sections"); 26530b57cec5SDimitry Andric // Now that we have a complete list of input files. 26540b57cec5SDimitry Andric // Beyond this point, no new files are added. 26550b57cec5SDimitry Andric // Aggregate all input sections into one place. 265681ad6265SDimitry Andric for (InputFile *f : ctx->objectFiles) 26570b57cec5SDimitry Andric for (InputSectionBase *s : f->getSections()) 26580b57cec5SDimitry Andric if (s && s != &InputSection::discarded) 26590b57cec5SDimitry Andric inputSections.push_back(s); 266081ad6265SDimitry Andric for (BinaryFile *f : ctx->binaryFiles) 26610b57cec5SDimitry Andric for (InputSectionBase *s : f->getSections()) 26620b57cec5SDimitry Andric inputSections.push_back(cast<InputSection>(s)); 2663e8d8bef9SDimitry Andric } 26640b57cec5SDimitry Andric 2665e8d8bef9SDimitry Andric { 2666e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Strip sections"); 266781ad6265SDimitry Andric if (ctx->hasSympart.load(std::memory_order_relaxed)) { 26680b57cec5SDimitry Andric llvm::erase_if(inputSections, [](InputSectionBase *s) { 266981ad6265SDimitry Andric if (s->type != SHT_LLVM_SYMPART) 267081ad6265SDimitry Andric return false; 26711fd87a68SDimitry Andric invokeELFT(readSymbolPartitionSection, s); 26720b57cec5SDimitry Andric return true; 267381ad6265SDimitry Andric }); 26740b57cec5SDimitry Andric } 26750b57cec5SDimitry Andric // We do not want to emit debug sections if --strip-all 2676349cc55cSDimitry Andric // or --strip-debug are given. 267781ad6265SDimitry Andric if (config->strip != StripPolicy::None) { 267881ad6265SDimitry Andric llvm::erase_if(inputSections, [](InputSectionBase *s) { 2679d65cd7a5SDimitry Andric if (isDebugSection(*s)) 2680d65cd7a5SDimitry Andric return true; 2681d65cd7a5SDimitry Andric if (auto *isec = dyn_cast<InputSection>(s)) 2682d65cd7a5SDimitry Andric if (InputSectionBase *rel = isec->getRelocatedSection()) 2683d65cd7a5SDimitry Andric if (isDebugSection(*rel)) 2684d65cd7a5SDimitry Andric return true; 2685d65cd7a5SDimitry Andric 2686d65cd7a5SDimitry Andric return false; 26870b57cec5SDimitry Andric }); 2688e8d8bef9SDimitry Andric } 268981ad6265SDimitry Andric } 2690e8d8bef9SDimitry Andric 2691e8d8bef9SDimitry Andric // Since we now have a complete set of input files, we can create 2692e8d8bef9SDimitry Andric // a .d file to record build dependencies. 2693e8d8bef9SDimitry Andric if (!config->dependencyFile.empty()) 2694e8d8bef9SDimitry Andric writeDependencyFile(); 26950b57cec5SDimitry Andric 26960b57cec5SDimitry Andric // Now that the number of partitions is fixed, save a pointer to the main 26970b57cec5SDimitry Andric // partition. 26980b57cec5SDimitry Andric mainPart = &partitions[0]; 26990b57cec5SDimitry Andric 27000b57cec5SDimitry Andric // Read .note.gnu.property sections from input object files which 27010b57cec5SDimitry Andric // contain a hint to tweak linker's and loader's behaviors. 27021fd87a68SDimitry Andric config->andFeatures = getAndFeatures(); 27030b57cec5SDimitry Andric 27040b57cec5SDimitry Andric // The Target instance handles target-specific stuff, such as applying 27050b57cec5SDimitry Andric // relocations or writing a PLT section. It also contains target-dependent 27060b57cec5SDimitry Andric // values such as a default image base address. 27070b57cec5SDimitry Andric target = getTarget(); 27080b57cec5SDimitry Andric 27090b57cec5SDimitry Andric config->eflags = target->calcEFlags(); 27100b57cec5SDimitry Andric // maxPageSize (sometimes called abi page size) is the maximum page size that 27110b57cec5SDimitry Andric // the output can be run on. For example if the OS can use 4k or 64k page 27120b57cec5SDimitry Andric // sizes then maxPageSize must be 64k for the output to be useable on both. 27130b57cec5SDimitry Andric // All important alignment decisions must use this value. 27140b57cec5SDimitry Andric config->maxPageSize = getMaxPageSize(args); 27150b57cec5SDimitry Andric // commonPageSize is the most common page size that the output will be run on. 27160b57cec5SDimitry Andric // For example if an OS can use 4k or 64k page sizes and 4k is more common 27170b57cec5SDimitry Andric // than 64k then commonPageSize is set to 4k. commonPageSize can be used for 27180b57cec5SDimitry Andric // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 27190b57cec5SDimitry Andric // is limited to writing trap instructions on the last executable segment. 27200b57cec5SDimitry Andric config->commonPageSize = getCommonPageSize(args); 27210b57cec5SDimitry Andric 27220b57cec5SDimitry Andric config->imageBase = getImageBase(args); 27230b57cec5SDimitry Andric 27240b57cec5SDimitry Andric if (config->emachine == EM_ARM) { 27250b57cec5SDimitry Andric // FIXME: These warnings can be removed when lld only uses these features 27260b57cec5SDimitry Andric // when the input objects have been compiled with an architecture that 27270b57cec5SDimitry Andric // supports them. 27280b57cec5SDimitry Andric if (config->armHasBlx == false) 27290b57cec5SDimitry Andric warn("lld uses blx instruction, no object with architecture supporting " 27300b57cec5SDimitry Andric "feature detected"); 27310b57cec5SDimitry Andric } 27320b57cec5SDimitry Andric 273385868e8aSDimitry Andric // This adds a .comment section containing a version string. 27340b57cec5SDimitry Andric if (!config->relocatable) 27350b57cec5SDimitry Andric inputSections.push_back(createCommentSection()); 27360b57cec5SDimitry Andric 273785868e8aSDimitry Andric // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection. 27381fd87a68SDimitry Andric invokeELFT(splitSections); 273985868e8aSDimitry Andric 274085868e8aSDimitry Andric // Garbage collection and removal of shared symbols from unused shared objects. 27411fd87a68SDimitry Andric invokeELFT(markLive); 274281ad6265SDimitry Andric demoteSharedAndLazySymbols(); 274385868e8aSDimitry Andric 274485868e8aSDimitry Andric // Make copies of any input sections that need to be copied into each 274585868e8aSDimitry Andric // partition. 274685868e8aSDimitry Andric copySectionsIntoPartitions(); 274785868e8aSDimitry Andric 274885868e8aSDimitry Andric // Create synthesized sections such as .got and .plt. This is called before 274985868e8aSDimitry Andric // processSectionCommands() so that they can be placed by SECTIONS commands. 27501fd87a68SDimitry Andric invokeELFT(createSyntheticSections); 275185868e8aSDimitry Andric 275285868e8aSDimitry Andric // Some input sections that are used for exception handling need to be moved 275385868e8aSDimitry Andric // into synthetic sections. Do that now so that they aren't assigned to 275485868e8aSDimitry Andric // output sections in the usual way. 275585868e8aSDimitry Andric if (!config->relocatable) 275685868e8aSDimitry Andric combineEhSections(); 275785868e8aSDimitry Andric 2758e8d8bef9SDimitry Andric { 2759e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Assign sections"); 2760e8d8bef9SDimitry Andric 276185868e8aSDimitry Andric // Create output sections described by SECTIONS commands. 276285868e8aSDimitry Andric script->processSectionCommands(); 276385868e8aSDimitry Andric 2764e8d8bef9SDimitry Andric // Linker scripts control how input sections are assigned to output 2765e8d8bef9SDimitry Andric // sections. Input sections that were not handled by scripts are called 2766e8d8bef9SDimitry Andric // "orphans", and they are assigned to output sections by the default rule. 2767e8d8bef9SDimitry Andric // Process that. 276885868e8aSDimitry Andric script->addOrphanSections(); 2769e8d8bef9SDimitry Andric } 2770e8d8bef9SDimitry Andric 2771e8d8bef9SDimitry Andric { 2772e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Merge/finalize input sections"); 277385868e8aSDimitry Andric 277485868e8aSDimitry Andric // Migrate InputSectionDescription::sectionBases to sections. This includes 277585868e8aSDimitry Andric // merging MergeInputSections into a single MergeSyntheticSection. From this 277685868e8aSDimitry Andric // point onwards InputSectionDescription::sections should be used instead of 277785868e8aSDimitry Andric // sectionBases. 27784824e7fdSDimitry Andric for (SectionCommand *cmd : script->sectionCommands) 277981ad6265SDimitry Andric if (auto *osd = dyn_cast<OutputDesc>(cmd)) 278081ad6265SDimitry Andric osd->osec.finalizeInputSections(); 2781e8d8bef9SDimitry Andric llvm::erase_if(inputSections, [](InputSectionBase *s) { 2782e8d8bef9SDimitry Andric return isa<MergeInputSection>(s); 2783e8d8bef9SDimitry Andric }); 2784e8d8bef9SDimitry Andric } 278585868e8aSDimitry Andric 278685868e8aSDimitry Andric // Two input sections with different output sections should not be folded. 278785868e8aSDimitry Andric // ICF runs after processSectionCommands() so that we know the output sections. 27880b57cec5SDimitry Andric if (config->icf != ICFLevel::None) { 27891fd87a68SDimitry Andric invokeELFT(findKeepUniqueSections, args); 27901fd87a68SDimitry Andric invokeELFT(doIcf); 27910b57cec5SDimitry Andric } 27920b57cec5SDimitry Andric 27930b57cec5SDimitry Andric // Read the callgraph now that we know what was gced or icfed 27940b57cec5SDimitry Andric if (config->callGraphProfileSort) { 27950b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) 27960b57cec5SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 27970b57cec5SDimitry Andric readCallGraph(*buffer); 27981fd87a68SDimitry Andric invokeELFT(readCallGraphsFromObjectFiles); 27990b57cec5SDimitry Andric } 28000b57cec5SDimitry Andric 28010b57cec5SDimitry Andric // Write the result to the file. 28021fd87a68SDimitry Andric invokeELFT(writeResult); 28030b57cec5SDimitry Andric } 2804