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" 5085868e8aSDimitry Andric #include "llvm/LTO/LTO.h" 510b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 520b57cec5SDimitry Andric #include "llvm/Support/Compression.h" 530b57cec5SDimitry Andric #include "llvm/Support/GlobPattern.h" 540b57cec5SDimitry Andric #include "llvm/Support/LEB128.h" 55*5ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h" 560b57cec5SDimitry Andric #include "llvm/Support/Path.h" 570b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h" 580b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h" 59*5ffd83dbSDimitry Andric #include "llvm/Support/TimeProfiler.h" 600b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 610b57cec5SDimitry Andric #include <cstdlib> 620b57cec5SDimitry Andric #include <utility> 630b57cec5SDimitry Andric 640b57cec5SDimitry Andric using namespace llvm; 650b57cec5SDimitry Andric using namespace llvm::ELF; 660b57cec5SDimitry Andric using namespace llvm::object; 670b57cec5SDimitry Andric using namespace llvm::sys; 680b57cec5SDimitry Andric using namespace llvm::support; 69*5ffd83dbSDimitry Andric using namespace lld; 70*5ffd83dbSDimitry Andric using namespace lld::elf; 710b57cec5SDimitry Andric 72*5ffd83dbSDimitry Andric Configuration *elf::config; 73*5ffd83dbSDimitry Andric LinkerDriver *elf::driver; 740b57cec5SDimitry Andric 750b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args); 760b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args); 770b57cec5SDimitry Andric 78*5ffd83dbSDimitry Andric bool elf::link(ArrayRef<const char *> args, bool canExitEarly, 79*5ffd83dbSDimitry Andric raw_ostream &stdoutOS, raw_ostream &stderrOS) { 80480093f4SDimitry Andric lld::stdoutOS = &stdoutOS; 81480093f4SDimitry Andric lld::stderrOS = &stderrOS; 82480093f4SDimitry Andric 830b57cec5SDimitry Andric errorHandler().logName = args::getFilenameWithoutExe(args[0]); 840b57cec5SDimitry Andric errorHandler().errorLimitExceededMsg = 850b57cec5SDimitry Andric "too many errors emitted, stopping now (use " 860b57cec5SDimitry Andric "-error-limit=0 to see all errors)"; 870b57cec5SDimitry Andric errorHandler().exitEarly = canExitEarly; 88480093f4SDimitry Andric stderrOS.enable_colors(stderrOS.has_colors()); 890b57cec5SDimitry Andric 900b57cec5SDimitry Andric inputSections.clear(); 910b57cec5SDimitry Andric outputSections.clear(); 92*5ffd83dbSDimitry Andric archiveFiles.clear(); 930b57cec5SDimitry Andric binaryFiles.clear(); 940b57cec5SDimitry Andric bitcodeFiles.clear(); 95*5ffd83dbSDimitry Andric lazyObjFiles.clear(); 960b57cec5SDimitry Andric objectFiles.clear(); 970b57cec5SDimitry Andric sharedFiles.clear(); 98*5ffd83dbSDimitry Andric backwardReferences.clear(); 990b57cec5SDimitry Andric 1000b57cec5SDimitry Andric config = make<Configuration>(); 1010b57cec5SDimitry Andric driver = make<LinkerDriver>(); 1020b57cec5SDimitry Andric script = make<LinkerScript>(); 1030b57cec5SDimitry Andric symtab = make<SymbolTable>(); 1040b57cec5SDimitry Andric 1050b57cec5SDimitry Andric tar = nullptr; 1060b57cec5SDimitry Andric memset(&in, 0, sizeof(in)); 1070b57cec5SDimitry Andric 1080b57cec5SDimitry Andric partitions = {Partition()}; 1090b57cec5SDimitry Andric 1100b57cec5SDimitry Andric SharedFile::vernauxNum = 0; 1110b57cec5SDimitry Andric 1120b57cec5SDimitry Andric config->progName = args[0]; 1130b57cec5SDimitry Andric 1140b57cec5SDimitry Andric driver->main(args); 1150b57cec5SDimitry Andric 1160b57cec5SDimitry Andric // Exit immediately if we don't need to return to the caller. 1170b57cec5SDimitry Andric // This saves time because the overhead of calling destructors 1180b57cec5SDimitry Andric // for all globally-allocated objects is not negligible. 1190b57cec5SDimitry Andric if (canExitEarly) 1200b57cec5SDimitry Andric exitLld(errorCount() ? 1 : 0); 1210b57cec5SDimitry Andric 1220b57cec5SDimitry Andric freeArena(); 1230b57cec5SDimitry Andric return !errorCount(); 1240b57cec5SDimitry Andric } 1250b57cec5SDimitry Andric 1260b57cec5SDimitry Andric // Parses a linker -m option. 1270b57cec5SDimitry Andric static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) { 1280b57cec5SDimitry Andric uint8_t osabi = 0; 1290b57cec5SDimitry Andric StringRef s = emul; 1300b57cec5SDimitry Andric if (s.endswith("_fbsd")) { 1310b57cec5SDimitry Andric s = s.drop_back(5); 1320b57cec5SDimitry Andric osabi = ELFOSABI_FREEBSD; 1330b57cec5SDimitry Andric } 1340b57cec5SDimitry Andric 1350b57cec5SDimitry Andric std::pair<ELFKind, uint16_t> ret = 1360b57cec5SDimitry Andric StringSwitch<std::pair<ELFKind, uint16_t>>(s) 1370b57cec5SDimitry Andric .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec", 1380b57cec5SDimitry Andric {ELF64LEKind, EM_AARCH64}) 1390b57cec5SDimitry Andric .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 1400b57cec5SDimitry Andric .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 1410b57cec5SDimitry Andric .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 1420b57cec5SDimitry Andric .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 1430b57cec5SDimitry Andric .Case("elf32lriscv", {ELF32LEKind, EM_RISCV}) 1440b57cec5SDimitry Andric .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC}) 1450b57cec5SDimitry Andric .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 1460b57cec5SDimitry Andric .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 1470b57cec5SDimitry Andric .Case("elf64lriscv", {ELF64LEKind, EM_RISCV}) 1480b57cec5SDimitry Andric .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 1490b57cec5SDimitry Andric .Case("elf64lppc", {ELF64LEKind, EM_PPC64}) 1500b57cec5SDimitry Andric .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 1510b57cec5SDimitry Andric .Case("elf_i386", {ELF32LEKind, EM_386}) 1520b57cec5SDimitry Andric .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 153*5ffd83dbSDimitry Andric .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9}) 1540b57cec5SDimitry Andric .Default({ELFNoneKind, EM_NONE}); 1550b57cec5SDimitry Andric 1560b57cec5SDimitry Andric if (ret.first == ELFNoneKind) 1570b57cec5SDimitry Andric error("unknown emulation: " + emul); 1580b57cec5SDimitry Andric return std::make_tuple(ret.first, ret.second, osabi); 1590b57cec5SDimitry Andric } 1600b57cec5SDimitry Andric 1610b57cec5SDimitry Andric // Returns slices of MB by parsing MB as an archive file. 1620b57cec5SDimitry Andric // Each slice consists of a member file in the archive. 1630b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 1640b57cec5SDimitry Andric MemoryBufferRef mb) { 1650b57cec5SDimitry Andric std::unique_ptr<Archive> file = 1660b57cec5SDimitry Andric CHECK(Archive::create(mb), 1670b57cec5SDimitry Andric mb.getBufferIdentifier() + ": failed to parse archive"); 1680b57cec5SDimitry Andric 1690b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> v; 1700b57cec5SDimitry Andric Error err = Error::success(); 1710b57cec5SDimitry Andric bool addToTar = file->isThin() && tar; 172480093f4SDimitry Andric for (const Archive::Child &c : file->children(err)) { 1730b57cec5SDimitry Andric MemoryBufferRef mbref = 1740b57cec5SDimitry Andric CHECK(c.getMemoryBufferRef(), 1750b57cec5SDimitry Andric mb.getBufferIdentifier() + 1760b57cec5SDimitry Andric ": could not get the buffer for a child of the archive"); 1770b57cec5SDimitry Andric if (addToTar) 1780b57cec5SDimitry Andric tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer()); 1790b57cec5SDimitry Andric v.push_back(std::make_pair(mbref, c.getChildOffset())); 1800b57cec5SDimitry Andric } 1810b57cec5SDimitry Andric if (err) 1820b57cec5SDimitry Andric fatal(mb.getBufferIdentifier() + ": Archive::children failed: " + 1830b57cec5SDimitry Andric toString(std::move(err))); 1840b57cec5SDimitry Andric 1850b57cec5SDimitry Andric // Take ownership of memory buffers created for members of thin archives. 1860b57cec5SDimitry Andric for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers()) 1870b57cec5SDimitry Andric make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); 1880b57cec5SDimitry Andric 1890b57cec5SDimitry Andric return v; 1900b57cec5SDimitry Andric } 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric // Opens a file and create a file object. Path has to be resolved already. 1930b57cec5SDimitry Andric void LinkerDriver::addFile(StringRef path, bool withLOption) { 1940b57cec5SDimitry Andric using namespace sys::fs; 1950b57cec5SDimitry Andric 1960b57cec5SDimitry Andric Optional<MemoryBufferRef> buffer = readFile(path); 1970b57cec5SDimitry Andric if (!buffer.hasValue()) 1980b57cec5SDimitry Andric return; 1990b57cec5SDimitry Andric MemoryBufferRef mbref = *buffer; 2000b57cec5SDimitry Andric 2010b57cec5SDimitry Andric if (config->formatBinary) { 2020b57cec5SDimitry Andric files.push_back(make<BinaryFile>(mbref)); 2030b57cec5SDimitry Andric return; 2040b57cec5SDimitry Andric } 2050b57cec5SDimitry Andric 2060b57cec5SDimitry Andric switch (identify_magic(mbref.getBuffer())) { 2070b57cec5SDimitry Andric case file_magic::unknown: 2080b57cec5SDimitry Andric readLinkerScript(mbref); 2090b57cec5SDimitry Andric return; 2100b57cec5SDimitry Andric case file_magic::archive: { 2110b57cec5SDimitry Andric // Handle -whole-archive. 2120b57cec5SDimitry Andric if (inWholeArchive) { 2130b57cec5SDimitry Andric for (const auto &p : getArchiveMembers(mbref)) 2140b57cec5SDimitry Andric files.push_back(createObjectFile(p.first, path, p.second)); 2150b57cec5SDimitry Andric return; 2160b57cec5SDimitry Andric } 2170b57cec5SDimitry Andric 2180b57cec5SDimitry Andric std::unique_ptr<Archive> file = 2190b57cec5SDimitry Andric CHECK(Archive::create(mbref), path + ": failed to parse archive"); 2200b57cec5SDimitry Andric 2210b57cec5SDimitry Andric // If an archive file has no symbol table, it is likely that a user 2220b57cec5SDimitry Andric // is attempting LTO and using a default ar command that doesn't 2230b57cec5SDimitry Andric // understand the LLVM bitcode file. It is a pretty common error, so 2240b57cec5SDimitry Andric // we'll handle it as if it had a symbol table. 2250b57cec5SDimitry Andric if (!file->isEmpty() && !file->hasSymbolTable()) { 2260b57cec5SDimitry Andric // Check if all members are bitcode files. If not, ignore, which is the 2270b57cec5SDimitry Andric // default action without the LTO hack described above. 2280b57cec5SDimitry Andric for (const std::pair<MemoryBufferRef, uint64_t> &p : 2290b57cec5SDimitry Andric getArchiveMembers(mbref)) 2300b57cec5SDimitry Andric if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) { 2310b57cec5SDimitry Andric error(path + ": archive has no index; run ranlib to add one"); 2320b57cec5SDimitry Andric return; 2330b57cec5SDimitry Andric } 2340b57cec5SDimitry Andric 2350b57cec5SDimitry Andric for (const std::pair<MemoryBufferRef, uint64_t> &p : 2360b57cec5SDimitry Andric getArchiveMembers(mbref)) 2370b57cec5SDimitry Andric files.push_back(make<LazyObjFile>(p.first, path, p.second)); 2380b57cec5SDimitry Andric return; 2390b57cec5SDimitry Andric } 2400b57cec5SDimitry Andric 2410b57cec5SDimitry Andric // Handle the regular case. 2420b57cec5SDimitry Andric files.push_back(make<ArchiveFile>(std::move(file))); 2430b57cec5SDimitry Andric return; 2440b57cec5SDimitry Andric } 2450b57cec5SDimitry Andric case file_magic::elf_shared_object: 2460b57cec5SDimitry Andric if (config->isStatic || config->relocatable) { 2470b57cec5SDimitry Andric error("attempted static link of dynamic object " + path); 2480b57cec5SDimitry Andric return; 2490b57cec5SDimitry Andric } 2500b57cec5SDimitry Andric 2510b57cec5SDimitry Andric // DSOs usually have DT_SONAME tags in their ELF headers, and the 2520b57cec5SDimitry Andric // sonames are used to identify DSOs. But if they are missing, 2530b57cec5SDimitry Andric // they are identified by filenames. We don't know whether the new 2540b57cec5SDimitry Andric // file has a DT_SONAME or not because we haven't parsed it yet. 2550b57cec5SDimitry Andric // Here, we set the default soname for the file because we might 2560b57cec5SDimitry Andric // need it later. 2570b57cec5SDimitry Andric // 2580b57cec5SDimitry Andric // If a file was specified by -lfoo, the directory part is not 2590b57cec5SDimitry Andric // significant, as a user did not specify it. This behavior is 2600b57cec5SDimitry Andric // compatible with GNU. 2610b57cec5SDimitry Andric files.push_back( 2620b57cec5SDimitry Andric make<SharedFile>(mbref, withLOption ? path::filename(path) : path)); 2630b57cec5SDimitry Andric return; 2640b57cec5SDimitry Andric case file_magic::bitcode: 2650b57cec5SDimitry Andric case file_magic::elf_relocatable: 2660b57cec5SDimitry Andric if (inLib) 2670b57cec5SDimitry Andric files.push_back(make<LazyObjFile>(mbref, "", 0)); 2680b57cec5SDimitry Andric else 2690b57cec5SDimitry Andric files.push_back(createObjectFile(mbref)); 2700b57cec5SDimitry Andric break; 2710b57cec5SDimitry Andric default: 2720b57cec5SDimitry Andric error(path + ": unknown file type"); 2730b57cec5SDimitry Andric } 2740b57cec5SDimitry Andric } 2750b57cec5SDimitry Andric 2760b57cec5SDimitry Andric // Add a given library by searching it from input search paths. 2770b57cec5SDimitry Andric void LinkerDriver::addLibrary(StringRef name) { 2780b57cec5SDimitry Andric if (Optional<std::string> path = searchLibrary(name)) 2790b57cec5SDimitry Andric addFile(*path, /*withLOption=*/true); 2800b57cec5SDimitry Andric else 2810b57cec5SDimitry Andric error("unable to find library -l" + name); 2820b57cec5SDimitry Andric } 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric // This function is called on startup. We need this for LTO since 2850b57cec5SDimitry Andric // LTO calls LLVM functions to compile bitcode files to native code. 2860b57cec5SDimitry Andric // Technically this can be delayed until we read bitcode files, but 2870b57cec5SDimitry Andric // we don't bother to do lazily because the initialization is fast. 2880b57cec5SDimitry Andric static void initLLVM() { 2890b57cec5SDimitry Andric InitializeAllTargets(); 2900b57cec5SDimitry Andric InitializeAllTargetMCs(); 2910b57cec5SDimitry Andric InitializeAllAsmPrinters(); 2920b57cec5SDimitry Andric InitializeAllAsmParsers(); 2930b57cec5SDimitry Andric } 2940b57cec5SDimitry Andric 2950b57cec5SDimitry Andric // Some command line options or some combinations of them are not allowed. 2960b57cec5SDimitry Andric // This function checks for such errors. 2970b57cec5SDimitry Andric static void checkOptions() { 2980b57cec5SDimitry Andric // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 2990b57cec5SDimitry Andric // table which is a relatively new feature. 3000b57cec5SDimitry Andric if (config->emachine == EM_MIPS && config->gnuHash) 3010b57cec5SDimitry Andric error("the .gnu.hash section is not compatible with the MIPS target"); 3020b57cec5SDimitry Andric 3030b57cec5SDimitry Andric if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64) 3040b57cec5SDimitry Andric error("--fix-cortex-a53-843419 is only supported on AArch64 targets"); 3050b57cec5SDimitry Andric 30685868e8aSDimitry Andric if (config->fixCortexA8 && config->emachine != EM_ARM) 30785868e8aSDimitry Andric error("--fix-cortex-a8 is only supported on ARM targets"); 30885868e8aSDimitry Andric 3090b57cec5SDimitry Andric if (config->tocOptimize && config->emachine != EM_PPC64) 3100b57cec5SDimitry Andric error("--toc-optimize is only supported on the PowerPC64 target"); 3110b57cec5SDimitry Andric 3120b57cec5SDimitry Andric if (config->pie && config->shared) 3130b57cec5SDimitry Andric error("-shared and -pie may not be used together"); 3140b57cec5SDimitry Andric 3150b57cec5SDimitry Andric if (!config->shared && !config->filterList.empty()) 3160b57cec5SDimitry Andric error("-F may not be used without -shared"); 3170b57cec5SDimitry Andric 3180b57cec5SDimitry Andric if (!config->shared && !config->auxiliaryList.empty()) 3190b57cec5SDimitry Andric error("-f may not be used without -shared"); 3200b57cec5SDimitry Andric 3210b57cec5SDimitry Andric if (!config->relocatable && !config->defineCommon) 3220b57cec5SDimitry Andric error("-no-define-common not supported in non relocatable output"); 3230b57cec5SDimitry Andric 32485868e8aSDimitry Andric if (config->strip == StripPolicy::All && config->emitRelocs) 32585868e8aSDimitry Andric error("--strip-all and --emit-relocs may not be used together"); 32685868e8aSDimitry Andric 3270b57cec5SDimitry Andric if (config->zText && config->zIfuncNoplt) 3280b57cec5SDimitry Andric error("-z text and -z ifunc-noplt may not be used together"); 3290b57cec5SDimitry Andric 3300b57cec5SDimitry Andric if (config->relocatable) { 3310b57cec5SDimitry Andric if (config->shared) 3320b57cec5SDimitry Andric error("-r and -shared may not be used together"); 3330b57cec5SDimitry Andric if (config->gcSections) 3340b57cec5SDimitry Andric error("-r and --gc-sections may not be used together"); 3350b57cec5SDimitry Andric if (config->gdbIndex) 3360b57cec5SDimitry Andric error("-r and --gdb-index may not be used together"); 3370b57cec5SDimitry Andric if (config->icf != ICFLevel::None) 3380b57cec5SDimitry Andric error("-r and --icf may not be used together"); 3390b57cec5SDimitry Andric if (config->pie) 3400b57cec5SDimitry Andric error("-r and -pie may not be used together"); 34185868e8aSDimitry Andric if (config->exportDynamic) 34285868e8aSDimitry Andric error("-r and --export-dynamic may not be used together"); 3430b57cec5SDimitry Andric } 3440b57cec5SDimitry Andric 3450b57cec5SDimitry Andric if (config->executeOnly) { 3460b57cec5SDimitry Andric if (config->emachine != EM_AARCH64) 3470b57cec5SDimitry Andric error("-execute-only is only supported on AArch64 targets"); 3480b57cec5SDimitry Andric 3490b57cec5SDimitry Andric if (config->singleRoRx && !script->hasSectionsCommand) 3500b57cec5SDimitry Andric error("-execute-only and -no-rosegment cannot be used together"); 3510b57cec5SDimitry Andric } 3520b57cec5SDimitry Andric 353480093f4SDimitry Andric if (config->zRetpolineplt && config->zForceIbt) 354480093f4SDimitry Andric error("-z force-ibt may not be used with -z retpolineplt"); 3550b57cec5SDimitry Andric 3560b57cec5SDimitry Andric if (config->emachine != EM_AARCH64) { 357*5ffd83dbSDimitry Andric if (config->zPacPlt) 358480093f4SDimitry Andric error("-z pac-plt only supported on AArch64"); 359*5ffd83dbSDimitry Andric if (config->zForceBti) 360480093f4SDimitry Andric error("-z force-bti only supported on AArch64"); 3610b57cec5SDimitry Andric } 3620b57cec5SDimitry Andric } 3630b57cec5SDimitry Andric 3640b57cec5SDimitry Andric static const char *getReproduceOption(opt::InputArgList &args) { 3650b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 3660b57cec5SDimitry Andric return arg->getValue(); 3670b57cec5SDimitry Andric return getenv("LLD_REPRODUCE"); 3680b57cec5SDimitry Andric } 3690b57cec5SDimitry Andric 3700b57cec5SDimitry Andric static bool hasZOption(opt::InputArgList &args, StringRef key) { 3710b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_z)) 3720b57cec5SDimitry Andric if (key == arg->getValue()) 3730b57cec5SDimitry Andric return true; 3740b57cec5SDimitry Andric return false; 3750b57cec5SDimitry Andric } 3760b57cec5SDimitry Andric 3770b57cec5SDimitry Andric static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2, 3780b57cec5SDimitry Andric bool Default) { 3790b57cec5SDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 3800b57cec5SDimitry Andric if (k1 == arg->getValue()) 3810b57cec5SDimitry Andric return true; 3820b57cec5SDimitry Andric if (k2 == arg->getValue()) 3830b57cec5SDimitry Andric return false; 3840b57cec5SDimitry Andric } 3850b57cec5SDimitry Andric return Default; 3860b57cec5SDimitry Andric } 3870b57cec5SDimitry Andric 38885868e8aSDimitry Andric static SeparateSegmentKind getZSeparate(opt::InputArgList &args) { 38985868e8aSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 39085868e8aSDimitry Andric StringRef v = arg->getValue(); 39185868e8aSDimitry Andric if (v == "noseparate-code") 39285868e8aSDimitry Andric return SeparateSegmentKind::None; 39385868e8aSDimitry Andric if (v == "separate-code") 39485868e8aSDimitry Andric return SeparateSegmentKind::Code; 39585868e8aSDimitry Andric if (v == "separate-loadable-segments") 39685868e8aSDimitry Andric return SeparateSegmentKind::Loadable; 39785868e8aSDimitry Andric } 39885868e8aSDimitry Andric return SeparateSegmentKind::None; 39985868e8aSDimitry Andric } 40085868e8aSDimitry Andric 401480093f4SDimitry Andric static GnuStackKind getZGnuStack(opt::InputArgList &args) { 402480093f4SDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 403480093f4SDimitry Andric if (StringRef("execstack") == arg->getValue()) 404480093f4SDimitry Andric return GnuStackKind::Exec; 405480093f4SDimitry Andric if (StringRef("noexecstack") == arg->getValue()) 406480093f4SDimitry Andric return GnuStackKind::NoExec; 407480093f4SDimitry Andric if (StringRef("nognustack") == arg->getValue()) 408480093f4SDimitry Andric return GnuStackKind::None; 409480093f4SDimitry Andric } 410480093f4SDimitry Andric 411480093f4SDimitry Andric return GnuStackKind::NoExec; 412480093f4SDimitry Andric } 413480093f4SDimitry Andric 414*5ffd83dbSDimitry Andric static uint8_t getZStartStopVisibility(opt::InputArgList &args) { 415*5ffd83dbSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 416*5ffd83dbSDimitry Andric std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 417*5ffd83dbSDimitry Andric if (kv.first == "start-stop-visibility") { 418*5ffd83dbSDimitry Andric if (kv.second == "default") 419*5ffd83dbSDimitry Andric return STV_DEFAULT; 420*5ffd83dbSDimitry Andric else if (kv.second == "internal") 421*5ffd83dbSDimitry Andric return STV_INTERNAL; 422*5ffd83dbSDimitry Andric else if (kv.second == "hidden") 423*5ffd83dbSDimitry Andric return STV_HIDDEN; 424*5ffd83dbSDimitry Andric else if (kv.second == "protected") 425*5ffd83dbSDimitry Andric return STV_PROTECTED; 426*5ffd83dbSDimitry Andric error("unknown -z start-stop-visibility= value: " + StringRef(kv.second)); 427*5ffd83dbSDimitry Andric } 428*5ffd83dbSDimitry Andric } 429*5ffd83dbSDimitry Andric return STV_PROTECTED; 430*5ffd83dbSDimitry Andric } 431*5ffd83dbSDimitry Andric 4320b57cec5SDimitry Andric static bool isKnownZFlag(StringRef s) { 4330b57cec5SDimitry Andric return s == "combreloc" || s == "copyreloc" || s == "defs" || 434480093f4SDimitry Andric s == "execstack" || s == "force-bti" || s == "force-ibt" || 435480093f4SDimitry Andric s == "global" || s == "hazardplt" || s == "ifunc-noplt" || 436480093f4SDimitry Andric s == "initfirst" || s == "interpose" || 4370b57cec5SDimitry Andric s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" || 43885868e8aSDimitry Andric s == "separate-code" || s == "separate-loadable-segments" || 4390b57cec5SDimitry Andric s == "nocombreloc" || s == "nocopyreloc" || s == "nodefaultlib" || 4400b57cec5SDimitry Andric s == "nodelete" || s == "nodlopen" || s == "noexecstack" || 441480093f4SDimitry Andric s == "nognustack" || s == "nokeep-text-section-prefix" || 442480093f4SDimitry Andric s == "norelro" || s == "noseparate-code" || s == "notext" || 443*5ffd83dbSDimitry Andric s == "now" || s == "origin" || s == "pac-plt" || s == "rel" || 444*5ffd83dbSDimitry Andric s == "rela" || s == "relro" || s == "retpolineplt" || 445*5ffd83dbSDimitry Andric s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" || 446*5ffd83dbSDimitry Andric s == "wxneeded" || s.startswith("common-page-size=") || 447*5ffd83dbSDimitry Andric s.startswith("dead-reloc-in-nonalloc=") || 448*5ffd83dbSDimitry Andric s.startswith("max-page-size=") || s.startswith("stack-size=") || 449*5ffd83dbSDimitry Andric s.startswith("start-stop-visibility="); 4500b57cec5SDimitry Andric } 4510b57cec5SDimitry Andric 4520b57cec5SDimitry Andric // Report an error for an unknown -z option. 4530b57cec5SDimitry Andric static void checkZOptions(opt::InputArgList &args) { 4540b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_z)) 4550b57cec5SDimitry Andric if (!isKnownZFlag(arg->getValue())) 4560b57cec5SDimitry Andric error("unknown -z value: " + StringRef(arg->getValue())); 4570b57cec5SDimitry Andric } 4580b57cec5SDimitry Andric 4590b57cec5SDimitry Andric void LinkerDriver::main(ArrayRef<const char *> argsArr) { 4600b57cec5SDimitry Andric ELFOptTable parser; 4610b57cec5SDimitry Andric opt::InputArgList args = parser.parse(argsArr.slice(1)); 4620b57cec5SDimitry Andric 4630b57cec5SDimitry Andric // Interpret this flag early because error() depends on them. 4640b57cec5SDimitry Andric errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20); 4650b57cec5SDimitry Andric checkZOptions(args); 4660b57cec5SDimitry Andric 4670b57cec5SDimitry Andric // Handle -help 4680b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 4690b57cec5SDimitry Andric printHelp(); 4700b57cec5SDimitry Andric return; 4710b57cec5SDimitry Andric } 4720b57cec5SDimitry Andric 4730b57cec5SDimitry Andric // Handle -v or -version. 4740b57cec5SDimitry Andric // 4750b57cec5SDimitry Andric // A note about "compatible with GNU linkers" message: this is a hack for 4760b57cec5SDimitry Andric // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and 4770b57cec5SDimitry Andric // still the newest version in March 2017) or earlier to recognize LLD as 4780b57cec5SDimitry Andric // a GNU compatible linker. As long as an output for the -v option 4790b57cec5SDimitry Andric // contains "GNU" or "with BFD", they recognize us as GNU-compatible. 4800b57cec5SDimitry Andric // 4810b57cec5SDimitry Andric // This is somewhat ugly hack, but in reality, we had no choice other 4820b57cec5SDimitry Andric // than doing this. Considering the very long release cycle of Libtool, 4830b57cec5SDimitry Andric // it is not easy to improve it to recognize LLD as a GNU compatible 4840b57cec5SDimitry Andric // linker in a timely manner. Even if we can make it, there are still a 4850b57cec5SDimitry Andric // lot of "configure" scripts out there that are generated by old version 4860b57cec5SDimitry Andric // of Libtool. We cannot convince every software developer to migrate to 4870b57cec5SDimitry Andric // the latest version and re-generate scripts. So we have this hack. 4880b57cec5SDimitry Andric if (args.hasArg(OPT_v) || args.hasArg(OPT_version)) 4890b57cec5SDimitry Andric message(getLLDVersion() + " (compatible with GNU linkers)"); 4900b57cec5SDimitry Andric 4910b57cec5SDimitry Andric if (const char *path = getReproduceOption(args)) { 4920b57cec5SDimitry Andric // Note that --reproduce is a debug option so you can ignore it 4930b57cec5SDimitry Andric // if you are trying to understand the whole picture of the code. 4940b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 4950b57cec5SDimitry Andric TarWriter::create(path, path::stem(path)); 4960b57cec5SDimitry Andric if (errOrWriter) { 4970b57cec5SDimitry Andric tar = std::move(*errOrWriter); 4980b57cec5SDimitry Andric tar->append("response.txt", createResponseFile(args)); 4990b57cec5SDimitry Andric tar->append("version.txt", getLLDVersion() + "\n"); 5000b57cec5SDimitry Andric } else { 5010b57cec5SDimitry Andric error("--reproduce: " + toString(errOrWriter.takeError())); 5020b57cec5SDimitry Andric } 5030b57cec5SDimitry Andric } 5040b57cec5SDimitry Andric 5050b57cec5SDimitry Andric readConfigs(args); 5060b57cec5SDimitry Andric 5070b57cec5SDimitry Andric // The behavior of -v or --version is a bit strange, but this is 5080b57cec5SDimitry Andric // needed for compatibility with GNU linkers. 5090b57cec5SDimitry Andric if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT)) 5100b57cec5SDimitry Andric return; 5110b57cec5SDimitry Andric if (args.hasArg(OPT_version)) 5120b57cec5SDimitry Andric return; 5130b57cec5SDimitry Andric 514*5ffd83dbSDimitry Andric // Initialize time trace profiler. 515*5ffd83dbSDimitry Andric if (config->timeTraceEnabled) 516*5ffd83dbSDimitry Andric timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName); 517*5ffd83dbSDimitry Andric 518*5ffd83dbSDimitry Andric { 519*5ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("ExecuteLinker"); 520*5ffd83dbSDimitry Andric 5210b57cec5SDimitry Andric initLLVM(); 5220b57cec5SDimitry Andric createFiles(args); 5230b57cec5SDimitry Andric if (errorCount()) 5240b57cec5SDimitry Andric return; 5250b57cec5SDimitry Andric 5260b57cec5SDimitry Andric inferMachineType(); 5270b57cec5SDimitry Andric setConfigs(args); 5280b57cec5SDimitry Andric checkOptions(); 5290b57cec5SDimitry Andric if (errorCount()) 5300b57cec5SDimitry Andric return; 5310b57cec5SDimitry Andric 5320b57cec5SDimitry Andric // The Target instance handles target-specific stuff, such as applying 5330b57cec5SDimitry Andric // relocations or writing a PLT section. It also contains target-dependent 5340b57cec5SDimitry Andric // values such as a default image base address. 5350b57cec5SDimitry Andric target = getTarget(); 5360b57cec5SDimitry Andric 5370b57cec5SDimitry Andric switch (config->ekind) { 5380b57cec5SDimitry Andric case ELF32LEKind: 5390b57cec5SDimitry Andric link<ELF32LE>(args); 540*5ffd83dbSDimitry Andric break; 5410b57cec5SDimitry Andric case ELF32BEKind: 5420b57cec5SDimitry Andric link<ELF32BE>(args); 543*5ffd83dbSDimitry Andric break; 5440b57cec5SDimitry Andric case ELF64LEKind: 5450b57cec5SDimitry Andric link<ELF64LE>(args); 546*5ffd83dbSDimitry Andric break; 5470b57cec5SDimitry Andric case ELF64BEKind: 5480b57cec5SDimitry Andric link<ELF64BE>(args); 549*5ffd83dbSDimitry Andric break; 5500b57cec5SDimitry Andric default: 5510b57cec5SDimitry Andric llvm_unreachable("unknown Config->EKind"); 5520b57cec5SDimitry Andric } 5530b57cec5SDimitry Andric } 5540b57cec5SDimitry Andric 555*5ffd83dbSDimitry Andric if (config->timeTraceEnabled) { 556*5ffd83dbSDimitry Andric if (auto E = timeTraceProfilerWrite(args.getLastArgValue(OPT_time_trace_file_eq).str(), 557*5ffd83dbSDimitry Andric config->outputFile)) { 558*5ffd83dbSDimitry Andric handleAllErrors(std::move(E), [&](const StringError &SE) { 559*5ffd83dbSDimitry Andric error(SE.getMessage()); 560*5ffd83dbSDimitry Andric }); 561*5ffd83dbSDimitry Andric return; 562*5ffd83dbSDimitry Andric } 563*5ffd83dbSDimitry Andric 564*5ffd83dbSDimitry Andric timeTraceProfilerCleanup(); 565*5ffd83dbSDimitry Andric } 566*5ffd83dbSDimitry Andric } 567*5ffd83dbSDimitry Andric 5680b57cec5SDimitry Andric static std::string getRpath(opt::InputArgList &args) { 5690b57cec5SDimitry Andric std::vector<StringRef> v = args::getStrings(args, OPT_rpath); 5700b57cec5SDimitry Andric return llvm::join(v.begin(), v.end(), ":"); 5710b57cec5SDimitry Andric } 5720b57cec5SDimitry Andric 5730b57cec5SDimitry Andric // Determines what we should do if there are remaining unresolved 5740b57cec5SDimitry Andric // symbols after the name resolution. 5750b57cec5SDimitry Andric static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &args) { 5760b57cec5SDimitry Andric UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols, 5770b57cec5SDimitry Andric OPT_warn_unresolved_symbols, true) 5780b57cec5SDimitry Andric ? UnresolvedPolicy::ReportError 5790b57cec5SDimitry Andric : UnresolvedPolicy::Warn; 5800b57cec5SDimitry Andric 5810b57cec5SDimitry Andric // Process the last of -unresolved-symbols, -no-undefined or -z defs. 5820b57cec5SDimitry Andric for (auto *arg : llvm::reverse(args)) { 5830b57cec5SDimitry Andric switch (arg->getOption().getID()) { 5840b57cec5SDimitry Andric case OPT_unresolved_symbols: { 5850b57cec5SDimitry Andric StringRef s = arg->getValue(); 5860b57cec5SDimitry Andric if (s == "ignore-all" || s == "ignore-in-object-files") 5870b57cec5SDimitry Andric return UnresolvedPolicy::Ignore; 5880b57cec5SDimitry Andric if (s == "ignore-in-shared-libs" || s == "report-all") 5890b57cec5SDimitry Andric return errorOrWarn; 5900b57cec5SDimitry Andric error("unknown --unresolved-symbols value: " + s); 5910b57cec5SDimitry Andric continue; 5920b57cec5SDimitry Andric } 5930b57cec5SDimitry Andric case OPT_no_undefined: 5940b57cec5SDimitry Andric return errorOrWarn; 5950b57cec5SDimitry Andric case OPT_z: 5960b57cec5SDimitry Andric if (StringRef(arg->getValue()) == "defs") 5970b57cec5SDimitry Andric return errorOrWarn; 59885868e8aSDimitry Andric if (StringRef(arg->getValue()) == "undefs") 59985868e8aSDimitry Andric return UnresolvedPolicy::Ignore; 6000b57cec5SDimitry Andric continue; 6010b57cec5SDimitry Andric } 6020b57cec5SDimitry Andric } 6030b57cec5SDimitry Andric 6040b57cec5SDimitry Andric // -shared implies -unresolved-symbols=ignore-all because missing 6050b57cec5SDimitry Andric // symbols are likely to be resolved at runtime using other DSOs. 6060b57cec5SDimitry Andric if (config->shared) 6070b57cec5SDimitry Andric return UnresolvedPolicy::Ignore; 6080b57cec5SDimitry Andric return errorOrWarn; 6090b57cec5SDimitry Andric } 6100b57cec5SDimitry Andric 6110b57cec5SDimitry Andric static Target2Policy getTarget2(opt::InputArgList &args) { 6120b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_target2, "got-rel"); 6130b57cec5SDimitry Andric if (s == "rel") 6140b57cec5SDimitry Andric return Target2Policy::Rel; 6150b57cec5SDimitry Andric if (s == "abs") 6160b57cec5SDimitry Andric return Target2Policy::Abs; 6170b57cec5SDimitry Andric if (s == "got-rel") 6180b57cec5SDimitry Andric return Target2Policy::GotRel; 6190b57cec5SDimitry Andric error("unknown --target2 option: " + s); 6200b57cec5SDimitry Andric return Target2Policy::GotRel; 6210b57cec5SDimitry Andric } 6220b57cec5SDimitry Andric 6230b57cec5SDimitry Andric static bool isOutputFormatBinary(opt::InputArgList &args) { 6240b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_oformat, "elf"); 6250b57cec5SDimitry Andric if (s == "binary") 6260b57cec5SDimitry Andric return true; 6270b57cec5SDimitry Andric if (!s.startswith("elf")) 6280b57cec5SDimitry Andric error("unknown --oformat value: " + s); 6290b57cec5SDimitry Andric return false; 6300b57cec5SDimitry Andric } 6310b57cec5SDimitry Andric 6320b57cec5SDimitry Andric static DiscardPolicy getDiscard(opt::InputArgList &args) { 6330b57cec5SDimitry Andric auto *arg = 6340b57cec5SDimitry Andric args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 6350b57cec5SDimitry Andric if (!arg) 6360b57cec5SDimitry Andric return DiscardPolicy::Default; 6370b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_discard_all) 6380b57cec5SDimitry Andric return DiscardPolicy::All; 6390b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_discard_locals) 6400b57cec5SDimitry Andric return DiscardPolicy::Locals; 6410b57cec5SDimitry Andric return DiscardPolicy::None; 6420b57cec5SDimitry Andric } 6430b57cec5SDimitry Andric 6440b57cec5SDimitry Andric static StringRef getDynamicLinker(opt::InputArgList &args) { 6450b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 64655e4f9d5SDimitry Andric if (!arg) 6470b57cec5SDimitry Andric return ""; 64855e4f9d5SDimitry Andric if (arg->getOption().getID() == OPT_no_dynamic_linker) { 64955e4f9d5SDimitry Andric // --no-dynamic-linker suppresses undefined weak symbols in .dynsym 65055e4f9d5SDimitry Andric config->noDynamicLinker = true; 65155e4f9d5SDimitry Andric return ""; 65255e4f9d5SDimitry Andric } 6530b57cec5SDimitry Andric return arg->getValue(); 6540b57cec5SDimitry Andric } 6550b57cec5SDimitry Andric 6560b57cec5SDimitry Andric static ICFLevel getICF(opt::InputArgList &args) { 6570b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all); 6580b57cec5SDimitry Andric if (!arg || arg->getOption().getID() == OPT_icf_none) 6590b57cec5SDimitry Andric return ICFLevel::None; 6600b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_icf_safe) 6610b57cec5SDimitry Andric return ICFLevel::Safe; 6620b57cec5SDimitry Andric return ICFLevel::All; 6630b57cec5SDimitry Andric } 6640b57cec5SDimitry Andric 6650b57cec5SDimitry Andric static StripPolicy getStrip(opt::InputArgList &args) { 6660b57cec5SDimitry Andric if (args.hasArg(OPT_relocatable)) 6670b57cec5SDimitry Andric return StripPolicy::None; 6680b57cec5SDimitry Andric 6690b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug); 6700b57cec5SDimitry Andric if (!arg) 6710b57cec5SDimitry Andric return StripPolicy::None; 6720b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_strip_all) 6730b57cec5SDimitry Andric return StripPolicy::All; 6740b57cec5SDimitry Andric return StripPolicy::Debug; 6750b57cec5SDimitry Andric } 6760b57cec5SDimitry Andric 6770b57cec5SDimitry Andric static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args, 6780b57cec5SDimitry Andric const opt::Arg &arg) { 6790b57cec5SDimitry Andric uint64_t va = 0; 6800b57cec5SDimitry Andric if (s.startswith("0x")) 6810b57cec5SDimitry Andric s = s.drop_front(2); 6820b57cec5SDimitry Andric if (!to_integer(s, va, 16)) 6830b57cec5SDimitry Andric error("invalid argument: " + arg.getAsString(args)); 6840b57cec5SDimitry Andric return va; 6850b57cec5SDimitry Andric } 6860b57cec5SDimitry Andric 6870b57cec5SDimitry Andric static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) { 6880b57cec5SDimitry Andric StringMap<uint64_t> ret; 6890b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section_start)) { 6900b57cec5SDimitry Andric StringRef name; 6910b57cec5SDimitry Andric StringRef addr; 6920b57cec5SDimitry Andric std::tie(name, addr) = StringRef(arg->getValue()).split('='); 6930b57cec5SDimitry Andric ret[name] = parseSectionAddress(addr, args, *arg); 6940b57cec5SDimitry Andric } 6950b57cec5SDimitry Andric 6960b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Ttext)) 6970b57cec5SDimitry Andric ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg); 6980b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Tdata)) 6990b57cec5SDimitry Andric ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg); 7000b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Tbss)) 7010b57cec5SDimitry Andric ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg); 7020b57cec5SDimitry Andric return ret; 7030b57cec5SDimitry Andric } 7040b57cec5SDimitry Andric 7050b57cec5SDimitry Andric static SortSectionPolicy getSortSection(opt::InputArgList &args) { 7060b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_sort_section); 7070b57cec5SDimitry Andric if (s == "alignment") 7080b57cec5SDimitry Andric return SortSectionPolicy::Alignment; 7090b57cec5SDimitry Andric if (s == "name") 7100b57cec5SDimitry Andric return SortSectionPolicy::Name; 7110b57cec5SDimitry Andric if (!s.empty()) 7120b57cec5SDimitry Andric error("unknown --sort-section rule: " + s); 7130b57cec5SDimitry Andric return SortSectionPolicy::Default; 7140b57cec5SDimitry Andric } 7150b57cec5SDimitry Andric 7160b57cec5SDimitry Andric static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) { 7170b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_orphan_handling, "place"); 7180b57cec5SDimitry Andric if (s == "warn") 7190b57cec5SDimitry Andric return OrphanHandlingPolicy::Warn; 7200b57cec5SDimitry Andric if (s == "error") 7210b57cec5SDimitry Andric return OrphanHandlingPolicy::Error; 7220b57cec5SDimitry Andric if (s != "place") 7230b57cec5SDimitry Andric error("unknown --orphan-handling mode: " + s); 7240b57cec5SDimitry Andric return OrphanHandlingPolicy::Place; 7250b57cec5SDimitry Andric } 7260b57cec5SDimitry Andric 7270b57cec5SDimitry Andric // Parse --build-id or --build-id=<style>. We handle "tree" as a 7280b57cec5SDimitry Andric // synonym for "sha1" because all our hash functions including 7290b57cec5SDimitry Andric // -build-id=sha1 are actually tree hashes for performance reasons. 7300b57cec5SDimitry Andric static std::pair<BuildIdKind, std::vector<uint8_t>> 7310b57cec5SDimitry Andric getBuildId(opt::InputArgList &args) { 7320b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq); 7330b57cec5SDimitry Andric if (!arg) 7340b57cec5SDimitry Andric return {BuildIdKind::None, {}}; 7350b57cec5SDimitry Andric 7360b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_build_id) 7370b57cec5SDimitry Andric return {BuildIdKind::Fast, {}}; 7380b57cec5SDimitry Andric 7390b57cec5SDimitry Andric StringRef s = arg->getValue(); 7400b57cec5SDimitry Andric if (s == "fast") 7410b57cec5SDimitry Andric return {BuildIdKind::Fast, {}}; 7420b57cec5SDimitry Andric if (s == "md5") 7430b57cec5SDimitry Andric return {BuildIdKind::Md5, {}}; 7440b57cec5SDimitry Andric if (s == "sha1" || s == "tree") 7450b57cec5SDimitry Andric return {BuildIdKind::Sha1, {}}; 7460b57cec5SDimitry Andric if (s == "uuid") 7470b57cec5SDimitry Andric return {BuildIdKind::Uuid, {}}; 7480b57cec5SDimitry Andric if (s.startswith("0x")) 7490b57cec5SDimitry Andric return {BuildIdKind::Hexstring, parseHex(s.substr(2))}; 7500b57cec5SDimitry Andric 7510b57cec5SDimitry Andric if (s != "none") 7520b57cec5SDimitry Andric error("unknown --build-id style: " + s); 7530b57cec5SDimitry Andric return {BuildIdKind::None, {}}; 7540b57cec5SDimitry Andric } 7550b57cec5SDimitry Andric 7560b57cec5SDimitry Andric static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) { 7570b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none"); 7580b57cec5SDimitry Andric if (s == "android") 7590b57cec5SDimitry Andric return {true, false}; 7600b57cec5SDimitry Andric if (s == "relr") 7610b57cec5SDimitry Andric return {false, true}; 7620b57cec5SDimitry Andric if (s == "android+relr") 7630b57cec5SDimitry Andric return {true, true}; 7640b57cec5SDimitry Andric 7650b57cec5SDimitry Andric if (s != "none") 7660b57cec5SDimitry Andric error("unknown -pack-dyn-relocs format: " + s); 7670b57cec5SDimitry Andric return {false, false}; 7680b57cec5SDimitry Andric } 7690b57cec5SDimitry Andric 7700b57cec5SDimitry Andric static void readCallGraph(MemoryBufferRef mb) { 7710b57cec5SDimitry Andric // Build a map from symbol name to section 7720b57cec5SDimitry Andric DenseMap<StringRef, Symbol *> map; 7730b57cec5SDimitry Andric for (InputFile *file : objectFiles) 7740b57cec5SDimitry Andric for (Symbol *sym : file->getSymbols()) 7750b57cec5SDimitry Andric map[sym->getName()] = sym; 7760b57cec5SDimitry Andric 7770b57cec5SDimitry Andric auto findSection = [&](StringRef name) -> InputSectionBase * { 7780b57cec5SDimitry Andric Symbol *sym = map.lookup(name); 7790b57cec5SDimitry Andric if (!sym) { 7800b57cec5SDimitry Andric if (config->warnSymbolOrdering) 7810b57cec5SDimitry Andric warn(mb.getBufferIdentifier() + ": no such symbol: " + name); 7820b57cec5SDimitry Andric return nullptr; 7830b57cec5SDimitry Andric } 7840b57cec5SDimitry Andric maybeWarnUnorderableSymbol(sym); 7850b57cec5SDimitry Andric 7860b57cec5SDimitry Andric if (Defined *dr = dyn_cast_or_null<Defined>(sym)) 7870b57cec5SDimitry Andric return dyn_cast_or_null<InputSectionBase>(dr->section); 7880b57cec5SDimitry Andric return nullptr; 7890b57cec5SDimitry Andric }; 7900b57cec5SDimitry Andric 7910b57cec5SDimitry Andric for (StringRef line : args::getLines(mb)) { 7920b57cec5SDimitry Andric SmallVector<StringRef, 3> fields; 7930b57cec5SDimitry Andric line.split(fields, ' '); 7940b57cec5SDimitry Andric uint64_t count; 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 7970b57cec5SDimitry Andric error(mb.getBufferIdentifier() + ": parse error"); 7980b57cec5SDimitry Andric return; 7990b57cec5SDimitry Andric } 8000b57cec5SDimitry Andric 8010b57cec5SDimitry Andric if (InputSectionBase *from = findSection(fields[0])) 8020b57cec5SDimitry Andric if (InputSectionBase *to = findSection(fields[1])) 8030b57cec5SDimitry Andric config->callGraphProfile[std::make_pair(from, to)] += count; 8040b57cec5SDimitry Andric } 8050b57cec5SDimitry Andric } 8060b57cec5SDimitry Andric 8070b57cec5SDimitry Andric template <class ELFT> static void readCallGraphsFromObjectFiles() { 8080b57cec5SDimitry Andric for (auto file : objectFiles) { 8090b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(file); 8100b57cec5SDimitry Andric 8110b57cec5SDimitry Andric for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) { 8120b57cec5SDimitry Andric auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from)); 8130b57cec5SDimitry Andric auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to)); 8140b57cec5SDimitry Andric if (!fromSym || !toSym) 8150b57cec5SDimitry Andric continue; 8160b57cec5SDimitry Andric 8170b57cec5SDimitry Andric auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section); 8180b57cec5SDimitry Andric auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section); 8190b57cec5SDimitry Andric if (from && to) 8200b57cec5SDimitry Andric config->callGraphProfile[{from, to}] += cgpe.cgp_weight; 8210b57cec5SDimitry Andric } 8220b57cec5SDimitry Andric } 8230b57cec5SDimitry Andric } 8240b57cec5SDimitry Andric 8250b57cec5SDimitry Andric static bool getCompressDebugSections(opt::InputArgList &args) { 8260b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none"); 8270b57cec5SDimitry Andric if (s == "none") 8280b57cec5SDimitry Andric return false; 8290b57cec5SDimitry Andric if (s != "zlib") 8300b57cec5SDimitry Andric error("unknown --compress-debug-sections value: " + s); 8310b57cec5SDimitry Andric if (!zlib::isAvailable()) 8320b57cec5SDimitry Andric error("--compress-debug-sections: zlib is not available"); 8330b57cec5SDimitry Andric return true; 8340b57cec5SDimitry Andric } 8350b57cec5SDimitry Andric 83685868e8aSDimitry Andric static StringRef getAliasSpelling(opt::Arg *arg) { 83785868e8aSDimitry Andric if (const opt::Arg *alias = arg->getAlias()) 83885868e8aSDimitry Andric return alias->getSpelling(); 83985868e8aSDimitry Andric return arg->getSpelling(); 84085868e8aSDimitry Andric } 84185868e8aSDimitry Andric 8420b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 8430b57cec5SDimitry Andric unsigned id) { 8440b57cec5SDimitry Andric auto *arg = args.getLastArg(id); 8450b57cec5SDimitry Andric if (!arg) 8460b57cec5SDimitry Andric return {"", ""}; 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric StringRef s = arg->getValue(); 8490b57cec5SDimitry Andric std::pair<StringRef, StringRef> ret = s.split(';'); 8500b57cec5SDimitry Andric if (ret.second.empty()) 85185868e8aSDimitry Andric error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s); 8520b57cec5SDimitry Andric return ret; 8530b57cec5SDimitry Andric } 8540b57cec5SDimitry Andric 8550b57cec5SDimitry Andric // Parse the symbol ordering file and warn for any duplicate entries. 8560b57cec5SDimitry Andric static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) { 8570b57cec5SDimitry Andric SetVector<StringRef> names; 8580b57cec5SDimitry Andric for (StringRef s : args::getLines(mb)) 8590b57cec5SDimitry Andric if (!names.insert(s) && config->warnSymbolOrdering) 8600b57cec5SDimitry Andric warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s); 8610b57cec5SDimitry Andric 8620b57cec5SDimitry Andric return names.takeVector(); 8630b57cec5SDimitry Andric } 8640b57cec5SDimitry Andric 865*5ffd83dbSDimitry Andric static bool getIsRela(opt::InputArgList &args) { 866*5ffd83dbSDimitry Andric // If -z rel or -z rela is specified, use the last option. 867*5ffd83dbSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 868*5ffd83dbSDimitry Andric StringRef s(arg->getValue()); 869*5ffd83dbSDimitry Andric if (s == "rel") 870*5ffd83dbSDimitry Andric return false; 871*5ffd83dbSDimitry Andric if (s == "rela") 872*5ffd83dbSDimitry Andric return true; 873*5ffd83dbSDimitry Andric } 874*5ffd83dbSDimitry Andric 875*5ffd83dbSDimitry Andric // Otherwise use the psABI defined relocation entry format. 876*5ffd83dbSDimitry Andric uint16_t m = config->emachine; 877*5ffd83dbSDimitry Andric return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC || 878*5ffd83dbSDimitry Andric m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64; 879*5ffd83dbSDimitry Andric } 880*5ffd83dbSDimitry Andric 8810b57cec5SDimitry Andric static void parseClangOption(StringRef opt, const Twine &msg) { 8820b57cec5SDimitry Andric std::string err; 8830b57cec5SDimitry Andric raw_string_ostream os(err); 8840b57cec5SDimitry Andric 8850b57cec5SDimitry Andric const char *argv[] = {config->progName.data(), opt.data()}; 8860b57cec5SDimitry Andric if (cl::ParseCommandLineOptions(2, argv, "", &os)) 8870b57cec5SDimitry Andric return; 8880b57cec5SDimitry Andric os.flush(); 8890b57cec5SDimitry Andric error(msg + ": " + StringRef(err).trim()); 8900b57cec5SDimitry Andric } 8910b57cec5SDimitry Andric 8920b57cec5SDimitry Andric // Initializes Config members by the command line options. 8930b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args) { 8940b57cec5SDimitry Andric errorHandler().verbose = args.hasArg(OPT_verbose); 8950b57cec5SDimitry Andric errorHandler().fatalWarnings = 8960b57cec5SDimitry Andric args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false); 8970b57cec5SDimitry Andric errorHandler().vsDiagnostics = 8980b57cec5SDimitry Andric args.hasArg(OPT_visual_studio_diagnostics_format, false); 8990b57cec5SDimitry Andric 9000b57cec5SDimitry Andric config->allowMultipleDefinition = 9010b57cec5SDimitry Andric args.hasFlag(OPT_allow_multiple_definition, 9020b57cec5SDimitry Andric OPT_no_allow_multiple_definition, false) || 9030b57cec5SDimitry Andric hasZOption(args, "muldefs"); 9040b57cec5SDimitry Andric config->allowShlibUndefined = 9050b57cec5SDimitry Andric args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined, 9060b57cec5SDimitry Andric args.hasArg(OPT_shared)); 9070b57cec5SDimitry Andric config->auxiliaryList = args::getStrings(args, OPT_auxiliary); 9080b57cec5SDimitry Andric config->bsymbolic = args.hasArg(OPT_Bsymbolic); 9090b57cec5SDimitry Andric config->bsymbolicFunctions = args.hasArg(OPT_Bsymbolic_functions); 9100b57cec5SDimitry Andric config->checkSections = 9110b57cec5SDimitry Andric args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 9120b57cec5SDimitry Andric config->chroot = args.getLastArgValue(OPT_chroot); 9130b57cec5SDimitry Andric config->compressDebugSections = getCompressDebugSections(args); 9140b57cec5SDimitry Andric config->cref = args.hasFlag(OPT_cref, OPT_no_cref, false); 9150b57cec5SDimitry Andric config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common, 9160b57cec5SDimitry Andric !args.hasArg(OPT_relocatable)); 917*5ffd83dbSDimitry Andric config->optimizeBBJumps = 918*5ffd83dbSDimitry Andric args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false); 9190b57cec5SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true); 9200b57cec5SDimitry Andric config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true); 9210b57cec5SDimitry Andric config->disableVerify = args.hasArg(OPT_disable_verify); 9220b57cec5SDimitry Andric config->discard = getDiscard(args); 9230b57cec5SDimitry Andric config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq); 9240b57cec5SDimitry Andric config->dynamicLinker = getDynamicLinker(args); 9250b57cec5SDimitry Andric config->ehFrameHdr = 9260b57cec5SDimitry Andric args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 9270b57cec5SDimitry Andric config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false); 9280b57cec5SDimitry Andric config->emitRelocs = args.hasArg(OPT_emit_relocs); 9290b57cec5SDimitry Andric config->callGraphProfileSort = args.hasFlag( 9300b57cec5SDimitry Andric OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true); 9310b57cec5SDimitry Andric config->enableNewDtags = 9320b57cec5SDimitry Andric args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 9330b57cec5SDimitry Andric config->entry = args.getLastArgValue(OPT_entry); 9340b57cec5SDimitry Andric config->executeOnly = 9350b57cec5SDimitry Andric args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 9360b57cec5SDimitry Andric config->exportDynamic = 9370b57cec5SDimitry Andric args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 9380b57cec5SDimitry Andric config->filterList = args::getStrings(args, OPT_filter); 9390b57cec5SDimitry Andric config->fini = args.getLastArgValue(OPT_fini, "_fini"); 940*5ffd83dbSDimitry Andric config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) && 941*5ffd83dbSDimitry Andric !args.hasArg(OPT_relocatable); 942*5ffd83dbSDimitry Andric config->fixCortexA8 = 943*5ffd83dbSDimitry Andric args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable); 9440b57cec5SDimitry Andric config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 9450b57cec5SDimitry Andric config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 9460b57cec5SDimitry Andric config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 9470b57cec5SDimitry Andric config->icf = getICF(args); 9480b57cec5SDimitry Andric config->ignoreDataAddressEquality = 9490b57cec5SDimitry Andric args.hasArg(OPT_ignore_data_address_equality); 9500b57cec5SDimitry Andric config->ignoreFunctionAddressEquality = 9510b57cec5SDimitry Andric args.hasArg(OPT_ignore_function_address_equality); 9520b57cec5SDimitry Andric config->init = args.getLastArgValue(OPT_init, "_init"); 9530b57cec5SDimitry Andric config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline); 9540b57cec5SDimitry Andric config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 9550b57cec5SDimitry Andric config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 9560b57cec5SDimitry Andric config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager); 957*5ffd83dbSDimitry Andric config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm); 9580b57cec5SDimitry Andric config->ltoNewPassManager = args.hasArg(OPT_lto_new_pass_manager); 9590b57cec5SDimitry Andric config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes); 960*5ffd83dbSDimitry Andric config->ltoWholeProgramVisibility = 961*5ffd83dbSDimitry Andric args.hasArg(OPT_lto_whole_program_visibility); 9620b57cec5SDimitry Andric config->ltoo = args::getInteger(args, OPT_lto_O, 2); 96385868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq); 9640b57cec5SDimitry Andric config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1); 9650b57cec5SDimitry Andric config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 966*5ffd83dbSDimitry Andric config->ltoBasicBlockSections = 967*5ffd83dbSDimitry Andric args.getLastArgValue(OPT_lto_basicblock_sections); 968*5ffd83dbSDimitry Andric config->ltoUniqueBasicBlockSectionNames = 969*5ffd83dbSDimitry Andric args.hasFlag(OPT_lto_unique_bb_section_names, 970*5ffd83dbSDimitry Andric OPT_no_lto_unique_bb_section_names, false); 9710b57cec5SDimitry Andric config->mapFile = args.getLastArgValue(OPT_Map); 9720b57cec5SDimitry Andric config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0); 9730b57cec5SDimitry Andric config->mergeArmExidx = 9740b57cec5SDimitry Andric args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 975480093f4SDimitry Andric config->mmapOutputFile = 976480093f4SDimitry Andric args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true); 9770b57cec5SDimitry Andric config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 9780b57cec5SDimitry Andric config->noinhibitExec = args.hasArg(OPT_noinhibit_exec); 9790b57cec5SDimitry Andric config->nostdlib = args.hasArg(OPT_nostdlib); 9800b57cec5SDimitry Andric config->oFormatBinary = isOutputFormatBinary(args); 9810b57cec5SDimitry Andric config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false); 9820b57cec5SDimitry Andric config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename); 9830b57cec5SDimitry Andric config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes); 9840b57cec5SDimitry Andric config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness); 9850b57cec5SDimitry Andric config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format); 9860b57cec5SDimitry Andric config->optimize = args::getInteger(args, OPT_O, 1); 9870b57cec5SDimitry Andric config->orphanHandling = getOrphanHandling(args); 9880b57cec5SDimitry Andric config->outputFile = args.getLastArgValue(OPT_o); 9890b57cec5SDimitry Andric config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false); 9900b57cec5SDimitry Andric config->printIcfSections = 9910b57cec5SDimitry Andric args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 9920b57cec5SDimitry Andric config->printGcSections = 9930b57cec5SDimitry Andric args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 994*5ffd83dbSDimitry Andric config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats); 9950b57cec5SDimitry Andric config->printSymbolOrder = 9960b57cec5SDimitry Andric args.getLastArgValue(OPT_print_symbol_order); 9970b57cec5SDimitry Andric config->rpath = getRpath(args); 9980b57cec5SDimitry Andric config->relocatable = args.hasArg(OPT_relocatable); 9990b57cec5SDimitry Andric config->saveTemps = args.hasArg(OPT_save_temps); 1000*5ffd83dbSDimitry Andric if (args.hasArg(OPT_shuffle_sections)) 1001*5ffd83dbSDimitry Andric config->shuffleSectionSeed = args::getInteger(args, OPT_shuffle_sections, 0); 10020b57cec5SDimitry Andric config->searchPaths = args::getStrings(args, OPT_library_path); 10030b57cec5SDimitry Andric config->sectionStartMap = getSectionStartMap(args); 10040b57cec5SDimitry Andric config->shared = args.hasArg(OPT_shared); 1005*5ffd83dbSDimitry Andric config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true); 10060b57cec5SDimitry Andric config->soName = args.getLastArgValue(OPT_soname); 10070b57cec5SDimitry Andric config->sortSection = getSortSection(args); 10080b57cec5SDimitry Andric config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384); 10090b57cec5SDimitry Andric config->strip = getStrip(args); 10100b57cec5SDimitry Andric config->sysroot = args.getLastArgValue(OPT_sysroot); 10110b57cec5SDimitry Andric config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 10120b57cec5SDimitry Andric config->target2 = getTarget2(args); 10130b57cec5SDimitry Andric config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir); 10140b57cec5SDimitry Andric config->thinLTOCachePolicy = CHECK( 10150b57cec5SDimitry Andric parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)), 10160b57cec5SDimitry Andric "--thinlto-cache-policy: invalid cache policy"); 101785868e8aSDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 101885868e8aSDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 101985868e8aSDimitry Andric args.hasArg(OPT_thinlto_index_only_eq); 102085868e8aSDimitry Andric config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq); 10210b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 102285868e8aSDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq); 10230b57cec5SDimitry Andric config->thinLTOPrefixReplace = 102485868e8aSDimitry Andric getOldNewOptions(args, OPT_thinlto_prefix_replace_eq); 1025*5ffd83dbSDimitry Andric config->thinLTOModulesToCompile = 1026*5ffd83dbSDimitry Andric args::getStrings(args, OPT_thinlto_single_module_eq); 1027*5ffd83dbSDimitry Andric config->timeTraceEnabled = args.hasArg(OPT_time_trace); 1028*5ffd83dbSDimitry Andric config->timeTraceGranularity = 1029*5ffd83dbSDimitry Andric args::getInteger(args, OPT_time_trace_granularity, 500); 10300b57cec5SDimitry Andric config->trace = args.hasArg(OPT_trace); 10310b57cec5SDimitry Andric config->undefined = args::getStrings(args, OPT_undefined); 10320b57cec5SDimitry Andric config->undefinedVersion = 10330b57cec5SDimitry Andric args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true); 1034*5ffd83dbSDimitry Andric config->unique = args.hasArg(OPT_unique); 10350b57cec5SDimitry Andric config->useAndroidRelrTags = args.hasFlag( 10360b57cec5SDimitry Andric OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 10370b57cec5SDimitry Andric config->unresolvedSymbols = getUnresolvedSymbolPolicy(args); 10380b57cec5SDimitry Andric config->warnBackrefs = 10390b57cec5SDimitry Andric args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 10400b57cec5SDimitry Andric config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 10410b57cec5SDimitry Andric config->warnIfuncTextrel = 10420b57cec5SDimitry Andric args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false); 10430b57cec5SDimitry Andric config->warnSymbolOrdering = 10440b57cec5SDimitry Andric args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 10450b57cec5SDimitry Andric config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true); 10460b57cec5SDimitry Andric config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true); 1047*5ffd83dbSDimitry Andric config->zForceBti = hasZOption(args, "force-bti"); 1048480093f4SDimitry Andric config->zForceIbt = hasZOption(args, "force-ibt"); 10490b57cec5SDimitry Andric config->zGlobal = hasZOption(args, "global"); 1050480093f4SDimitry Andric config->zGnustack = getZGnuStack(args); 10510b57cec5SDimitry Andric config->zHazardplt = hasZOption(args, "hazardplt"); 10520b57cec5SDimitry Andric config->zIfuncNoplt = hasZOption(args, "ifunc-noplt"); 10530b57cec5SDimitry Andric config->zInitfirst = hasZOption(args, "initfirst"); 10540b57cec5SDimitry Andric config->zInterpose = hasZOption(args, "interpose"); 10550b57cec5SDimitry Andric config->zKeepTextSectionPrefix = getZFlag( 10560b57cec5SDimitry Andric args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 10570b57cec5SDimitry Andric config->zNodefaultlib = hasZOption(args, "nodefaultlib"); 10580b57cec5SDimitry Andric config->zNodelete = hasZOption(args, "nodelete"); 10590b57cec5SDimitry Andric config->zNodlopen = hasZOption(args, "nodlopen"); 10600b57cec5SDimitry Andric config->zNow = getZFlag(args, "now", "lazy", false); 10610b57cec5SDimitry Andric config->zOrigin = hasZOption(args, "origin"); 1062*5ffd83dbSDimitry Andric config->zPacPlt = hasZOption(args, "pac-plt"); 10630b57cec5SDimitry Andric config->zRelro = getZFlag(args, "relro", "norelro", true); 10640b57cec5SDimitry Andric config->zRetpolineplt = hasZOption(args, "retpolineplt"); 10650b57cec5SDimitry Andric config->zRodynamic = hasZOption(args, "rodynamic"); 106685868e8aSDimitry Andric config->zSeparate = getZSeparate(args); 1067480093f4SDimitry Andric config->zShstk = hasZOption(args, "shstk"); 10680b57cec5SDimitry Andric config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0); 1069*5ffd83dbSDimitry Andric config->zStartStopVisibility = getZStartStopVisibility(args); 10700b57cec5SDimitry Andric config->zText = getZFlag(args, "text", "notext", true); 10710b57cec5SDimitry Andric config->zWxneeded = hasZOption(args, "wxneeded"); 10720b57cec5SDimitry Andric 1073*5ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_z)) { 1074*5ffd83dbSDimitry Andric std::pair<StringRef, StringRef> option = 1075*5ffd83dbSDimitry Andric StringRef(arg->getValue()).split('='); 1076*5ffd83dbSDimitry Andric if (option.first != "dead-reloc-in-nonalloc") 1077*5ffd83dbSDimitry Andric continue; 1078*5ffd83dbSDimitry Andric constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: "; 1079*5ffd83dbSDimitry Andric std::pair<StringRef, StringRef> kv = option.second.split('='); 1080*5ffd83dbSDimitry Andric if (kv.first.empty() || kv.second.empty()) { 1081*5ffd83dbSDimitry Andric error(errPrefix + "expected <section_glob>=<value>"); 1082*5ffd83dbSDimitry Andric continue; 1083*5ffd83dbSDimitry Andric } 1084*5ffd83dbSDimitry Andric uint64_t v; 1085*5ffd83dbSDimitry Andric if (!to_integer(kv.second, v)) 1086*5ffd83dbSDimitry Andric error(errPrefix + "expected a non-negative integer, but got '" + 1087*5ffd83dbSDimitry Andric kv.second + "'"); 1088*5ffd83dbSDimitry Andric else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1089*5ffd83dbSDimitry Andric config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v); 1090*5ffd83dbSDimitry Andric else 1091*5ffd83dbSDimitry Andric error(errPrefix + toString(pat.takeError())); 1092*5ffd83dbSDimitry Andric } 1093*5ffd83dbSDimitry Andric 10940b57cec5SDimitry Andric // Parse LTO options. 10950b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq)) 10960b57cec5SDimitry Andric parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())), 10970b57cec5SDimitry Andric arg->getSpelling()); 10980b57cec5SDimitry Andric 1099*5ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus)) 1100*5ffd83dbSDimitry Andric parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling()); 1101*5ffd83dbSDimitry Andric 1102*5ffd83dbSDimitry Andric // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or 1103*5ffd83dbSDimitry Andric // relative path. Just ignore. If not ended with "lto-wrapper", consider it an 1104*5ffd83dbSDimitry Andric // unsupported LLVMgold.so option and error. 1105*5ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) 1106*5ffd83dbSDimitry Andric if (!StringRef(arg->getValue()).endswith("lto-wrapper")) 1107*5ffd83dbSDimitry Andric error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() + 1108*5ffd83dbSDimitry Andric "'"); 11090b57cec5SDimitry Andric 11100b57cec5SDimitry Andric // Parse -mllvm options. 11110b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_mllvm)) 11120b57cec5SDimitry Andric parseClangOption(arg->getValue(), arg->getSpelling()); 11130b57cec5SDimitry Andric 1114*5ffd83dbSDimitry Andric // --threads= takes a positive integer and provides the default value for 1115*5ffd83dbSDimitry Andric // --thinlto-jobs=. 1116*5ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 1117*5ffd83dbSDimitry Andric StringRef v(arg->getValue()); 1118*5ffd83dbSDimitry Andric unsigned threads = 0; 1119*5ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 1120*5ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 1121*5ffd83dbSDimitry Andric arg->getValue() + "'"); 1122*5ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 1123*5ffd83dbSDimitry Andric config->thinLTOJobs = v; 1124*5ffd83dbSDimitry Andric } 1125*5ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_thinlto_jobs)) 1126*5ffd83dbSDimitry Andric config->thinLTOJobs = arg->getValue(); 1127*5ffd83dbSDimitry Andric 11280b57cec5SDimitry Andric if (config->ltoo > 3) 11290b57cec5SDimitry Andric error("invalid optimization level for LTO: " + Twine(config->ltoo)); 11300b57cec5SDimitry Andric if (config->ltoPartitions == 0) 11310b57cec5SDimitry Andric error("--lto-partitions: number of threads must be > 0"); 1132*5ffd83dbSDimitry Andric if (!get_threadpool_strategy(config->thinLTOJobs)) 1133*5ffd83dbSDimitry Andric error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 11340b57cec5SDimitry Andric 11350b57cec5SDimitry Andric if (config->splitStackAdjustSize < 0) 11360b57cec5SDimitry Andric error("--split-stack-adjust-size: size must be >= 0"); 11370b57cec5SDimitry Andric 1138480093f4SDimitry Andric // The text segment is traditionally the first segment, whose address equals 1139480093f4SDimitry Andric // the base address. However, lld places the R PT_LOAD first. -Ttext-segment 1140480093f4SDimitry Andric // is an old-fashioned option that does not play well with lld's layout. 1141480093f4SDimitry Andric // Suggest --image-base as a likely alternative. 1142480093f4SDimitry Andric if (args.hasArg(OPT_Ttext_segment)) 1143480093f4SDimitry Andric error("-Ttext-segment is not supported. Use --image-base if you " 1144480093f4SDimitry Andric "intend to set the base address"); 1145480093f4SDimitry Andric 11460b57cec5SDimitry Andric // Parse ELF{32,64}{LE,BE} and CPU type. 11470b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_m)) { 11480b57cec5SDimitry Andric StringRef s = arg->getValue(); 11490b57cec5SDimitry Andric std::tie(config->ekind, config->emachine, config->osabi) = 11500b57cec5SDimitry Andric parseEmulation(s); 11510b57cec5SDimitry Andric config->mipsN32Abi = 11520b57cec5SDimitry Andric (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32")); 11530b57cec5SDimitry Andric config->emulation = s; 11540b57cec5SDimitry Andric } 11550b57cec5SDimitry Andric 11560b57cec5SDimitry Andric // Parse -hash-style={sysv,gnu,both}. 11570b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_hash_style)) { 11580b57cec5SDimitry Andric StringRef s = arg->getValue(); 11590b57cec5SDimitry Andric if (s == "sysv") 11600b57cec5SDimitry Andric config->sysvHash = true; 11610b57cec5SDimitry Andric else if (s == "gnu") 11620b57cec5SDimitry Andric config->gnuHash = true; 11630b57cec5SDimitry Andric else if (s == "both") 11640b57cec5SDimitry Andric config->sysvHash = config->gnuHash = true; 11650b57cec5SDimitry Andric else 11660b57cec5SDimitry Andric error("unknown -hash-style: " + s); 11670b57cec5SDimitry Andric } 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric if (args.hasArg(OPT_print_map)) 11700b57cec5SDimitry Andric config->mapFile = "-"; 11710b57cec5SDimitry Andric 11720b57cec5SDimitry Andric // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 11730b57cec5SDimitry Andric // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 11740b57cec5SDimitry Andric // it. 11750b57cec5SDimitry Andric if (config->nmagic || config->omagic) 11760b57cec5SDimitry Andric config->zRelro = false; 11770b57cec5SDimitry Andric 11780b57cec5SDimitry Andric std::tie(config->buildId, config->buildIdVector) = getBuildId(args); 11790b57cec5SDimitry Andric 11800b57cec5SDimitry Andric std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) = 11810b57cec5SDimitry Andric getPackDynRelocs(args); 11820b57cec5SDimitry Andric 11830b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){ 11840b57cec5SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 11850b57cec5SDimitry Andric error("--symbol-ordering-file and --call-graph-order-file " 11860b57cec5SDimitry Andric "may not be used together"); 11870b57cec5SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){ 11880b57cec5SDimitry Andric config->symbolOrderingFile = getSymbolOrderingFile(*buffer); 11890b57cec5SDimitry Andric // Also need to disable CallGraphProfileSort to prevent 11900b57cec5SDimitry Andric // LLD order symbols with CGProfile 11910b57cec5SDimitry Andric config->callGraphProfileSort = false; 11920b57cec5SDimitry Andric } 11930b57cec5SDimitry Andric } 11940b57cec5SDimitry Andric 119585868e8aSDimitry Andric assert(config->versionDefinitions.empty()); 119685868e8aSDimitry Andric config->versionDefinitions.push_back({"local", (uint16_t)VER_NDX_LOCAL, {}}); 119785868e8aSDimitry Andric config->versionDefinitions.push_back( 119885868e8aSDimitry Andric {"global", (uint16_t)VER_NDX_GLOBAL, {}}); 119985868e8aSDimitry Andric 12000b57cec5SDimitry Andric // If --retain-symbol-file is used, we'll keep only the symbols listed in 12010b57cec5SDimitry Andric // the file and discard all others. 12020b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) { 120385868e8aSDimitry Andric config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back( 120485868e8aSDimitry Andric {"*", /*isExternCpp=*/false, /*hasWildcard=*/true}); 12050b57cec5SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 12060b57cec5SDimitry Andric for (StringRef s : args::getLines(*buffer)) 120785868e8aSDimitry Andric config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back( 120885868e8aSDimitry Andric {s, /*isExternCpp=*/false, /*hasWildcard=*/false}); 12090b57cec5SDimitry Andric } 12100b57cec5SDimitry Andric 1211*5ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) { 1212*5ffd83dbSDimitry Andric StringRef pattern(arg->getValue()); 1213*5ffd83dbSDimitry Andric if (Expected<GlobPattern> pat = GlobPattern::create(pattern)) 1214*5ffd83dbSDimitry Andric config->warnBackrefsExclude.push_back(std::move(*pat)); 1215*5ffd83dbSDimitry Andric else 1216*5ffd83dbSDimitry Andric error(arg->getSpelling() + ": " + toString(pat.takeError())); 1217*5ffd83dbSDimitry Andric } 1218*5ffd83dbSDimitry Andric 1219*5ffd83dbSDimitry Andric // When producing an executable, --dynamic-list specifies non-local defined 1220*5ffd83dbSDimitry Andric // symbols whith are required to be exported. When producing a shared object, 1221*5ffd83dbSDimitry Andric // symbols not specified by --dynamic-list are non-preemptible. 1222*5ffd83dbSDimitry Andric config->symbolic = 1223*5ffd83dbSDimitry Andric args.hasArg(OPT_Bsymbolic) || args.hasArg(OPT_dynamic_list); 12240b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_dynamic_list)) 12250b57cec5SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 12260b57cec5SDimitry Andric readDynamicList(*buffer); 12270b57cec5SDimitry Andric 1228*5ffd83dbSDimitry Andric // --export-dynamic-symbol specifies additional --dynamic-list symbols if any 1229*5ffd83dbSDimitry Andric // other option expresses a symbolic intention: -no-pie, -pie, -Bsymbolic, 1230*5ffd83dbSDimitry Andric // -Bsymbolic-functions (if STT_FUNC), --dynamic-list. 12310b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export_dynamic_symbol)) 12320b57cec5SDimitry Andric config->dynamicList.push_back( 1233*5ffd83dbSDimitry Andric {arg->getValue(), /*isExternCpp=*/false, 1234*5ffd83dbSDimitry Andric /*hasWildcard=*/hasWildcard(arg->getValue())}); 12350b57cec5SDimitry Andric 12360b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_version_script)) 12370b57cec5SDimitry Andric if (Optional<std::string> path = searchScript(arg->getValue())) { 12380b57cec5SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(*path)) 12390b57cec5SDimitry Andric readVersionScript(*buffer); 12400b57cec5SDimitry Andric } else { 12410b57cec5SDimitry Andric error(Twine("cannot find version script ") + arg->getValue()); 12420b57cec5SDimitry Andric } 12430b57cec5SDimitry Andric } 12440b57cec5SDimitry Andric 12450b57cec5SDimitry Andric // Some Config members do not directly correspond to any particular 12460b57cec5SDimitry Andric // command line options, but computed based on other Config values. 12470b57cec5SDimitry Andric // This function initialize such members. See Config.h for the details 12480b57cec5SDimitry Andric // of these values. 12490b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args) { 12500b57cec5SDimitry Andric ELFKind k = config->ekind; 12510b57cec5SDimitry Andric uint16_t m = config->emachine; 12520b57cec5SDimitry Andric 12530b57cec5SDimitry Andric config->copyRelocs = (config->relocatable || config->emitRelocs); 12540b57cec5SDimitry Andric config->is64 = (k == ELF64LEKind || k == ELF64BEKind); 12550b57cec5SDimitry Andric config->isLE = (k == ELF32LEKind || k == ELF64LEKind); 12560b57cec5SDimitry Andric config->endianness = config->isLE ? endianness::little : endianness::big; 12570b57cec5SDimitry Andric config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS); 12580b57cec5SDimitry Andric config->isPic = config->pie || config->shared; 12590b57cec5SDimitry Andric config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic); 12600b57cec5SDimitry Andric config->wordsize = config->is64 ? 8 : 4; 12610b57cec5SDimitry Andric 12620b57cec5SDimitry Andric // ELF defines two different ways to store relocation addends as shown below: 12630b57cec5SDimitry Andric // 1264*5ffd83dbSDimitry Andric // Rel: Addends are stored to the location where relocations are applied. It 1265*5ffd83dbSDimitry Andric // cannot pack the full range of addend values for all relocation types, but 1266*5ffd83dbSDimitry Andric // this only affects relocation types that we don't support emitting as 1267*5ffd83dbSDimitry Andric // dynamic relocations (see getDynRel). 12680b57cec5SDimitry Andric // Rela: Addends are stored as part of relocation entry. 12690b57cec5SDimitry Andric // 12700b57cec5SDimitry Andric // In other words, Rela makes it easy to read addends at the price of extra 1271*5ffd83dbSDimitry Andric // 4 or 8 byte for each relocation entry. 12720b57cec5SDimitry Andric // 1273*5ffd83dbSDimitry Andric // We pick the format for dynamic relocations according to the psABI for each 1274*5ffd83dbSDimitry Andric // processor, but a contrary choice can be made if the dynamic loader 1275*5ffd83dbSDimitry Andric // supports. 1276*5ffd83dbSDimitry Andric config->isRela = getIsRela(args); 12770b57cec5SDimitry Andric 12780b57cec5SDimitry Andric // If the output uses REL relocations we must store the dynamic relocation 12790b57cec5SDimitry Andric // addends to the output sections. We also store addends for RELA relocations 12800b57cec5SDimitry Andric // if --apply-dynamic-relocs is used. 12810b57cec5SDimitry Andric // We default to not writing the addends when using RELA relocations since 12820b57cec5SDimitry Andric // any standard conforming tool can find it in r_addend. 12830b57cec5SDimitry Andric config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs, 12840b57cec5SDimitry Andric OPT_no_apply_dynamic_relocs, false) || 12850b57cec5SDimitry Andric !config->isRela; 12860b57cec5SDimitry Andric 12870b57cec5SDimitry Andric config->tocOptimize = 12880b57cec5SDimitry Andric args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64); 12890b57cec5SDimitry Andric } 12900b57cec5SDimitry Andric 12910b57cec5SDimitry Andric // Returns a value of "-format" option. 12920b57cec5SDimitry Andric static bool isFormatBinary(StringRef s) { 12930b57cec5SDimitry Andric if (s == "binary") 12940b57cec5SDimitry Andric return true; 12950b57cec5SDimitry Andric if (s == "elf" || s == "default") 12960b57cec5SDimitry Andric return false; 12970b57cec5SDimitry Andric error("unknown -format value: " + s + 12980b57cec5SDimitry Andric " (supported formats: elf, default, binary)"); 12990b57cec5SDimitry Andric return false; 13000b57cec5SDimitry Andric } 13010b57cec5SDimitry Andric 13020b57cec5SDimitry Andric void LinkerDriver::createFiles(opt::InputArgList &args) { 13030b57cec5SDimitry Andric // For --{push,pop}-state. 13040b57cec5SDimitry Andric std::vector<std::tuple<bool, bool, bool>> stack; 13050b57cec5SDimitry Andric 13060b57cec5SDimitry Andric // Iterate over argv to process input files and positional arguments. 13070b57cec5SDimitry Andric for (auto *arg : args) { 13080b57cec5SDimitry Andric switch (arg->getOption().getID()) { 13090b57cec5SDimitry Andric case OPT_library: 13100b57cec5SDimitry Andric addLibrary(arg->getValue()); 13110b57cec5SDimitry Andric break; 13120b57cec5SDimitry Andric case OPT_INPUT: 13130b57cec5SDimitry Andric addFile(arg->getValue(), /*withLOption=*/false); 13140b57cec5SDimitry Andric break; 13150b57cec5SDimitry Andric case OPT_defsym: { 13160b57cec5SDimitry Andric StringRef from; 13170b57cec5SDimitry Andric StringRef to; 13180b57cec5SDimitry Andric std::tie(from, to) = StringRef(arg->getValue()).split('='); 13190b57cec5SDimitry Andric if (from.empty() || to.empty()) 13200b57cec5SDimitry Andric error("-defsym: syntax error: " + StringRef(arg->getValue())); 13210b57cec5SDimitry Andric else 13220b57cec5SDimitry Andric readDefsym(from, MemoryBufferRef(to, "-defsym")); 13230b57cec5SDimitry Andric break; 13240b57cec5SDimitry Andric } 13250b57cec5SDimitry Andric case OPT_script: 13260b57cec5SDimitry Andric if (Optional<std::string> path = searchScript(arg->getValue())) { 13270b57cec5SDimitry Andric if (Optional<MemoryBufferRef> mb = readFile(*path)) 13280b57cec5SDimitry Andric readLinkerScript(*mb); 13290b57cec5SDimitry Andric break; 13300b57cec5SDimitry Andric } 13310b57cec5SDimitry Andric error(Twine("cannot find linker script ") + arg->getValue()); 13320b57cec5SDimitry Andric break; 13330b57cec5SDimitry Andric case OPT_as_needed: 13340b57cec5SDimitry Andric config->asNeeded = true; 13350b57cec5SDimitry Andric break; 13360b57cec5SDimitry Andric case OPT_format: 13370b57cec5SDimitry Andric config->formatBinary = isFormatBinary(arg->getValue()); 13380b57cec5SDimitry Andric break; 13390b57cec5SDimitry Andric case OPT_no_as_needed: 13400b57cec5SDimitry Andric config->asNeeded = false; 13410b57cec5SDimitry Andric break; 13420b57cec5SDimitry Andric case OPT_Bstatic: 13430b57cec5SDimitry Andric case OPT_omagic: 13440b57cec5SDimitry Andric case OPT_nmagic: 13450b57cec5SDimitry Andric config->isStatic = true; 13460b57cec5SDimitry Andric break; 13470b57cec5SDimitry Andric case OPT_Bdynamic: 13480b57cec5SDimitry Andric config->isStatic = false; 13490b57cec5SDimitry Andric break; 13500b57cec5SDimitry Andric case OPT_whole_archive: 13510b57cec5SDimitry Andric inWholeArchive = true; 13520b57cec5SDimitry Andric break; 13530b57cec5SDimitry Andric case OPT_no_whole_archive: 13540b57cec5SDimitry Andric inWholeArchive = false; 13550b57cec5SDimitry Andric break; 13560b57cec5SDimitry Andric case OPT_just_symbols: 13570b57cec5SDimitry Andric if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) { 13580b57cec5SDimitry Andric files.push_back(createObjectFile(*mb)); 13590b57cec5SDimitry Andric files.back()->justSymbols = true; 13600b57cec5SDimitry Andric } 13610b57cec5SDimitry Andric break; 13620b57cec5SDimitry Andric case OPT_start_group: 13630b57cec5SDimitry Andric if (InputFile::isInGroup) 13640b57cec5SDimitry Andric error("nested --start-group"); 13650b57cec5SDimitry Andric InputFile::isInGroup = true; 13660b57cec5SDimitry Andric break; 13670b57cec5SDimitry Andric case OPT_end_group: 13680b57cec5SDimitry Andric if (!InputFile::isInGroup) 13690b57cec5SDimitry Andric error("stray --end-group"); 13700b57cec5SDimitry Andric InputFile::isInGroup = false; 13710b57cec5SDimitry Andric ++InputFile::nextGroupId; 13720b57cec5SDimitry Andric break; 13730b57cec5SDimitry Andric case OPT_start_lib: 13740b57cec5SDimitry Andric if (inLib) 13750b57cec5SDimitry Andric error("nested --start-lib"); 13760b57cec5SDimitry Andric if (InputFile::isInGroup) 13770b57cec5SDimitry Andric error("may not nest --start-lib in --start-group"); 13780b57cec5SDimitry Andric inLib = true; 13790b57cec5SDimitry Andric InputFile::isInGroup = true; 13800b57cec5SDimitry Andric break; 13810b57cec5SDimitry Andric case OPT_end_lib: 13820b57cec5SDimitry Andric if (!inLib) 13830b57cec5SDimitry Andric error("stray --end-lib"); 13840b57cec5SDimitry Andric inLib = false; 13850b57cec5SDimitry Andric InputFile::isInGroup = false; 13860b57cec5SDimitry Andric ++InputFile::nextGroupId; 13870b57cec5SDimitry Andric break; 13880b57cec5SDimitry Andric case OPT_push_state: 13890b57cec5SDimitry Andric stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive); 13900b57cec5SDimitry Andric break; 13910b57cec5SDimitry Andric case OPT_pop_state: 13920b57cec5SDimitry Andric if (stack.empty()) { 13930b57cec5SDimitry Andric error("unbalanced --push-state/--pop-state"); 13940b57cec5SDimitry Andric break; 13950b57cec5SDimitry Andric } 13960b57cec5SDimitry Andric std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back(); 13970b57cec5SDimitry Andric stack.pop_back(); 13980b57cec5SDimitry Andric break; 13990b57cec5SDimitry Andric } 14000b57cec5SDimitry Andric } 14010b57cec5SDimitry Andric 14020b57cec5SDimitry Andric if (files.empty() && errorCount() == 0) 14030b57cec5SDimitry Andric error("no input files"); 14040b57cec5SDimitry Andric } 14050b57cec5SDimitry Andric 14060b57cec5SDimitry Andric // If -m <machine_type> was not given, infer it from object files. 14070b57cec5SDimitry Andric void LinkerDriver::inferMachineType() { 14080b57cec5SDimitry Andric if (config->ekind != ELFNoneKind) 14090b57cec5SDimitry Andric return; 14100b57cec5SDimitry Andric 14110b57cec5SDimitry Andric for (InputFile *f : files) { 14120b57cec5SDimitry Andric if (f->ekind == ELFNoneKind) 14130b57cec5SDimitry Andric continue; 14140b57cec5SDimitry Andric config->ekind = f->ekind; 14150b57cec5SDimitry Andric config->emachine = f->emachine; 14160b57cec5SDimitry Andric config->osabi = f->osabi; 14170b57cec5SDimitry Andric config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f); 14180b57cec5SDimitry Andric return; 14190b57cec5SDimitry Andric } 14200b57cec5SDimitry Andric error("target emulation unknown: -m or at least one .o file required"); 14210b57cec5SDimitry Andric } 14220b57cec5SDimitry Andric 14230b57cec5SDimitry Andric // Parse -z max-page-size=<value>. The default value is defined by 14240b57cec5SDimitry Andric // each target. 14250b57cec5SDimitry Andric static uint64_t getMaxPageSize(opt::InputArgList &args) { 14260b57cec5SDimitry Andric uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size", 14270b57cec5SDimitry Andric target->defaultMaxPageSize); 14280b57cec5SDimitry Andric if (!isPowerOf2_64(val)) 14290b57cec5SDimitry Andric error("max-page-size: value isn't a power of 2"); 14300b57cec5SDimitry Andric if (config->nmagic || config->omagic) { 14310b57cec5SDimitry Andric if (val != target->defaultMaxPageSize) 14320b57cec5SDimitry Andric warn("-z max-page-size set, but paging disabled by omagic or nmagic"); 14330b57cec5SDimitry Andric return 1; 14340b57cec5SDimitry Andric } 14350b57cec5SDimitry Andric return val; 14360b57cec5SDimitry Andric } 14370b57cec5SDimitry Andric 14380b57cec5SDimitry Andric // Parse -z common-page-size=<value>. The default value is defined by 14390b57cec5SDimitry Andric // each target. 14400b57cec5SDimitry Andric static uint64_t getCommonPageSize(opt::InputArgList &args) { 14410b57cec5SDimitry Andric uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size", 14420b57cec5SDimitry Andric target->defaultCommonPageSize); 14430b57cec5SDimitry Andric if (!isPowerOf2_64(val)) 14440b57cec5SDimitry Andric error("common-page-size: value isn't a power of 2"); 14450b57cec5SDimitry Andric if (config->nmagic || config->omagic) { 14460b57cec5SDimitry Andric if (val != target->defaultCommonPageSize) 14470b57cec5SDimitry Andric warn("-z common-page-size set, but paging disabled by omagic or nmagic"); 14480b57cec5SDimitry Andric return 1; 14490b57cec5SDimitry Andric } 14500b57cec5SDimitry Andric // commonPageSize can't be larger than maxPageSize. 14510b57cec5SDimitry Andric if (val > config->maxPageSize) 14520b57cec5SDimitry Andric val = config->maxPageSize; 14530b57cec5SDimitry Andric return val; 14540b57cec5SDimitry Andric } 14550b57cec5SDimitry Andric 14560b57cec5SDimitry Andric // Parses -image-base option. 14570b57cec5SDimitry Andric static Optional<uint64_t> getImageBase(opt::InputArgList &args) { 14580b57cec5SDimitry Andric // Because we are using "Config->maxPageSize" here, this function has to be 14590b57cec5SDimitry Andric // called after the variable is initialized. 14600b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_image_base); 14610b57cec5SDimitry Andric if (!arg) 14620b57cec5SDimitry Andric return None; 14630b57cec5SDimitry Andric 14640b57cec5SDimitry Andric StringRef s = arg->getValue(); 14650b57cec5SDimitry Andric uint64_t v; 14660b57cec5SDimitry Andric if (!to_integer(s, v)) { 14670b57cec5SDimitry Andric error("-image-base: number expected, but got " + s); 14680b57cec5SDimitry Andric return 0; 14690b57cec5SDimitry Andric } 14700b57cec5SDimitry Andric if ((v % config->maxPageSize) != 0) 14710b57cec5SDimitry Andric warn("-image-base: address isn't multiple of page size: " + s); 14720b57cec5SDimitry Andric return v; 14730b57cec5SDimitry Andric } 14740b57cec5SDimitry Andric 14750b57cec5SDimitry Andric // Parses `--exclude-libs=lib,lib,...`. 14760b57cec5SDimitry Andric // The library names may be delimited by commas or colons. 14770b57cec5SDimitry Andric static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) { 14780b57cec5SDimitry Andric DenseSet<StringRef> ret; 14790b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_exclude_libs)) { 14800b57cec5SDimitry Andric StringRef s = arg->getValue(); 14810b57cec5SDimitry Andric for (;;) { 14820b57cec5SDimitry Andric size_t pos = s.find_first_of(",:"); 14830b57cec5SDimitry Andric if (pos == StringRef::npos) 14840b57cec5SDimitry Andric break; 14850b57cec5SDimitry Andric ret.insert(s.substr(0, pos)); 14860b57cec5SDimitry Andric s = s.substr(pos + 1); 14870b57cec5SDimitry Andric } 14880b57cec5SDimitry Andric ret.insert(s); 14890b57cec5SDimitry Andric } 14900b57cec5SDimitry Andric return ret; 14910b57cec5SDimitry Andric } 14920b57cec5SDimitry Andric 14930b57cec5SDimitry Andric // Handles the -exclude-libs option. If a static library file is specified 14940b57cec5SDimitry Andric // by the -exclude-libs option, all public symbols from the archive become 14950b57cec5SDimitry Andric // private unless otherwise specified by version scripts or something. 14960b57cec5SDimitry Andric // A special library name "ALL" means all archive files. 14970b57cec5SDimitry Andric // 14980b57cec5SDimitry Andric // This is not a popular option, but some programs such as bionic libc use it. 14990b57cec5SDimitry Andric static void excludeLibs(opt::InputArgList &args) { 15000b57cec5SDimitry Andric DenseSet<StringRef> libs = getExcludeLibs(args); 15010b57cec5SDimitry Andric bool all = libs.count("ALL"); 15020b57cec5SDimitry Andric 15030b57cec5SDimitry Andric auto visit = [&](InputFile *file) { 15040b57cec5SDimitry Andric if (!file->archiveName.empty()) 15050b57cec5SDimitry Andric if (all || libs.count(path::filename(file->archiveName))) 15060b57cec5SDimitry Andric for (Symbol *sym : file->getSymbols()) 1507480093f4SDimitry Andric if (!sym->isUndefined() && !sym->isLocal() && sym->file == file) 15080b57cec5SDimitry Andric sym->versionId = VER_NDX_LOCAL; 15090b57cec5SDimitry Andric }; 15100b57cec5SDimitry Andric 15110b57cec5SDimitry Andric for (InputFile *file : objectFiles) 15120b57cec5SDimitry Andric visit(file); 15130b57cec5SDimitry Andric 15140b57cec5SDimitry Andric for (BitcodeFile *file : bitcodeFiles) 15150b57cec5SDimitry Andric visit(file); 15160b57cec5SDimitry Andric } 15170b57cec5SDimitry Andric 1518*5ffd83dbSDimitry Andric // Force Sym to be entered in the output. 15190b57cec5SDimitry Andric static void handleUndefined(Symbol *sym) { 15200b57cec5SDimitry Andric // Since a symbol may not be used inside the program, LTO may 15210b57cec5SDimitry Andric // eliminate it. Mark the symbol as "used" to prevent it. 15220b57cec5SDimitry Andric sym->isUsedInRegularObj = true; 15230b57cec5SDimitry Andric 15240b57cec5SDimitry Andric if (sym->isLazy()) 15250b57cec5SDimitry Andric sym->fetch(); 15260b57cec5SDimitry Andric } 15270b57cec5SDimitry Andric 1528480093f4SDimitry Andric // As an extension to GNU linkers, lld supports a variant of `-u` 15290b57cec5SDimitry Andric // which accepts wildcard patterns. All symbols that match a given 15300b57cec5SDimitry Andric // pattern are handled as if they were given by `-u`. 15310b57cec5SDimitry Andric static void handleUndefinedGlob(StringRef arg) { 15320b57cec5SDimitry Andric Expected<GlobPattern> pat = GlobPattern::create(arg); 15330b57cec5SDimitry Andric if (!pat) { 15340b57cec5SDimitry Andric error("--undefined-glob: " + toString(pat.takeError())); 15350b57cec5SDimitry Andric return; 15360b57cec5SDimitry Andric } 15370b57cec5SDimitry Andric 15380b57cec5SDimitry Andric std::vector<Symbol *> syms; 1539480093f4SDimitry Andric for (Symbol *sym : symtab->symbols()) { 15400b57cec5SDimitry Andric // Calling Sym->fetch() from here is not safe because it may 15410b57cec5SDimitry Andric // add new symbols to the symbol table, invalidating the 15420b57cec5SDimitry Andric // current iterator. So we just keep a note. 15430b57cec5SDimitry Andric if (pat->match(sym->getName())) 15440b57cec5SDimitry Andric syms.push_back(sym); 1545480093f4SDimitry Andric } 15460b57cec5SDimitry Andric 15470b57cec5SDimitry Andric for (Symbol *sym : syms) 15480b57cec5SDimitry Andric handleUndefined(sym); 15490b57cec5SDimitry Andric } 15500b57cec5SDimitry Andric 15510b57cec5SDimitry Andric static void handleLibcall(StringRef name) { 15520b57cec5SDimitry Andric Symbol *sym = symtab->find(name); 15530b57cec5SDimitry Andric if (!sym || !sym->isLazy()) 15540b57cec5SDimitry Andric return; 15550b57cec5SDimitry Andric 15560b57cec5SDimitry Andric MemoryBufferRef mb; 15570b57cec5SDimitry Andric if (auto *lo = dyn_cast<LazyObject>(sym)) 15580b57cec5SDimitry Andric mb = lo->file->mb; 15590b57cec5SDimitry Andric else 15600b57cec5SDimitry Andric mb = cast<LazyArchive>(sym)->getMemberBuffer(); 15610b57cec5SDimitry Andric 15620b57cec5SDimitry Andric if (isBitcode(mb)) 15630b57cec5SDimitry Andric sym->fetch(); 15640b57cec5SDimitry Andric } 15650b57cec5SDimitry Andric 15660b57cec5SDimitry Andric // Replaces common symbols with defined symbols reside in .bss sections. 15670b57cec5SDimitry Andric // This function is called after all symbol names are resolved. As a 15680b57cec5SDimitry Andric // result, the passes after the symbol resolution won't see any 15690b57cec5SDimitry Andric // symbols of type CommonSymbol. 15700b57cec5SDimitry Andric static void replaceCommonSymbols() { 1571480093f4SDimitry Andric for (Symbol *sym : symtab->symbols()) { 15720b57cec5SDimitry Andric auto *s = dyn_cast<CommonSymbol>(sym); 15730b57cec5SDimitry Andric if (!s) 1574480093f4SDimitry Andric continue; 15750b57cec5SDimitry Andric 15760b57cec5SDimitry Andric auto *bss = make<BssSection>("COMMON", s->size, s->alignment); 15770b57cec5SDimitry Andric bss->file = s->file; 15780b57cec5SDimitry Andric bss->markDead(); 15790b57cec5SDimitry Andric inputSections.push_back(bss); 15800b57cec5SDimitry Andric s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type, 15810b57cec5SDimitry Andric /*value=*/0, s->size, bss}); 1582480093f4SDimitry Andric } 15830b57cec5SDimitry Andric } 15840b57cec5SDimitry Andric 15850b57cec5SDimitry Andric // If all references to a DSO happen to be weak, the DSO is not added 15860b57cec5SDimitry Andric // to DT_NEEDED. If that happens, we need to eliminate shared symbols 15870b57cec5SDimitry Andric // created from the DSO. Otherwise, they become dangling references 15880b57cec5SDimitry Andric // that point to a non-existent DSO. 15890b57cec5SDimitry Andric static void demoteSharedSymbols() { 1590480093f4SDimitry Andric for (Symbol *sym : symtab->symbols()) { 15910b57cec5SDimitry Andric auto *s = dyn_cast<SharedSymbol>(sym); 15920b57cec5SDimitry Andric if (!s || s->getFile().isNeeded) 1593480093f4SDimitry Andric continue; 15940b57cec5SDimitry Andric 15950b57cec5SDimitry Andric bool used = s->used; 15960b57cec5SDimitry Andric s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type}); 15970b57cec5SDimitry Andric s->used = used; 1598480093f4SDimitry Andric } 15990b57cec5SDimitry Andric } 16000b57cec5SDimitry Andric 16010b57cec5SDimitry Andric // The section referred to by `s` is considered address-significant. Set the 16020b57cec5SDimitry Andric // keepUnique flag on the section if appropriate. 16030b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 16040b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 16050b57cec5SDimitry Andric if (d->section) 16060b57cec5SDimitry Andric // We don't need to keep text sections unique under --icf=all even if they 16070b57cec5SDimitry Andric // are address-significant. 16080b57cec5SDimitry Andric if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR)) 16090b57cec5SDimitry Andric d->section->keepUnique = true; 16100b57cec5SDimitry Andric } 16110b57cec5SDimitry Andric 16120b57cec5SDimitry Andric // Record sections that define symbols mentioned in --keep-unique <symbol> 16130b57cec5SDimitry Andric // and symbols referred to by address-significance tables. These sections are 16140b57cec5SDimitry Andric // ineligible for ICF. 16150b57cec5SDimitry Andric template <class ELFT> 16160b57cec5SDimitry Andric static void findKeepUniqueSections(opt::InputArgList &args) { 16170b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_keep_unique)) { 16180b57cec5SDimitry Andric StringRef name = arg->getValue(); 16190b57cec5SDimitry Andric auto *d = dyn_cast_or_null<Defined>(symtab->find(name)); 16200b57cec5SDimitry Andric if (!d || !d->section) { 16210b57cec5SDimitry Andric warn("could not find symbol " + name + " to keep unique"); 16220b57cec5SDimitry Andric continue; 16230b57cec5SDimitry Andric } 16240b57cec5SDimitry Andric d->section->keepUnique = true; 16250b57cec5SDimitry Andric } 16260b57cec5SDimitry Andric 16270b57cec5SDimitry Andric // --icf=all --ignore-data-address-equality means that we can ignore 16280b57cec5SDimitry Andric // the dynsym and address-significance tables entirely. 16290b57cec5SDimitry Andric if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality) 16300b57cec5SDimitry Andric return; 16310b57cec5SDimitry Andric 16320b57cec5SDimitry Andric // Symbols in the dynsym could be address-significant in other executables 16330b57cec5SDimitry Andric // or DSOs, so we conservatively mark them as address-significant. 1634480093f4SDimitry Andric for (Symbol *sym : symtab->symbols()) 16350b57cec5SDimitry Andric if (sym->includeInDynsym()) 16360b57cec5SDimitry Andric markAddrsig(sym); 16370b57cec5SDimitry Andric 16380b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 16390b57cec5SDimitry Andric // referenced symbol as address-significant. 16400b57cec5SDimitry Andric for (InputFile *f : objectFiles) { 16410b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(f); 16420b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 16430b57cec5SDimitry Andric if (obj->addrsigSec) { 16440b57cec5SDimitry Andric ArrayRef<uint8_t> contents = 16450b57cec5SDimitry Andric check(obj->getObj().getSectionContents(obj->addrsigSec)); 16460b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 16470b57cec5SDimitry Andric while (cur != contents.end()) { 16480b57cec5SDimitry Andric unsigned size; 16490b57cec5SDimitry Andric const char *err; 16500b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 16510b57cec5SDimitry Andric if (err) 16520b57cec5SDimitry Andric fatal(toString(f) + ": could not decode addrsig section: " + err); 16530b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 16540b57cec5SDimitry Andric cur += size; 16550b57cec5SDimitry Andric } 16560b57cec5SDimitry Andric } else { 16570b57cec5SDimitry Andric // If an object file does not have an address-significance table, 16580b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 16590b57cec5SDimitry Andric for (Symbol *s : syms) 16600b57cec5SDimitry Andric markAddrsig(s); 16610b57cec5SDimitry Andric } 16620b57cec5SDimitry Andric } 16630b57cec5SDimitry Andric } 16640b57cec5SDimitry Andric 16650b57cec5SDimitry Andric // This function reads a symbol partition specification section. These sections 16660b57cec5SDimitry Andric // are used to control which partition a symbol is allocated to. See 16670b57cec5SDimitry Andric // https://lld.llvm.org/Partitions.html for more details on partitions. 16680b57cec5SDimitry Andric template <typename ELFT> 16690b57cec5SDimitry Andric static void readSymbolPartitionSection(InputSectionBase *s) { 16700b57cec5SDimitry Andric // Read the relocation that refers to the partition's entry point symbol. 16710b57cec5SDimitry Andric Symbol *sym; 16720b57cec5SDimitry Andric if (s->areRelocsRela) 16730b57cec5SDimitry Andric sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]); 16740b57cec5SDimitry Andric else 16750b57cec5SDimitry Andric sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]); 16760b57cec5SDimitry Andric if (!isa<Defined>(sym) || !sym->includeInDynsym()) 16770b57cec5SDimitry Andric return; 16780b57cec5SDimitry Andric 16790b57cec5SDimitry Andric StringRef partName = reinterpret_cast<const char *>(s->data().data()); 16800b57cec5SDimitry Andric for (Partition &part : partitions) { 16810b57cec5SDimitry Andric if (part.name == partName) { 16820b57cec5SDimitry Andric sym->partition = part.getNumber(); 16830b57cec5SDimitry Andric return; 16840b57cec5SDimitry Andric } 16850b57cec5SDimitry Andric } 16860b57cec5SDimitry Andric 16870b57cec5SDimitry Andric // Forbid partitions from being used on incompatible targets, and forbid them 16880b57cec5SDimitry Andric // from being used together with various linker features that assume a single 16890b57cec5SDimitry Andric // set of output sections. 16900b57cec5SDimitry Andric if (script->hasSectionsCommand) 16910b57cec5SDimitry Andric error(toString(s->file) + 16920b57cec5SDimitry Andric ": partitions cannot be used with the SECTIONS command"); 16930b57cec5SDimitry Andric if (script->hasPhdrsCommands()) 16940b57cec5SDimitry Andric error(toString(s->file) + 16950b57cec5SDimitry Andric ": partitions cannot be used with the PHDRS command"); 16960b57cec5SDimitry Andric if (!config->sectionStartMap.empty()) 16970b57cec5SDimitry Andric error(toString(s->file) + ": partitions cannot be used with " 16980b57cec5SDimitry Andric "--section-start, -Ttext, -Tdata or -Tbss"); 16990b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 17000b57cec5SDimitry Andric error(toString(s->file) + ": partitions cannot be used on this target"); 17010b57cec5SDimitry Andric 17020b57cec5SDimitry Andric // Impose a limit of no more than 254 partitions. This limit comes from the 17030b57cec5SDimitry Andric // sizes of the Partition fields in InputSectionBase and Symbol, as well as 17040b57cec5SDimitry Andric // the amount of space devoted to the partition number in RankFlags. 17050b57cec5SDimitry Andric if (partitions.size() == 254) 17060b57cec5SDimitry Andric fatal("may not have more than 254 partitions"); 17070b57cec5SDimitry Andric 17080b57cec5SDimitry Andric partitions.emplace_back(); 17090b57cec5SDimitry Andric Partition &newPart = partitions.back(); 17100b57cec5SDimitry Andric newPart.name = partName; 17110b57cec5SDimitry Andric sym->partition = newPart.getNumber(); 17120b57cec5SDimitry Andric } 17130b57cec5SDimitry Andric 17140b57cec5SDimitry Andric static Symbol *addUndefined(StringRef name) { 17150b57cec5SDimitry Andric return symtab->addSymbol( 17160b57cec5SDimitry Andric Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0}); 17170b57cec5SDimitry Andric } 17180b57cec5SDimitry Andric 1719*5ffd83dbSDimitry Andric static Symbol *addUnusedUndefined(StringRef name) { 1720*5ffd83dbSDimitry Andric Undefined sym{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0}; 1721*5ffd83dbSDimitry Andric sym.isUsedInRegularObj = false; 1722*5ffd83dbSDimitry Andric return symtab->addSymbol(sym); 1723*5ffd83dbSDimitry Andric } 1724*5ffd83dbSDimitry Andric 17250b57cec5SDimitry Andric // This function is where all the optimizations of link-time 17260b57cec5SDimitry Andric // optimization takes place. When LTO is in use, some input files are 17270b57cec5SDimitry Andric // not in native object file format but in the LLVM bitcode format. 17280b57cec5SDimitry Andric // This function compiles bitcode files into a few big native files 17290b57cec5SDimitry Andric // using LLVM functions and replaces bitcode symbols with the results. 17300b57cec5SDimitry Andric // Because all bitcode files that the program consists of are passed to 17310b57cec5SDimitry Andric // the compiler at once, it can do a whole-program optimization. 17320b57cec5SDimitry Andric template <class ELFT> void LinkerDriver::compileBitcodeFiles() { 1733*5ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("LTO"); 17340b57cec5SDimitry Andric // Compile bitcode files and replace bitcode symbols. 17350b57cec5SDimitry Andric lto.reset(new BitcodeCompiler); 17360b57cec5SDimitry Andric for (BitcodeFile *file : bitcodeFiles) 17370b57cec5SDimitry Andric lto->add(*file); 17380b57cec5SDimitry Andric 17390b57cec5SDimitry Andric for (InputFile *file : lto->compile()) { 17400b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(file); 17410b57cec5SDimitry Andric obj->parse(/*ignoreComdats=*/true); 1742*5ffd83dbSDimitry Andric 1743*5ffd83dbSDimitry Andric // Parse '@' in symbol names for non-relocatable output. 1744*5ffd83dbSDimitry Andric if (!config->relocatable) 17450b57cec5SDimitry Andric for (Symbol *sym : obj->getGlobalSymbols()) 17460b57cec5SDimitry Andric sym->parseSymbolVersion(); 17470b57cec5SDimitry Andric objectFiles.push_back(file); 17480b57cec5SDimitry Andric } 17490b57cec5SDimitry Andric } 17500b57cec5SDimitry Andric 17510b57cec5SDimitry Andric // The --wrap option is a feature to rename symbols so that you can write 17520b57cec5SDimitry Andric // wrappers for existing functions. If you pass `-wrap=foo`, all 17530b57cec5SDimitry Andric // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are 17540b57cec5SDimitry Andric // expected to write `wrap_foo` function as a wrapper). The original 17550b57cec5SDimitry Andric // symbol becomes accessible as `real_foo`, so you can call that from your 17560b57cec5SDimitry Andric // wrapper. 17570b57cec5SDimitry Andric // 17580b57cec5SDimitry Andric // This data structure is instantiated for each -wrap option. 17590b57cec5SDimitry Andric struct WrappedSymbol { 17600b57cec5SDimitry Andric Symbol *sym; 17610b57cec5SDimitry Andric Symbol *real; 17620b57cec5SDimitry Andric Symbol *wrap; 17630b57cec5SDimitry Andric }; 17640b57cec5SDimitry Andric 17650b57cec5SDimitry Andric // Handles -wrap option. 17660b57cec5SDimitry Andric // 17670b57cec5SDimitry Andric // This function instantiates wrapper symbols. At this point, they seem 17680b57cec5SDimitry Andric // like they are not being used at all, so we explicitly set some flags so 17690b57cec5SDimitry Andric // that LTO won't eliminate them. 17700b57cec5SDimitry Andric static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) { 17710b57cec5SDimitry Andric std::vector<WrappedSymbol> v; 17720b57cec5SDimitry Andric DenseSet<StringRef> seen; 17730b57cec5SDimitry Andric 17740b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wrap)) { 17750b57cec5SDimitry Andric StringRef name = arg->getValue(); 17760b57cec5SDimitry Andric if (!seen.insert(name).second) 17770b57cec5SDimitry Andric continue; 17780b57cec5SDimitry Andric 17790b57cec5SDimitry Andric Symbol *sym = symtab->find(name); 17800b57cec5SDimitry Andric if (!sym) 17810b57cec5SDimitry Andric continue; 17820b57cec5SDimitry Andric 17830b57cec5SDimitry Andric Symbol *real = addUndefined(saver.save("__real_" + name)); 17840b57cec5SDimitry Andric Symbol *wrap = addUndefined(saver.save("__wrap_" + name)); 17850b57cec5SDimitry Andric v.push_back({sym, real, wrap}); 17860b57cec5SDimitry Andric 17870b57cec5SDimitry Andric // We want to tell LTO not to inline symbols to be overwritten 17880b57cec5SDimitry Andric // because LTO doesn't know the final symbol contents after renaming. 17890b57cec5SDimitry Andric real->canInline = false; 17900b57cec5SDimitry Andric sym->canInline = false; 17910b57cec5SDimitry Andric 17920b57cec5SDimitry Andric // Tell LTO not to eliminate these symbols. 17930b57cec5SDimitry Andric sym->isUsedInRegularObj = true; 17940b57cec5SDimitry Andric wrap->isUsedInRegularObj = true; 17950b57cec5SDimitry Andric } 17960b57cec5SDimitry Andric return v; 17970b57cec5SDimitry Andric } 17980b57cec5SDimitry Andric 17990b57cec5SDimitry Andric // Do renaming for -wrap by updating pointers to symbols. 18000b57cec5SDimitry Andric // 18010b57cec5SDimitry Andric // When this function is executed, only InputFiles and symbol table 18020b57cec5SDimitry Andric // contain pointers to symbol objects. We visit them to replace pointers, 18030b57cec5SDimitry Andric // so that wrapped symbols are swapped as instructed by the command line. 18040b57cec5SDimitry Andric static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) { 18050b57cec5SDimitry Andric DenseMap<Symbol *, Symbol *> map; 18060b57cec5SDimitry Andric for (const WrappedSymbol &w : wrapped) { 18070b57cec5SDimitry Andric map[w.sym] = w.wrap; 18080b57cec5SDimitry Andric map[w.real] = w.sym; 18090b57cec5SDimitry Andric } 18100b57cec5SDimitry Andric 18110b57cec5SDimitry Andric // Update pointers in input files. 18120b57cec5SDimitry Andric parallelForEach(objectFiles, [&](InputFile *file) { 18130b57cec5SDimitry Andric MutableArrayRef<Symbol *> syms = file->getMutableSymbols(); 18140b57cec5SDimitry Andric for (size_t i = 0, e = syms.size(); i != e; ++i) 18150b57cec5SDimitry Andric if (Symbol *s = map.lookup(syms[i])) 18160b57cec5SDimitry Andric syms[i] = s; 18170b57cec5SDimitry Andric }); 18180b57cec5SDimitry Andric 18190b57cec5SDimitry Andric // Update pointers in the symbol table. 18200b57cec5SDimitry Andric for (const WrappedSymbol &w : wrapped) 18210b57cec5SDimitry Andric symtab->wrap(w.sym, w.real, w.wrap); 18220b57cec5SDimitry Andric } 18230b57cec5SDimitry Andric 18240b57cec5SDimitry Andric // To enable CET (x86's hardware-assited control flow enforcement), each 18250b57cec5SDimitry Andric // source file must be compiled with -fcf-protection. Object files compiled 18260b57cec5SDimitry Andric // with the flag contain feature flags indicating that they are compatible 18270b57cec5SDimitry Andric // with CET. We enable the feature only when all object files are compatible 18280b57cec5SDimitry Andric // with CET. 18290b57cec5SDimitry Andric // 18300b57cec5SDimitry Andric // This is also the case with AARCH64's BTI and PAC which use the similar 18310b57cec5SDimitry Andric // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism. 18320b57cec5SDimitry Andric template <class ELFT> static uint32_t getAndFeatures() { 18330b57cec5SDimitry Andric if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 18340b57cec5SDimitry Andric config->emachine != EM_AARCH64) 18350b57cec5SDimitry Andric return 0; 18360b57cec5SDimitry Andric 18370b57cec5SDimitry Andric uint32_t ret = -1; 18380b57cec5SDimitry Andric for (InputFile *f : objectFiles) { 18390b57cec5SDimitry Andric uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures; 1840*5ffd83dbSDimitry Andric if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) { 1841*5ffd83dbSDimitry Andric warn(toString(f) + ": -z force-bti: file does not have " 1842*5ffd83dbSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 18430b57cec5SDimitry Andric features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI; 1844480093f4SDimitry Andric } else if (config->zForceIbt && 1845480093f4SDimitry Andric !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) { 1846480093f4SDimitry Andric warn(toString(f) + ": -z force-ibt: file does not have " 1847480093f4SDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 1848480093f4SDimitry Andric features |= GNU_PROPERTY_X86_FEATURE_1_IBT; 1849480093f4SDimitry Andric } 1850*5ffd83dbSDimitry Andric if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) { 1851*5ffd83dbSDimitry Andric warn(toString(f) + ": -z pac-plt: file does not have " 1852*5ffd83dbSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property"); 1853*5ffd83dbSDimitry Andric features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC; 1854*5ffd83dbSDimitry Andric } 18550b57cec5SDimitry Andric ret &= features; 18560b57cec5SDimitry Andric } 18570b57cec5SDimitry Andric 1858480093f4SDimitry Andric // Force enable Shadow Stack. 1859480093f4SDimitry Andric if (config->zShstk) 1860480093f4SDimitry Andric ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK; 18610b57cec5SDimitry Andric 18620b57cec5SDimitry Andric return ret; 18630b57cec5SDimitry Andric } 18640b57cec5SDimitry Andric 18650b57cec5SDimitry Andric // Do actual linking. Note that when this function is called, 18660b57cec5SDimitry Andric // all linker scripts have already been parsed. 18670b57cec5SDimitry Andric template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) { 1868*5ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link")); 18690b57cec5SDimitry Andric // If a -hash-style option was not given, set to a default value, 18700b57cec5SDimitry Andric // which varies depending on the target. 18710b57cec5SDimitry Andric if (!args.hasArg(OPT_hash_style)) { 18720b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 18730b57cec5SDimitry Andric config->sysvHash = true; 18740b57cec5SDimitry Andric else 18750b57cec5SDimitry Andric config->sysvHash = config->gnuHash = true; 18760b57cec5SDimitry Andric } 18770b57cec5SDimitry Andric 18780b57cec5SDimitry Andric // Default output filename is "a.out" by the Unix tradition. 18790b57cec5SDimitry Andric if (config->outputFile.empty()) 18800b57cec5SDimitry Andric config->outputFile = "a.out"; 18810b57cec5SDimitry Andric 18820b57cec5SDimitry Andric // Fail early if the output file or map file is not writable. If a user has a 18830b57cec5SDimitry Andric // long link, e.g. due to a large LTO link, they do not wish to run it and 18840b57cec5SDimitry Andric // find that it failed because there was a mistake in their command-line. 18850b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) 18860b57cec5SDimitry Andric error("cannot open output file " + config->outputFile + ": " + e.message()); 18870b57cec5SDimitry Andric if (auto e = tryCreateFile(config->mapFile)) 18880b57cec5SDimitry Andric error("cannot open map file " + config->mapFile + ": " + e.message()); 18890b57cec5SDimitry Andric if (errorCount()) 18900b57cec5SDimitry Andric return; 18910b57cec5SDimitry Andric 18920b57cec5SDimitry Andric // Use default entry point name if no name was given via the command 18930b57cec5SDimitry Andric // line nor linker scripts. For some reason, MIPS entry point name is 18940b57cec5SDimitry Andric // different from others. 18950b57cec5SDimitry Andric config->warnMissingEntry = 18960b57cec5SDimitry Andric (!config->entry.empty() || (!config->shared && !config->relocatable)); 18970b57cec5SDimitry Andric if (config->entry.empty() && !config->relocatable) 18980b57cec5SDimitry Andric config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start"; 18990b57cec5SDimitry Andric 19000b57cec5SDimitry Andric // Handle --trace-symbol. 19010b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_trace_symbol)) 19020b57cec5SDimitry Andric symtab->insert(arg->getValue())->traced = true; 19030b57cec5SDimitry Andric 1904*5ffd83dbSDimitry Andric // Handle -u/--undefined before input files. If both a.a and b.so define foo, 1905*5ffd83dbSDimitry Andric // -u foo a.a b.so will fetch a.a. 1906*5ffd83dbSDimitry Andric for (StringRef name : config->undefined) 1907*5ffd83dbSDimitry Andric addUnusedUndefined(name); 1908*5ffd83dbSDimitry Andric 19090b57cec5SDimitry Andric // Add all files to the symbol table. This will add almost all 19100b57cec5SDimitry Andric // symbols that we need to the symbol table. This process might 19110b57cec5SDimitry Andric // add files to the link, via autolinking, these files are always 19120b57cec5SDimitry Andric // appended to the Files vector. 1913*5ffd83dbSDimitry Andric { 1914*5ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("Parse input files"); 19150b57cec5SDimitry Andric for (size_t i = 0; i < files.size(); ++i) 19160b57cec5SDimitry Andric parseFile(files[i]); 1917*5ffd83dbSDimitry Andric } 19180b57cec5SDimitry Andric 19190b57cec5SDimitry Andric // Now that we have every file, we can decide if we will need a 19200b57cec5SDimitry Andric // dynamic symbol table. 19210b57cec5SDimitry Andric // We need one if we were asked to export dynamic symbols or if we are 19220b57cec5SDimitry Andric // producing a shared library. 19230b57cec5SDimitry Andric // We also need one if any shared libraries are used and for pie executables 19240b57cec5SDimitry Andric // (probably because the dynamic linker needs it). 19250b57cec5SDimitry Andric config->hasDynSymTab = 19260b57cec5SDimitry Andric !sharedFiles.empty() || config->isPic || config->exportDynamic; 19270b57cec5SDimitry Andric 19280b57cec5SDimitry Andric // Some symbols (such as __ehdr_start) are defined lazily only when there 19290b57cec5SDimitry Andric // are undefined symbols for them, so we add these to trigger that logic. 19300b57cec5SDimitry Andric for (StringRef name : script->referencedSymbols) 19310b57cec5SDimitry Andric addUndefined(name); 19320b57cec5SDimitry Andric 1933*5ffd83dbSDimitry Andric // Prevent LTO from removing any definition referenced by -u. 1934*5ffd83dbSDimitry Andric for (StringRef name : config->undefined) 1935*5ffd83dbSDimitry Andric if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name))) 1936*5ffd83dbSDimitry Andric sym->isUsedInRegularObj = true; 19370b57cec5SDimitry Andric 19380b57cec5SDimitry Andric // If an entry symbol is in a static archive, pull out that file now. 19390b57cec5SDimitry Andric if (Symbol *sym = symtab->find(config->entry)) 19400b57cec5SDimitry Andric handleUndefined(sym); 19410b57cec5SDimitry Andric 19420b57cec5SDimitry Andric // Handle the `--undefined-glob <pattern>` options. 19430b57cec5SDimitry Andric for (StringRef pat : args::getStrings(args, OPT_undefined_glob)) 19440b57cec5SDimitry Andric handleUndefinedGlob(pat); 19450b57cec5SDimitry Andric 1946480093f4SDimitry Andric // Mark -init and -fini symbols so that the LTO doesn't eliminate them. 1947*5ffd83dbSDimitry Andric if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init))) 1948480093f4SDimitry Andric sym->isUsedInRegularObj = true; 1949*5ffd83dbSDimitry Andric if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini))) 1950480093f4SDimitry Andric sym->isUsedInRegularObj = true; 1951480093f4SDimitry Andric 19520b57cec5SDimitry Andric // If any of our inputs are bitcode files, the LTO code generator may create 19530b57cec5SDimitry Andric // references to certain library functions that might not be explicit in the 19540b57cec5SDimitry Andric // bitcode file's symbol table. If any of those library functions are defined 19550b57cec5SDimitry Andric // in a bitcode file in an archive member, we need to arrange to use LTO to 19560b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 19570b57cec5SDimitry Andric // 19580b57cec5SDimitry Andric // However, adding all libcall symbols to the link can have undesired 19590b57cec5SDimitry Andric // consequences. For example, the libgcc implementation of 19600b57cec5SDimitry Andric // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 19610b57cec5SDimitry Andric // that aborts the program if the Linux kernel does not support 64-bit 19620b57cec5SDimitry Andric // atomics, which would prevent the program from running even if it does not 19630b57cec5SDimitry Andric // use 64-bit atomics. 19640b57cec5SDimitry Andric // 19650b57cec5SDimitry Andric // Therefore, we only add libcall symbols to the link before LTO if we have 19660b57cec5SDimitry Andric // to, i.e. if the symbol's definition is in bitcode. Any other required 19670b57cec5SDimitry Andric // libcall symbols will be added to the link after LTO when we add the LTO 19680b57cec5SDimitry Andric // object file to the link. 19690b57cec5SDimitry Andric if (!bitcodeFiles.empty()) 197085868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 19710b57cec5SDimitry Andric handleLibcall(s); 19720b57cec5SDimitry Andric 19730b57cec5SDimitry Andric // Return if there were name resolution errors. 19740b57cec5SDimitry Andric if (errorCount()) 19750b57cec5SDimitry Andric return; 19760b57cec5SDimitry Andric 19770b57cec5SDimitry Andric // We want to declare linker script's symbols early, 19780b57cec5SDimitry Andric // so that we can version them. 19790b57cec5SDimitry Andric // They also might be exported if referenced by DSOs. 19800b57cec5SDimitry Andric script->declareSymbols(); 19810b57cec5SDimitry Andric 19820b57cec5SDimitry Andric // Handle the -exclude-libs option. 19830b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_libs)) 19840b57cec5SDimitry Andric excludeLibs(args); 19850b57cec5SDimitry Andric 19860b57cec5SDimitry Andric // Create elfHeader early. We need a dummy section in 19870b57cec5SDimitry Andric // addReservedSymbols to mark the created symbols as not absolute. 19880b57cec5SDimitry Andric Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC); 19890b57cec5SDimitry Andric Out::elfHeader->size = sizeof(typename ELFT::Ehdr); 19900b57cec5SDimitry Andric 19910b57cec5SDimitry Andric // Create wrapped symbols for -wrap option. 19920b57cec5SDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 19930b57cec5SDimitry Andric 19940b57cec5SDimitry Andric // We need to create some reserved symbols such as _end. Create them. 19950b57cec5SDimitry Andric if (!config->relocatable) 19960b57cec5SDimitry Andric addReservedSymbols(); 19970b57cec5SDimitry Andric 19980b57cec5SDimitry Andric // Apply version scripts. 19990b57cec5SDimitry Andric // 20000b57cec5SDimitry Andric // For a relocatable output, version scripts don't make sense, and 20010b57cec5SDimitry Andric // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 20020b57cec5SDimitry Andric // name "foo@ver1") rather do harm, so we don't call this if -r is given. 20030b57cec5SDimitry Andric if (!config->relocatable) 20040b57cec5SDimitry Andric symtab->scanVersionScript(); 20050b57cec5SDimitry Andric 20060b57cec5SDimitry Andric // Do link-time optimization if given files are LLVM bitcode files. 20070b57cec5SDimitry Andric // This compiles bitcode files into real object files. 20080b57cec5SDimitry Andric // 20090b57cec5SDimitry Andric // With this the symbol table should be complete. After this, no new names 20100b57cec5SDimitry Andric // except a few linker-synthesized ones will be added to the symbol table. 20110b57cec5SDimitry Andric compileBitcodeFiles<ELFT>(); 2012*5ffd83dbSDimitry Andric 2013*5ffd83dbSDimitry Andric // Symbol resolution finished. Report backward reference problems. 2014*5ffd83dbSDimitry Andric reportBackrefs(); 20150b57cec5SDimitry Andric if (errorCount()) 20160b57cec5SDimitry Andric return; 20170b57cec5SDimitry Andric 20180b57cec5SDimitry Andric // If -thinlto-index-only is given, we should create only "index 20190b57cec5SDimitry Andric // files" and not object files. Index file creation is already done 20200b57cec5SDimitry Andric // in addCombinedLTOObject, so we are done if that's the case. 2021*5ffd83dbSDimitry Andric // Likewise, --plugin-opt=emit-llvm and --plugin-opt=emit-asm are the 2022*5ffd83dbSDimitry Andric // options to create output files in bitcode or assembly code 2023*5ffd83dbSDimitry Andric // repsectively. No object files are generated. 2024*5ffd83dbSDimitry Andric // Also bail out here when only certain thinLTO modules are specified for 2025*5ffd83dbSDimitry Andric // compilation. The intermediate object file are the expected output. 2026*5ffd83dbSDimitry Andric if (config->thinLTOIndexOnly || config->emitLLVM || config->ltoEmitAsm || 2027*5ffd83dbSDimitry Andric !config->thinLTOModulesToCompile.empty()) 20280b57cec5SDimitry Andric return; 20290b57cec5SDimitry Andric 20300b57cec5SDimitry Andric // Apply symbol renames for -wrap. 20310b57cec5SDimitry Andric if (!wrapped.empty()) 20320b57cec5SDimitry Andric wrapSymbols(wrapped); 20330b57cec5SDimitry Andric 20340b57cec5SDimitry Andric // Now that we have a complete list of input files. 20350b57cec5SDimitry Andric // Beyond this point, no new files are added. 20360b57cec5SDimitry Andric // Aggregate all input sections into one place. 20370b57cec5SDimitry Andric for (InputFile *f : objectFiles) 20380b57cec5SDimitry Andric for (InputSectionBase *s : f->getSections()) 20390b57cec5SDimitry Andric if (s && s != &InputSection::discarded) 20400b57cec5SDimitry Andric inputSections.push_back(s); 20410b57cec5SDimitry Andric for (BinaryFile *f : binaryFiles) 20420b57cec5SDimitry Andric for (InputSectionBase *s : f->getSections()) 20430b57cec5SDimitry Andric inputSections.push_back(cast<InputSection>(s)); 20440b57cec5SDimitry Andric 20450b57cec5SDimitry Andric llvm::erase_if(inputSections, [](InputSectionBase *s) { 20460b57cec5SDimitry Andric if (s->type == SHT_LLVM_SYMPART) { 20470b57cec5SDimitry Andric readSymbolPartitionSection<ELFT>(s); 20480b57cec5SDimitry Andric return true; 20490b57cec5SDimitry Andric } 20500b57cec5SDimitry Andric 20510b57cec5SDimitry Andric // We do not want to emit debug sections if --strip-all 20520b57cec5SDimitry Andric // or -strip-debug are given. 2053d65cd7a5SDimitry Andric if (config->strip == StripPolicy::None) 2054d65cd7a5SDimitry Andric return false; 2055d65cd7a5SDimitry Andric 2056d65cd7a5SDimitry Andric if (isDebugSection(*s)) 2057d65cd7a5SDimitry Andric return true; 2058d65cd7a5SDimitry Andric if (auto *isec = dyn_cast<InputSection>(s)) 2059d65cd7a5SDimitry Andric if (InputSectionBase *rel = isec->getRelocatedSection()) 2060d65cd7a5SDimitry Andric if (isDebugSection(*rel)) 2061d65cd7a5SDimitry Andric return true; 2062d65cd7a5SDimitry Andric 2063d65cd7a5SDimitry Andric return false; 20640b57cec5SDimitry Andric }); 20650b57cec5SDimitry Andric 20660b57cec5SDimitry Andric // Now that the number of partitions is fixed, save a pointer to the main 20670b57cec5SDimitry Andric // partition. 20680b57cec5SDimitry Andric mainPart = &partitions[0]; 20690b57cec5SDimitry Andric 20700b57cec5SDimitry Andric // Read .note.gnu.property sections from input object files which 20710b57cec5SDimitry Andric // contain a hint to tweak linker's and loader's behaviors. 20720b57cec5SDimitry Andric config->andFeatures = getAndFeatures<ELFT>(); 20730b57cec5SDimitry Andric 20740b57cec5SDimitry Andric // The Target instance handles target-specific stuff, such as applying 20750b57cec5SDimitry Andric // relocations or writing a PLT section. It also contains target-dependent 20760b57cec5SDimitry Andric // values such as a default image base address. 20770b57cec5SDimitry Andric target = getTarget(); 20780b57cec5SDimitry Andric 20790b57cec5SDimitry Andric config->eflags = target->calcEFlags(); 20800b57cec5SDimitry Andric // maxPageSize (sometimes called abi page size) is the maximum page size that 20810b57cec5SDimitry Andric // the output can be run on. For example if the OS can use 4k or 64k page 20820b57cec5SDimitry Andric // sizes then maxPageSize must be 64k for the output to be useable on both. 20830b57cec5SDimitry Andric // All important alignment decisions must use this value. 20840b57cec5SDimitry Andric config->maxPageSize = getMaxPageSize(args); 20850b57cec5SDimitry Andric // commonPageSize is the most common page size that the output will be run on. 20860b57cec5SDimitry Andric // For example if an OS can use 4k or 64k page sizes and 4k is more common 20870b57cec5SDimitry Andric // than 64k then commonPageSize is set to 4k. commonPageSize can be used for 20880b57cec5SDimitry Andric // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 20890b57cec5SDimitry Andric // is limited to writing trap instructions on the last executable segment. 20900b57cec5SDimitry Andric config->commonPageSize = getCommonPageSize(args); 20910b57cec5SDimitry Andric 20920b57cec5SDimitry Andric config->imageBase = getImageBase(args); 20930b57cec5SDimitry Andric 20940b57cec5SDimitry Andric if (config->emachine == EM_ARM) { 20950b57cec5SDimitry Andric // FIXME: These warnings can be removed when lld only uses these features 20960b57cec5SDimitry Andric // when the input objects have been compiled with an architecture that 20970b57cec5SDimitry Andric // supports them. 20980b57cec5SDimitry Andric if (config->armHasBlx == false) 20990b57cec5SDimitry Andric warn("lld uses blx instruction, no object with architecture supporting " 21000b57cec5SDimitry Andric "feature detected"); 21010b57cec5SDimitry Andric } 21020b57cec5SDimitry Andric 210385868e8aSDimitry Andric // This adds a .comment section containing a version string. 21040b57cec5SDimitry Andric if (!config->relocatable) 21050b57cec5SDimitry Andric inputSections.push_back(createCommentSection()); 21060b57cec5SDimitry Andric 21070b57cec5SDimitry Andric // Replace common symbols with regular symbols. 21080b57cec5SDimitry Andric replaceCommonSymbols(); 21090b57cec5SDimitry Andric 211085868e8aSDimitry Andric // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection. 21110b57cec5SDimitry Andric splitSections<ELFT>(); 211285868e8aSDimitry Andric 211385868e8aSDimitry Andric // Garbage collection and removal of shared symbols from unused shared objects. 21140b57cec5SDimitry Andric markLive<ELFT>(); 21150b57cec5SDimitry Andric demoteSharedSymbols(); 211685868e8aSDimitry Andric 211785868e8aSDimitry Andric // Make copies of any input sections that need to be copied into each 211885868e8aSDimitry Andric // partition. 211985868e8aSDimitry Andric copySectionsIntoPartitions(); 212085868e8aSDimitry Andric 212185868e8aSDimitry Andric // Create synthesized sections such as .got and .plt. This is called before 212285868e8aSDimitry Andric // processSectionCommands() so that they can be placed by SECTIONS commands. 212385868e8aSDimitry Andric createSyntheticSections<ELFT>(); 212485868e8aSDimitry Andric 212585868e8aSDimitry Andric // Some input sections that are used for exception handling need to be moved 212685868e8aSDimitry Andric // into synthetic sections. Do that now so that they aren't assigned to 212785868e8aSDimitry Andric // output sections in the usual way. 212885868e8aSDimitry Andric if (!config->relocatable) 212985868e8aSDimitry Andric combineEhSections(); 213085868e8aSDimitry Andric 213185868e8aSDimitry Andric // Create output sections described by SECTIONS commands. 213285868e8aSDimitry Andric script->processSectionCommands(); 213385868e8aSDimitry Andric 213485868e8aSDimitry Andric // Linker scripts control how input sections are assigned to output sections. 213585868e8aSDimitry Andric // Input sections that were not handled by scripts are called "orphans", and 213685868e8aSDimitry Andric // they are assigned to output sections by the default rule. Process that. 213785868e8aSDimitry Andric script->addOrphanSections(); 213885868e8aSDimitry Andric 213985868e8aSDimitry Andric // Migrate InputSectionDescription::sectionBases to sections. This includes 214085868e8aSDimitry Andric // merging MergeInputSections into a single MergeSyntheticSection. From this 214185868e8aSDimitry Andric // point onwards InputSectionDescription::sections should be used instead of 214285868e8aSDimitry Andric // sectionBases. 214385868e8aSDimitry Andric for (BaseCommand *base : script->sectionCommands) 214485868e8aSDimitry Andric if (auto *sec = dyn_cast<OutputSection>(base)) 214585868e8aSDimitry Andric sec->finalizeInputSections(); 214685868e8aSDimitry Andric llvm::erase_if(inputSections, 214785868e8aSDimitry Andric [](InputSectionBase *s) { return isa<MergeInputSection>(s); }); 214885868e8aSDimitry Andric 214985868e8aSDimitry Andric // Two input sections with different output sections should not be folded. 215085868e8aSDimitry Andric // ICF runs after processSectionCommands() so that we know the output sections. 21510b57cec5SDimitry Andric if (config->icf != ICFLevel::None) { 21520b57cec5SDimitry Andric findKeepUniqueSections<ELFT>(args); 21530b57cec5SDimitry Andric doIcf<ELFT>(); 21540b57cec5SDimitry Andric } 21550b57cec5SDimitry Andric 21560b57cec5SDimitry Andric // Read the callgraph now that we know what was gced or icfed 21570b57cec5SDimitry Andric if (config->callGraphProfileSort) { 21580b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) 21590b57cec5SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 21600b57cec5SDimitry Andric readCallGraph(*buffer); 21610b57cec5SDimitry Andric readCallGraphsFromObjectFiles<ELFT>(); 21620b57cec5SDimitry Andric } 21630b57cec5SDimitry Andric 21640b57cec5SDimitry Andric // Write the result to the file. 21650b57cec5SDimitry Andric writeResult<ELFT>(); 21660b57cec5SDimitry Andric } 2167