10b57cec5SDimitry Andric //===- Driver.cpp ---------------------------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // The driver drives the entire linking process. It is responsible for 100b57cec5SDimitry Andric // parsing command line options and doing whatever it is instructed to do. 110b57cec5SDimitry Andric // 120b57cec5SDimitry Andric // One notable thing in the LLD's driver when compared to other linkers is 130b57cec5SDimitry Andric // that the LLD's driver is agnostic on the host operating system. 140b57cec5SDimitry Andric // Other linkers usually have implicit default values (such as a dynamic 150b57cec5SDimitry Andric // linker path or library paths) for each host OS. 160b57cec5SDimitry Andric // 170b57cec5SDimitry Andric // I don't think implicit default values are useful because they are 18bdd1243dSDimitry Andric // usually explicitly specified by the compiler ctx.driver. They can even 190b57cec5SDimitry Andric // be harmful when you are doing cross-linking. Therefore, in LLD, we 200b57cec5SDimitry Andric // simply trust the compiler driver to pass all required options and 210b57cec5SDimitry Andric // don't try to make effort on our side. 220b57cec5SDimitry Andric // 230b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 240b57cec5SDimitry Andric 250b57cec5SDimitry Andric #include "Driver.h" 260b57cec5SDimitry Andric #include "Config.h" 270b57cec5SDimitry Andric #include "ICF.h" 280b57cec5SDimitry Andric #include "InputFiles.h" 290b57cec5SDimitry Andric #include "InputSection.h" 30bdd1243dSDimitry Andric #include "LTO.h" 310b57cec5SDimitry Andric #include "LinkerScript.h" 320b57cec5SDimitry Andric #include "MarkLive.h" 330b57cec5SDimitry Andric #include "OutputSections.h" 340b57cec5SDimitry Andric #include "ScriptParser.h" 350b57cec5SDimitry Andric #include "SymbolTable.h" 360b57cec5SDimitry Andric #include "Symbols.h" 370b57cec5SDimitry Andric #include "SyntheticSections.h" 380b57cec5SDimitry Andric #include "Target.h" 390b57cec5SDimitry Andric #include "Writer.h" 400b57cec5SDimitry Andric #include "lld/Common/Args.h" 41bdd1243dSDimitry Andric #include "lld/Common/CommonLinkerContext.h" 420b57cec5SDimitry Andric #include "lld/Common/Driver.h" 430b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h" 440b57cec5SDimitry Andric #include "lld/Common/Filesystem.h" 450b57cec5SDimitry Andric #include "lld/Common/Memory.h" 460b57cec5SDimitry Andric #include "lld/Common/Strings.h" 470b57cec5SDimitry Andric #include "lld/Common/TargetOptionsCommandFlags.h" 480b57cec5SDimitry Andric #include "lld/Common/Version.h" 490b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h" 500b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h" 510b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 52e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h" 5385868e8aSDimitry Andric #include "llvm/LTO/LTO.h" 5481ad6265SDimitry Andric #include "llvm/Object/Archive.h" 55e8d8bef9SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h" 560b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 570b57cec5SDimitry Andric #include "llvm/Support/Compression.h" 5881ad6265SDimitry Andric #include "llvm/Support/FileSystem.h" 590b57cec5SDimitry Andric #include "llvm/Support/GlobPattern.h" 600b57cec5SDimitry Andric #include "llvm/Support/LEB128.h" 615ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h" 620b57cec5SDimitry Andric #include "llvm/Support/Path.h" 630b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h" 640b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h" 655ffd83dbSDimitry Andric #include "llvm/Support/TimeProfiler.h" 660b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 670b57cec5SDimitry Andric #include <cstdlib> 68*06c3fb27SDimitry Andric #include <tuple> 690b57cec5SDimitry Andric #include <utility> 700b57cec5SDimitry Andric 710b57cec5SDimitry Andric using namespace llvm; 720b57cec5SDimitry Andric using namespace llvm::ELF; 730b57cec5SDimitry Andric using namespace llvm::object; 740b57cec5SDimitry Andric using namespace llvm::sys; 750b57cec5SDimitry Andric using namespace llvm::support; 765ffd83dbSDimitry Andric using namespace lld; 775ffd83dbSDimitry Andric using namespace lld::elf; 780b57cec5SDimitry Andric 79bdd1243dSDimitry Andric ConfigWrapper elf::config; 80bdd1243dSDimitry Andric Ctx elf::ctx; 810b57cec5SDimitry Andric 820b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args); 830b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args); 840b57cec5SDimitry Andric 851fd87a68SDimitry Andric void elf::errorOrWarn(const Twine &msg) { 861fd87a68SDimitry Andric if (config->noinhibitExec) 871fd87a68SDimitry Andric warn(msg); 881fd87a68SDimitry Andric else 891fd87a68SDimitry Andric error(msg); 901fd87a68SDimitry Andric } 911fd87a68SDimitry Andric 92bdd1243dSDimitry Andric void Ctx::reset() { 93bdd1243dSDimitry Andric driver = LinkerDriver(); 94bdd1243dSDimitry Andric memoryBuffers.clear(); 95bdd1243dSDimitry Andric objectFiles.clear(); 96bdd1243dSDimitry Andric sharedFiles.clear(); 97bdd1243dSDimitry Andric binaryFiles.clear(); 98bdd1243dSDimitry Andric bitcodeFiles.clear(); 99bdd1243dSDimitry Andric lazyBitcodeFiles.clear(); 100bdd1243dSDimitry Andric inputSections.clear(); 101bdd1243dSDimitry Andric ehInputSections.clear(); 102bdd1243dSDimitry Andric duplicates.clear(); 103bdd1243dSDimitry Andric nonPrevailingSyms.clear(); 104bdd1243dSDimitry Andric whyExtractRecords.clear(); 105bdd1243dSDimitry Andric backwardReferences.clear(); 106bdd1243dSDimitry Andric hasSympart.store(false, std::memory_order_relaxed); 107bdd1243dSDimitry Andric needsTlsLd.store(false, std::memory_order_relaxed); 108bdd1243dSDimitry Andric } 109bdd1243dSDimitry Andric 110*06c3fb27SDimitry Andric llvm::raw_fd_ostream Ctx::openAuxiliaryFile(llvm::StringRef filename, 111*06c3fb27SDimitry Andric std::error_code &ec) { 112*06c3fb27SDimitry Andric using namespace llvm::sys::fs; 113*06c3fb27SDimitry Andric OpenFlags flags = 114*06c3fb27SDimitry Andric auxiliaryFiles.insert(filename).second ? OF_None : OF_Append; 115*06c3fb27SDimitry Andric return {filename, ec, flags}; 116*06c3fb27SDimitry Andric } 117*06c3fb27SDimitry Andric 118*06c3fb27SDimitry Andric namespace lld { 119*06c3fb27SDimitry Andric namespace elf { 120*06c3fb27SDimitry Andric bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS, 121*06c3fb27SDimitry Andric llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) { 122*06c3fb27SDimitry Andric // This driver-specific context will be freed later by unsafeLldMain(). 12304eeddc0SDimitry Andric auto *ctx = new CommonLinkerContext; 124480093f4SDimitry Andric 12504eeddc0SDimitry Andric ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); 12604eeddc0SDimitry Andric ctx->e.cleanupCallback = []() { 127bdd1243dSDimitry Andric elf::ctx.reset(); 128bdd1243dSDimitry Andric symtab = SymbolTable(); 129bdd1243dSDimitry Andric 1300b57cec5SDimitry Andric outputSections.clear(); 13104eeddc0SDimitry Andric symAux.clear(); 1320b57cec5SDimitry Andric 1330b57cec5SDimitry Andric tar = nullptr; 13404eeddc0SDimitry Andric in.reset(); 1350b57cec5SDimitry Andric 13604eeddc0SDimitry Andric partitions.clear(); 13704eeddc0SDimitry Andric partitions.emplace_back(); 1380b57cec5SDimitry Andric 1390b57cec5SDimitry Andric SharedFile::vernauxNum = 0; 140e8d8bef9SDimitry Andric }; 14104eeddc0SDimitry Andric ctx->e.logName = args::getFilenameWithoutExe(args[0]); 14204eeddc0SDimitry Andric ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use " 14381ad6265SDimitry Andric "--error-limit=0 to see all errors)"; 144e8d8bef9SDimitry Andric 145bdd1243dSDimitry Andric config = ConfigWrapper(); 1460eae32dcSDimitry Andric script = std::make_unique<LinkerScript>(); 147bdd1243dSDimitry Andric 148bdd1243dSDimitry Andric symAux.emplace_back(); 149e8d8bef9SDimitry Andric 15004eeddc0SDimitry Andric partitions.clear(); 15104eeddc0SDimitry Andric partitions.emplace_back(); 1520b57cec5SDimitry Andric 1530b57cec5SDimitry Andric config->progName = args[0]; 1540b57cec5SDimitry Andric 155bdd1243dSDimitry Andric elf::ctx.driver.linkerMain(args); 1560b57cec5SDimitry Andric 15704eeddc0SDimitry Andric return errorCount() == 0; 1580b57cec5SDimitry Andric } 159*06c3fb27SDimitry Andric } // namespace elf 160*06c3fb27SDimitry Andric } // namespace lld 1610b57cec5SDimitry Andric 1620b57cec5SDimitry Andric // Parses a linker -m option. 1630b57cec5SDimitry Andric static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) { 1640b57cec5SDimitry Andric uint8_t osabi = 0; 1650b57cec5SDimitry Andric StringRef s = emul; 166*06c3fb27SDimitry Andric if (s.ends_with("_fbsd")) { 1670b57cec5SDimitry Andric s = s.drop_back(5); 1680b57cec5SDimitry Andric osabi = ELFOSABI_FREEBSD; 1690b57cec5SDimitry Andric } 1700b57cec5SDimitry Andric 1710b57cec5SDimitry Andric std::pair<ELFKind, uint16_t> ret = 1720b57cec5SDimitry Andric StringSwitch<std::pair<ELFKind, uint16_t>>(s) 173fe6060f1SDimitry Andric .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64}) 174fe6060f1SDimitry Andric .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64}) 1750b57cec5SDimitry Andric .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 176*06c3fb27SDimitry Andric .Cases("armelfb", "armelfb_linux_eabi", {ELF32BEKind, EM_ARM}) 1770b57cec5SDimitry Andric .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 1780b57cec5SDimitry Andric .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 1790b57cec5SDimitry Andric .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 1800b57cec5SDimitry Andric .Case("elf32lriscv", {ELF32LEKind, EM_RISCV}) 1810b57cec5SDimitry Andric .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC}) 182e8d8bef9SDimitry Andric .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC}) 183*06c3fb27SDimitry Andric .Case("elf32loongarch", {ELF32LEKind, EM_LOONGARCH}) 1840b57cec5SDimitry Andric .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 1850b57cec5SDimitry Andric .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 1860b57cec5SDimitry Andric .Case("elf64lriscv", {ELF64LEKind, EM_RISCV}) 1870b57cec5SDimitry Andric .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 1880b57cec5SDimitry Andric .Case("elf64lppc", {ELF64LEKind, EM_PPC64}) 1890b57cec5SDimitry Andric .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 1900b57cec5SDimitry Andric .Case("elf_i386", {ELF32LEKind, EM_386}) 1910b57cec5SDimitry Andric .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 1925ffd83dbSDimitry Andric .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9}) 193e8d8bef9SDimitry Andric .Case("msp430elf", {ELF32LEKind, EM_MSP430}) 194bdd1243dSDimitry Andric .Case("elf64_amdgpu", {ELF64LEKind, EM_AMDGPU}) 195*06c3fb27SDimitry Andric .Case("elf64loongarch", {ELF64LEKind, EM_LOONGARCH}) 1960b57cec5SDimitry Andric .Default({ELFNoneKind, EM_NONE}); 1970b57cec5SDimitry Andric 1980b57cec5SDimitry Andric if (ret.first == ELFNoneKind) 1990b57cec5SDimitry Andric error("unknown emulation: " + emul); 200e8d8bef9SDimitry Andric if (ret.second == EM_MSP430) 201e8d8bef9SDimitry Andric osabi = ELFOSABI_STANDALONE; 202bdd1243dSDimitry Andric else if (ret.second == EM_AMDGPU) 203bdd1243dSDimitry Andric osabi = ELFOSABI_AMDGPU_HSA; 2040b57cec5SDimitry Andric return std::make_tuple(ret.first, ret.second, osabi); 2050b57cec5SDimitry Andric } 2060b57cec5SDimitry Andric 2070b57cec5SDimitry Andric // Returns slices of MB by parsing MB as an archive file. 2080b57cec5SDimitry Andric // Each slice consists of a member file in the archive. 2090b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 2100b57cec5SDimitry Andric MemoryBufferRef mb) { 2110b57cec5SDimitry Andric std::unique_ptr<Archive> file = 2120b57cec5SDimitry Andric CHECK(Archive::create(mb), 2130b57cec5SDimitry Andric mb.getBufferIdentifier() + ": failed to parse archive"); 2140b57cec5SDimitry Andric 2150b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> v; 2160b57cec5SDimitry Andric Error err = Error::success(); 2170b57cec5SDimitry Andric bool addToTar = file->isThin() && tar; 218480093f4SDimitry Andric for (const Archive::Child &c : file->children(err)) { 2190b57cec5SDimitry Andric MemoryBufferRef mbref = 2200b57cec5SDimitry Andric CHECK(c.getMemoryBufferRef(), 2210b57cec5SDimitry Andric mb.getBufferIdentifier() + 2220b57cec5SDimitry Andric ": could not get the buffer for a child of the archive"); 2230b57cec5SDimitry Andric if (addToTar) 2240b57cec5SDimitry Andric tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer()); 2250b57cec5SDimitry Andric v.push_back(std::make_pair(mbref, c.getChildOffset())); 2260b57cec5SDimitry Andric } 2270b57cec5SDimitry Andric if (err) 2280b57cec5SDimitry Andric fatal(mb.getBufferIdentifier() + ": Archive::children failed: " + 2290b57cec5SDimitry Andric toString(std::move(err))); 2300b57cec5SDimitry Andric 2310b57cec5SDimitry Andric // Take ownership of memory buffers created for members of thin archives. 2321fd87a68SDimitry Andric std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers(); 233bdd1243dSDimitry Andric std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers)); 2340b57cec5SDimitry Andric 2350b57cec5SDimitry Andric return v; 2360b57cec5SDimitry Andric } 2370b57cec5SDimitry Andric 238fcaf7f86SDimitry Andric static bool isBitcode(MemoryBufferRef mb) { 239fcaf7f86SDimitry Andric return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode; 240fcaf7f86SDimitry Andric } 241fcaf7f86SDimitry Andric 2420b57cec5SDimitry Andric // Opens a file and create a file object. Path has to be resolved already. 2430b57cec5SDimitry Andric void LinkerDriver::addFile(StringRef path, bool withLOption) { 2440b57cec5SDimitry Andric using namespace sys::fs; 2450b57cec5SDimitry Andric 246bdd1243dSDimitry Andric std::optional<MemoryBufferRef> buffer = readFile(path); 24781ad6265SDimitry Andric if (!buffer) 2480b57cec5SDimitry Andric return; 2490b57cec5SDimitry Andric MemoryBufferRef mbref = *buffer; 2500b57cec5SDimitry Andric 2510b57cec5SDimitry Andric if (config->formatBinary) { 2520b57cec5SDimitry Andric files.push_back(make<BinaryFile>(mbref)); 2530b57cec5SDimitry Andric return; 2540b57cec5SDimitry Andric } 2550b57cec5SDimitry Andric 2560b57cec5SDimitry Andric switch (identify_magic(mbref.getBuffer())) { 2570b57cec5SDimitry Andric case file_magic::unknown: 2580b57cec5SDimitry Andric readLinkerScript(mbref); 2590b57cec5SDimitry Andric return; 2600b57cec5SDimitry Andric case file_magic::archive: { 261bdd1243dSDimitry Andric auto members = getArchiveMembers(mbref); 2620b57cec5SDimitry Andric if (inWholeArchive) { 263bdd1243dSDimitry Andric for (const std::pair<MemoryBufferRef, uint64_t> &p : members) { 264fcaf7f86SDimitry Andric if (isBitcode(p.first)) 265fcaf7f86SDimitry Andric files.push_back(make<BitcodeFile>(p.first, path, p.second, false)); 266fcaf7f86SDimitry Andric else 267fcaf7f86SDimitry Andric files.push_back(createObjFile(p.first, path)); 268fcaf7f86SDimitry Andric } 2690b57cec5SDimitry Andric return; 2700b57cec5SDimitry Andric } 2710b57cec5SDimitry Andric 27281ad6265SDimitry Andric archiveFiles.emplace_back(path, members.size()); 2730b57cec5SDimitry Andric 27481ad6265SDimitry Andric // Handle archives and --start-lib/--end-lib using the same code path. This 27581ad6265SDimitry Andric // scans all the ELF relocatable object files and bitcode files in the 27681ad6265SDimitry Andric // archive rather than just the index file, with the benefit that the 27781ad6265SDimitry Andric // symbols are only loaded once. For many projects archives see high 27881ad6265SDimitry Andric // utilization rates and it is a net performance win. --start-lib scans 27981ad6265SDimitry Andric // symbols in the same order that llvm-ar adds them to the index, so in the 28081ad6265SDimitry Andric // common case the semantics are identical. If the archive symbol table was 28181ad6265SDimitry Andric // created in a different order, or is incomplete, this strategy has 28281ad6265SDimitry Andric // different semantics. Such output differences are considered user error. 28381ad6265SDimitry Andric // 284d56accc7SDimitry Andric // All files within the archive get the same group ID to allow mutual 285d56accc7SDimitry Andric // references for --warn-backrefs. 286d56accc7SDimitry Andric bool saved = InputFile::isInGroup; 287d56accc7SDimitry Andric InputFile::isInGroup = true; 28881ad6265SDimitry Andric for (const std::pair<MemoryBufferRef, uint64_t> &p : members) { 28904eeddc0SDimitry Andric auto magic = identify_magic(p.first.getBuffer()); 290fcaf7f86SDimitry Andric if (magic == file_magic::elf_relocatable) 291fcaf7f86SDimitry Andric files.push_back(createObjFile(p.first, path, true)); 292fcaf7f86SDimitry Andric else if (magic == file_magic::bitcode) 293fcaf7f86SDimitry Andric files.push_back(make<BitcodeFile>(p.first, path, p.second, true)); 29404eeddc0SDimitry Andric else 29581ad6265SDimitry Andric warn(path + ": archive member '" + p.first.getBufferIdentifier() + 29604eeddc0SDimitry Andric "' is neither ET_REL nor LLVM bitcode"); 29704eeddc0SDimitry Andric } 298d56accc7SDimitry Andric InputFile::isInGroup = saved; 299d56accc7SDimitry Andric if (!saved) 300d56accc7SDimitry Andric ++InputFile::nextGroupId; 3010b57cec5SDimitry Andric return; 3020b57cec5SDimitry Andric } 303bdd1243dSDimitry Andric case file_magic::elf_shared_object: { 3040b57cec5SDimitry Andric if (config->isStatic || config->relocatable) { 3050b57cec5SDimitry Andric error("attempted static link of dynamic object " + path); 3060b57cec5SDimitry Andric return; 3070b57cec5SDimitry Andric } 3080b57cec5SDimitry Andric 309349cc55cSDimitry Andric // Shared objects are identified by soname. soname is (if specified) 310349cc55cSDimitry Andric // DT_SONAME and falls back to filename. If a file was specified by -lfoo, 311349cc55cSDimitry Andric // the directory part is ignored. Note that path may be a temporary and 312349cc55cSDimitry Andric // cannot be stored into SharedFile::soName. 313349cc55cSDimitry Andric path = mbref.getBufferIdentifier(); 314bdd1243dSDimitry Andric auto *f = 315bdd1243dSDimitry Andric make<SharedFile>(mbref, withLOption ? path::filename(path) : path); 316bdd1243dSDimitry Andric f->init(); 317bdd1243dSDimitry Andric files.push_back(f); 3180b57cec5SDimitry Andric return; 319bdd1243dSDimitry Andric } 3200b57cec5SDimitry Andric case file_magic::bitcode: 321fcaf7f86SDimitry Andric files.push_back(make<BitcodeFile>(mbref, "", 0, inLib)); 322fcaf7f86SDimitry Andric break; 3230b57cec5SDimitry Andric case file_magic::elf_relocatable: 324fcaf7f86SDimitry Andric files.push_back(createObjFile(mbref, "", inLib)); 3250b57cec5SDimitry Andric break; 3260b57cec5SDimitry Andric default: 3270b57cec5SDimitry Andric error(path + ": unknown file type"); 3280b57cec5SDimitry Andric } 3290b57cec5SDimitry Andric } 3300b57cec5SDimitry Andric 3310b57cec5SDimitry Andric // Add a given library by searching it from input search paths. 3320b57cec5SDimitry Andric void LinkerDriver::addLibrary(StringRef name) { 333bdd1243dSDimitry Andric if (std::optional<std::string> path = searchLibrary(name)) 334972a253aSDimitry Andric addFile(saver().save(*path), /*withLOption=*/true); 3350b57cec5SDimitry Andric else 336e8d8bef9SDimitry Andric error("unable to find library -l" + name, ErrorTag::LibNotFound, {name}); 3370b57cec5SDimitry Andric } 3380b57cec5SDimitry Andric 3390b57cec5SDimitry Andric // This function is called on startup. We need this for LTO since 3400b57cec5SDimitry Andric // LTO calls LLVM functions to compile bitcode files to native code. 3410b57cec5SDimitry Andric // Technically this can be delayed until we read bitcode files, but 3420b57cec5SDimitry Andric // we don't bother to do lazily because the initialization is fast. 3430b57cec5SDimitry Andric static void initLLVM() { 3440b57cec5SDimitry Andric InitializeAllTargets(); 3450b57cec5SDimitry Andric InitializeAllTargetMCs(); 3460b57cec5SDimitry Andric InitializeAllAsmPrinters(); 3470b57cec5SDimitry Andric InitializeAllAsmParsers(); 3480b57cec5SDimitry Andric } 3490b57cec5SDimitry Andric 3500b57cec5SDimitry Andric // Some command line options or some combinations of them are not allowed. 3510b57cec5SDimitry Andric // This function checks for such errors. 3520b57cec5SDimitry Andric static void checkOptions() { 3530b57cec5SDimitry Andric // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 3540b57cec5SDimitry Andric // table which is a relatively new feature. 3550b57cec5SDimitry Andric if (config->emachine == EM_MIPS && config->gnuHash) 3560b57cec5SDimitry Andric error("the .gnu.hash section is not compatible with the MIPS target"); 3570b57cec5SDimitry Andric 358*06c3fb27SDimitry Andric if (config->emachine == EM_ARM) { 359*06c3fb27SDimitry Andric if (!config->cmseImplib) { 360*06c3fb27SDimitry Andric if (!config->cmseInputLib.empty()) 361*06c3fb27SDimitry Andric error("--in-implib may not be used without --cmse-implib"); 362*06c3fb27SDimitry Andric if (!config->cmseOutputLib.empty()) 363*06c3fb27SDimitry Andric error("--out-implib may not be used without --cmse-implib"); 364*06c3fb27SDimitry Andric } 365*06c3fb27SDimitry Andric } else { 366*06c3fb27SDimitry Andric if (config->cmseImplib) 367*06c3fb27SDimitry Andric error("--cmse-implib is only supported on ARM targets"); 368*06c3fb27SDimitry Andric if (!config->cmseInputLib.empty()) 369*06c3fb27SDimitry Andric error("--in-implib is only supported on ARM targets"); 370*06c3fb27SDimitry Andric if (!config->cmseOutputLib.empty()) 371*06c3fb27SDimitry Andric error("--out-implib is only supported on ARM targets"); 372*06c3fb27SDimitry Andric } 373*06c3fb27SDimitry Andric 3740b57cec5SDimitry Andric if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64) 3750b57cec5SDimitry Andric error("--fix-cortex-a53-843419 is only supported on AArch64 targets"); 3760b57cec5SDimitry Andric 37785868e8aSDimitry Andric if (config->fixCortexA8 && config->emachine != EM_ARM) 37885868e8aSDimitry Andric error("--fix-cortex-a8 is only supported on ARM targets"); 37985868e8aSDimitry Andric 380*06c3fb27SDimitry Andric if (config->armBe8 && config->emachine != EM_ARM) 381*06c3fb27SDimitry Andric error("--be8 is only supported on ARM targets"); 382*06c3fb27SDimitry Andric 383*06c3fb27SDimitry Andric if (config->fixCortexA8 && !config->isLE) 384*06c3fb27SDimitry Andric error("--fix-cortex-a8 is not supported on big endian targets"); 385*06c3fb27SDimitry Andric 3860b57cec5SDimitry Andric if (config->tocOptimize && config->emachine != EM_PPC64) 387e8d8bef9SDimitry Andric error("--toc-optimize is only supported on PowerPC64 targets"); 388e8d8bef9SDimitry Andric 389e8d8bef9SDimitry Andric if (config->pcRelOptimize && config->emachine != EM_PPC64) 390e8d8bef9SDimitry Andric error("--pcrel-optimize is only supported on PowerPC64 targets"); 3910b57cec5SDimitry Andric 392*06c3fb27SDimitry Andric if (config->relaxGP && config->emachine != EM_RISCV) 393*06c3fb27SDimitry Andric error("--relax-gp is only supported on RISC-V targets"); 394*06c3fb27SDimitry Andric 3950b57cec5SDimitry Andric if (config->pie && config->shared) 3960b57cec5SDimitry Andric error("-shared and -pie may not be used together"); 3970b57cec5SDimitry Andric 3980b57cec5SDimitry Andric if (!config->shared && !config->filterList.empty()) 3990b57cec5SDimitry Andric error("-F may not be used without -shared"); 4000b57cec5SDimitry Andric 4010b57cec5SDimitry Andric if (!config->shared && !config->auxiliaryList.empty()) 4020b57cec5SDimitry Andric error("-f may not be used without -shared"); 4030b57cec5SDimitry Andric 40485868e8aSDimitry Andric if (config->strip == StripPolicy::All && config->emitRelocs) 40585868e8aSDimitry Andric error("--strip-all and --emit-relocs may not be used together"); 40685868e8aSDimitry Andric 4070b57cec5SDimitry Andric if (config->zText && config->zIfuncNoplt) 4080b57cec5SDimitry Andric error("-z text and -z ifunc-noplt may not be used together"); 4090b57cec5SDimitry Andric 4100b57cec5SDimitry Andric if (config->relocatable) { 4110b57cec5SDimitry Andric if (config->shared) 4120b57cec5SDimitry Andric error("-r and -shared may not be used together"); 4130b57cec5SDimitry Andric if (config->gdbIndex) 4140b57cec5SDimitry Andric error("-r and --gdb-index may not be used together"); 4150b57cec5SDimitry Andric if (config->icf != ICFLevel::None) 4160b57cec5SDimitry Andric error("-r and --icf may not be used together"); 4170b57cec5SDimitry Andric if (config->pie) 4180b57cec5SDimitry Andric error("-r and -pie may not be used together"); 41985868e8aSDimitry Andric if (config->exportDynamic) 42085868e8aSDimitry Andric error("-r and --export-dynamic may not be used together"); 4210b57cec5SDimitry Andric } 4220b57cec5SDimitry Andric 4230b57cec5SDimitry Andric if (config->executeOnly) { 4240b57cec5SDimitry Andric if (config->emachine != EM_AARCH64) 425349cc55cSDimitry Andric error("--execute-only is only supported on AArch64 targets"); 4260b57cec5SDimitry Andric 4270b57cec5SDimitry Andric if (config->singleRoRx && !script->hasSectionsCommand) 428349cc55cSDimitry Andric error("--execute-only and --no-rosegment cannot be used together"); 4290b57cec5SDimitry Andric } 4300b57cec5SDimitry Andric 431480093f4SDimitry Andric if (config->zRetpolineplt && config->zForceIbt) 432480093f4SDimitry Andric error("-z force-ibt may not be used with -z retpolineplt"); 4330b57cec5SDimitry Andric 4340b57cec5SDimitry Andric if (config->emachine != EM_AARCH64) { 4355ffd83dbSDimitry Andric if (config->zPacPlt) 436480093f4SDimitry Andric error("-z pac-plt only supported on AArch64"); 4375ffd83dbSDimitry Andric if (config->zForceBti) 438480093f4SDimitry Andric error("-z force-bti only supported on AArch64"); 4390eae32dcSDimitry Andric if (config->zBtiReport != "none") 4400eae32dcSDimitry Andric error("-z bti-report only supported on AArch64"); 4410b57cec5SDimitry Andric } 4420eae32dcSDimitry Andric 4430eae32dcSDimitry Andric if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 4440eae32dcSDimitry Andric config->zCetReport != "none") 4450eae32dcSDimitry Andric error("-z cet-report only supported on X86 and X86_64"); 4460b57cec5SDimitry Andric } 4470b57cec5SDimitry Andric 4480b57cec5SDimitry Andric static const char *getReproduceOption(opt::InputArgList &args) { 4490b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 4500b57cec5SDimitry Andric return arg->getValue(); 4510b57cec5SDimitry Andric return getenv("LLD_REPRODUCE"); 4520b57cec5SDimitry Andric } 4530b57cec5SDimitry Andric 4540b57cec5SDimitry Andric static bool hasZOption(opt::InputArgList &args, StringRef key) { 4550b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_z)) 4560b57cec5SDimitry Andric if (key == arg->getValue()) 4570b57cec5SDimitry Andric return true; 4580b57cec5SDimitry Andric return false; 4590b57cec5SDimitry Andric } 4600b57cec5SDimitry Andric 4610b57cec5SDimitry Andric static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2, 4620b57cec5SDimitry Andric bool Default) { 4630b57cec5SDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 4640b57cec5SDimitry Andric if (k1 == arg->getValue()) 4650b57cec5SDimitry Andric return true; 4660b57cec5SDimitry Andric if (k2 == arg->getValue()) 4670b57cec5SDimitry Andric return false; 4680b57cec5SDimitry Andric } 4690b57cec5SDimitry Andric return Default; 4700b57cec5SDimitry Andric } 4710b57cec5SDimitry Andric 47285868e8aSDimitry Andric static SeparateSegmentKind getZSeparate(opt::InputArgList &args) { 47385868e8aSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 47485868e8aSDimitry Andric StringRef v = arg->getValue(); 47585868e8aSDimitry Andric if (v == "noseparate-code") 47685868e8aSDimitry Andric return SeparateSegmentKind::None; 47785868e8aSDimitry Andric if (v == "separate-code") 47885868e8aSDimitry Andric return SeparateSegmentKind::Code; 47985868e8aSDimitry Andric if (v == "separate-loadable-segments") 48085868e8aSDimitry Andric return SeparateSegmentKind::Loadable; 48185868e8aSDimitry Andric } 48285868e8aSDimitry Andric return SeparateSegmentKind::None; 48385868e8aSDimitry Andric } 48485868e8aSDimitry Andric 485480093f4SDimitry Andric static GnuStackKind getZGnuStack(opt::InputArgList &args) { 486480093f4SDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 487480093f4SDimitry Andric if (StringRef("execstack") == arg->getValue()) 488480093f4SDimitry Andric return GnuStackKind::Exec; 489480093f4SDimitry Andric if (StringRef("noexecstack") == arg->getValue()) 490480093f4SDimitry Andric return GnuStackKind::NoExec; 491480093f4SDimitry Andric if (StringRef("nognustack") == arg->getValue()) 492480093f4SDimitry Andric return GnuStackKind::None; 493480093f4SDimitry Andric } 494480093f4SDimitry Andric 495480093f4SDimitry Andric return GnuStackKind::NoExec; 496480093f4SDimitry Andric } 497480093f4SDimitry Andric 4985ffd83dbSDimitry Andric static uint8_t getZStartStopVisibility(opt::InputArgList &args) { 4995ffd83dbSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 5005ffd83dbSDimitry Andric std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 5015ffd83dbSDimitry Andric if (kv.first == "start-stop-visibility") { 5025ffd83dbSDimitry Andric if (kv.second == "default") 5035ffd83dbSDimitry Andric return STV_DEFAULT; 5045ffd83dbSDimitry Andric else if (kv.second == "internal") 5055ffd83dbSDimitry Andric return STV_INTERNAL; 5065ffd83dbSDimitry Andric else if (kv.second == "hidden") 5075ffd83dbSDimitry Andric return STV_HIDDEN; 5085ffd83dbSDimitry Andric else if (kv.second == "protected") 5095ffd83dbSDimitry Andric return STV_PROTECTED; 5105ffd83dbSDimitry Andric error("unknown -z start-stop-visibility= value: " + StringRef(kv.second)); 5115ffd83dbSDimitry Andric } 5125ffd83dbSDimitry Andric } 5135ffd83dbSDimitry Andric return STV_PROTECTED; 5145ffd83dbSDimitry Andric } 5155ffd83dbSDimitry Andric 51681ad6265SDimitry Andric constexpr const char *knownZFlags[] = { 51781ad6265SDimitry Andric "combreloc", 51881ad6265SDimitry Andric "copyreloc", 51981ad6265SDimitry Andric "defs", 52081ad6265SDimitry Andric "execstack", 52181ad6265SDimitry Andric "force-bti", 52281ad6265SDimitry Andric "force-ibt", 52381ad6265SDimitry Andric "global", 52481ad6265SDimitry Andric "hazardplt", 52581ad6265SDimitry Andric "ifunc-noplt", 52681ad6265SDimitry Andric "initfirst", 52781ad6265SDimitry Andric "interpose", 52881ad6265SDimitry Andric "keep-text-section-prefix", 52981ad6265SDimitry Andric "lazy", 53081ad6265SDimitry Andric "muldefs", 53181ad6265SDimitry Andric "nocombreloc", 53281ad6265SDimitry Andric "nocopyreloc", 53381ad6265SDimitry Andric "nodefaultlib", 53481ad6265SDimitry Andric "nodelete", 53581ad6265SDimitry Andric "nodlopen", 53681ad6265SDimitry Andric "noexecstack", 53781ad6265SDimitry Andric "nognustack", 53881ad6265SDimitry Andric "nokeep-text-section-prefix", 53981ad6265SDimitry Andric "nopack-relative-relocs", 54081ad6265SDimitry Andric "norelro", 54181ad6265SDimitry Andric "noseparate-code", 54281ad6265SDimitry Andric "nostart-stop-gc", 54381ad6265SDimitry Andric "notext", 54481ad6265SDimitry Andric "now", 54581ad6265SDimitry Andric "origin", 54681ad6265SDimitry Andric "pac-plt", 54781ad6265SDimitry Andric "pack-relative-relocs", 54881ad6265SDimitry Andric "rel", 54981ad6265SDimitry Andric "rela", 55081ad6265SDimitry Andric "relro", 55181ad6265SDimitry Andric "retpolineplt", 55281ad6265SDimitry Andric "rodynamic", 55381ad6265SDimitry Andric "separate-code", 55481ad6265SDimitry Andric "separate-loadable-segments", 55581ad6265SDimitry Andric "shstk", 55681ad6265SDimitry Andric "start-stop-gc", 55781ad6265SDimitry Andric "text", 55881ad6265SDimitry Andric "undefs", 55981ad6265SDimitry Andric "wxneeded", 56081ad6265SDimitry Andric }; 56181ad6265SDimitry Andric 5620b57cec5SDimitry Andric static bool isKnownZFlag(StringRef s) { 56381ad6265SDimitry Andric return llvm::is_contained(knownZFlags, s) || 564*06c3fb27SDimitry Andric s.starts_with("common-page-size=") || s.starts_with("bti-report=") || 565*06c3fb27SDimitry Andric s.starts_with("cet-report=") || 566*06c3fb27SDimitry Andric s.starts_with("dead-reloc-in-nonalloc=") || 567*06c3fb27SDimitry Andric s.starts_with("max-page-size=") || s.starts_with("stack-size=") || 568*06c3fb27SDimitry Andric s.starts_with("start-stop-visibility="); 5690b57cec5SDimitry Andric } 5700b57cec5SDimitry Andric 5714824e7fdSDimitry Andric // Report a warning for an unknown -z option. 5720b57cec5SDimitry Andric static void checkZOptions(opt::InputArgList &args) { 5730b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_z)) 5740b57cec5SDimitry Andric if (!isKnownZFlag(arg->getValue())) 5754824e7fdSDimitry Andric warn("unknown -z value: " + StringRef(arg->getValue())); 5760b57cec5SDimitry Andric } 5770b57cec5SDimitry Andric 578753f127fSDimitry Andric constexpr const char *saveTempsValues[] = { 579753f127fSDimitry Andric "resolution", "preopt", "promote", "internalize", "import", 580753f127fSDimitry Andric "opt", "precodegen", "prelink", "combinedindex"}; 581753f127fSDimitry Andric 582e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 5830b57cec5SDimitry Andric ELFOptTable parser; 5840b57cec5SDimitry Andric opt::InputArgList args = parser.parse(argsArr.slice(1)); 5850b57cec5SDimitry Andric 58681ad6265SDimitry Andric // Interpret these flags early because error()/warn() depend on them. 5870b57cec5SDimitry Andric errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20); 5884824e7fdSDimitry Andric errorHandler().fatalWarnings = 589bdd1243dSDimitry Andric args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) && 590bdd1243dSDimitry Andric !args.hasArg(OPT_no_warnings); 591bdd1243dSDimitry Andric errorHandler().suppressWarnings = args.hasArg(OPT_no_warnings); 5920b57cec5SDimitry Andric checkZOptions(args); 5930b57cec5SDimitry Andric 5940b57cec5SDimitry Andric // Handle -help 5950b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 5960b57cec5SDimitry Andric printHelp(); 5970b57cec5SDimitry Andric return; 5980b57cec5SDimitry Andric } 5990b57cec5SDimitry Andric 6000b57cec5SDimitry Andric // Handle -v or -version. 6010b57cec5SDimitry Andric // 6020b57cec5SDimitry Andric // A note about "compatible with GNU linkers" message: this is a hack for 603349cc55cSDimitry Andric // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as 604349cc55cSDimitry Andric // a GNU compatible linker. See 605349cc55cSDimitry Andric // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>. 6060b57cec5SDimitry Andric // 6070b57cec5SDimitry Andric // This is somewhat ugly hack, but in reality, we had no choice other 6080b57cec5SDimitry Andric // than doing this. Considering the very long release cycle of Libtool, 6090b57cec5SDimitry Andric // it is not easy to improve it to recognize LLD as a GNU compatible 6100b57cec5SDimitry Andric // linker in a timely manner. Even if we can make it, there are still a 6110b57cec5SDimitry Andric // lot of "configure" scripts out there that are generated by old version 6120b57cec5SDimitry Andric // of Libtool. We cannot convince every software developer to migrate to 6130b57cec5SDimitry Andric // the latest version and re-generate scripts. So we have this hack. 6140b57cec5SDimitry Andric if (args.hasArg(OPT_v) || args.hasArg(OPT_version)) 6150b57cec5SDimitry Andric message(getLLDVersion() + " (compatible with GNU linkers)"); 6160b57cec5SDimitry Andric 6170b57cec5SDimitry Andric if (const char *path = getReproduceOption(args)) { 6180b57cec5SDimitry Andric // Note that --reproduce is a debug option so you can ignore it 6190b57cec5SDimitry Andric // if you are trying to understand the whole picture of the code. 6200b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 6210b57cec5SDimitry Andric TarWriter::create(path, path::stem(path)); 6220b57cec5SDimitry Andric if (errOrWriter) { 6230b57cec5SDimitry Andric tar = std::move(*errOrWriter); 6240b57cec5SDimitry Andric tar->append("response.txt", createResponseFile(args)); 6250b57cec5SDimitry Andric tar->append("version.txt", getLLDVersion() + "\n"); 626e8d8bef9SDimitry Andric StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 627e8d8bef9SDimitry Andric if (!ltoSampleProfile.empty()) 628e8d8bef9SDimitry Andric readFile(ltoSampleProfile); 6290b57cec5SDimitry Andric } else { 6300b57cec5SDimitry Andric error("--reproduce: " + toString(errOrWriter.takeError())); 6310b57cec5SDimitry Andric } 6320b57cec5SDimitry Andric } 6330b57cec5SDimitry Andric 6340b57cec5SDimitry Andric readConfigs(args); 6350b57cec5SDimitry Andric 6360b57cec5SDimitry Andric // The behavior of -v or --version is a bit strange, but this is 6370b57cec5SDimitry Andric // needed for compatibility with GNU linkers. 6380b57cec5SDimitry Andric if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT)) 6390b57cec5SDimitry Andric return; 6400b57cec5SDimitry Andric if (args.hasArg(OPT_version)) 6410b57cec5SDimitry Andric return; 6420b57cec5SDimitry Andric 6435ffd83dbSDimitry Andric // Initialize time trace profiler. 6445ffd83dbSDimitry Andric if (config->timeTraceEnabled) 6455ffd83dbSDimitry Andric timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName); 6465ffd83dbSDimitry Andric 6475ffd83dbSDimitry Andric { 6485ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("ExecuteLinker"); 6495ffd83dbSDimitry Andric 6500b57cec5SDimitry Andric initLLVM(); 6510b57cec5SDimitry Andric createFiles(args); 6520b57cec5SDimitry Andric if (errorCount()) 6530b57cec5SDimitry Andric return; 6540b57cec5SDimitry Andric 6550b57cec5SDimitry Andric inferMachineType(); 6560b57cec5SDimitry Andric setConfigs(args); 6570b57cec5SDimitry Andric checkOptions(); 6580b57cec5SDimitry Andric if (errorCount()) 6590b57cec5SDimitry Andric return; 6600b57cec5SDimitry Andric 6611fd87a68SDimitry Andric link(args); 6620b57cec5SDimitry Andric } 6630b57cec5SDimitry Andric 6645ffd83dbSDimitry Andric if (config->timeTraceEnabled) { 665349cc55cSDimitry Andric checkError(timeTraceProfilerWrite( 66681ad6265SDimitry Andric args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile)); 6675ffd83dbSDimitry Andric timeTraceProfilerCleanup(); 6685ffd83dbSDimitry Andric } 6695ffd83dbSDimitry Andric } 6705ffd83dbSDimitry Andric 6710b57cec5SDimitry Andric static std::string getRpath(opt::InputArgList &args) { 672bdd1243dSDimitry Andric SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath); 6730b57cec5SDimitry Andric return llvm::join(v.begin(), v.end(), ":"); 6740b57cec5SDimitry Andric } 6750b57cec5SDimitry Andric 6760b57cec5SDimitry Andric // Determines what we should do if there are remaining unresolved 6770b57cec5SDimitry Andric // symbols after the name resolution. 678e8d8bef9SDimitry Andric static void setUnresolvedSymbolPolicy(opt::InputArgList &args) { 6790b57cec5SDimitry Andric UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols, 6800b57cec5SDimitry Andric OPT_warn_unresolved_symbols, true) 6810b57cec5SDimitry Andric ? UnresolvedPolicy::ReportError 6820b57cec5SDimitry Andric : UnresolvedPolicy::Warn; 683349cc55cSDimitry Andric // -shared implies --unresolved-symbols=ignore-all because missing 684e8d8bef9SDimitry Andric // symbols are likely to be resolved at runtime. 685e8d8bef9SDimitry Andric bool diagRegular = !config->shared, diagShlib = !config->shared; 6860b57cec5SDimitry Andric 687e8d8bef9SDimitry Andric for (const opt::Arg *arg : args) { 6880b57cec5SDimitry Andric switch (arg->getOption().getID()) { 6890b57cec5SDimitry Andric case OPT_unresolved_symbols: { 6900b57cec5SDimitry Andric StringRef s = arg->getValue(); 691e8d8bef9SDimitry Andric if (s == "ignore-all") { 692e8d8bef9SDimitry Andric diagRegular = false; 693e8d8bef9SDimitry Andric diagShlib = false; 694e8d8bef9SDimitry Andric } else if (s == "ignore-in-object-files") { 695e8d8bef9SDimitry Andric diagRegular = false; 696e8d8bef9SDimitry Andric diagShlib = true; 697e8d8bef9SDimitry Andric } else if (s == "ignore-in-shared-libs") { 698e8d8bef9SDimitry Andric diagRegular = true; 699e8d8bef9SDimitry Andric diagShlib = false; 700e8d8bef9SDimitry Andric } else if (s == "report-all") { 701e8d8bef9SDimitry Andric diagRegular = true; 702e8d8bef9SDimitry Andric diagShlib = true; 703e8d8bef9SDimitry Andric } else { 7040b57cec5SDimitry Andric error("unknown --unresolved-symbols value: " + s); 705e8d8bef9SDimitry Andric } 706e8d8bef9SDimitry Andric break; 7070b57cec5SDimitry Andric } 7080b57cec5SDimitry Andric case OPT_no_undefined: 709e8d8bef9SDimitry Andric diagRegular = true; 710e8d8bef9SDimitry Andric break; 7110b57cec5SDimitry Andric case OPT_z: 7120b57cec5SDimitry Andric if (StringRef(arg->getValue()) == "defs") 713e8d8bef9SDimitry Andric diagRegular = true; 714e8d8bef9SDimitry Andric else if (StringRef(arg->getValue()) == "undefs") 715e8d8bef9SDimitry Andric diagRegular = false; 716e8d8bef9SDimitry Andric break; 717e8d8bef9SDimitry Andric case OPT_allow_shlib_undefined: 718e8d8bef9SDimitry Andric diagShlib = false; 719e8d8bef9SDimitry Andric break; 720e8d8bef9SDimitry Andric case OPT_no_allow_shlib_undefined: 721e8d8bef9SDimitry Andric diagShlib = true; 722e8d8bef9SDimitry Andric break; 7230b57cec5SDimitry Andric } 7240b57cec5SDimitry Andric } 7250b57cec5SDimitry Andric 726e8d8bef9SDimitry Andric config->unresolvedSymbols = 727e8d8bef9SDimitry Andric diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore; 728e8d8bef9SDimitry Andric config->unresolvedSymbolsInShlib = 729e8d8bef9SDimitry Andric diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore; 7300b57cec5SDimitry Andric } 7310b57cec5SDimitry Andric 7320b57cec5SDimitry Andric static Target2Policy getTarget2(opt::InputArgList &args) { 7330b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_target2, "got-rel"); 7340b57cec5SDimitry Andric if (s == "rel") 7350b57cec5SDimitry Andric return Target2Policy::Rel; 7360b57cec5SDimitry Andric if (s == "abs") 7370b57cec5SDimitry Andric return Target2Policy::Abs; 7380b57cec5SDimitry Andric if (s == "got-rel") 7390b57cec5SDimitry Andric return Target2Policy::GotRel; 7400b57cec5SDimitry Andric error("unknown --target2 option: " + s); 7410b57cec5SDimitry Andric return Target2Policy::GotRel; 7420b57cec5SDimitry Andric } 7430b57cec5SDimitry Andric 7440b57cec5SDimitry Andric static bool isOutputFormatBinary(opt::InputArgList &args) { 7450b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_oformat, "elf"); 7460b57cec5SDimitry Andric if (s == "binary") 7470b57cec5SDimitry Andric return true; 748*06c3fb27SDimitry Andric if (!s.starts_with("elf")) 7490b57cec5SDimitry Andric error("unknown --oformat value: " + s); 7500b57cec5SDimitry Andric return false; 7510b57cec5SDimitry Andric } 7520b57cec5SDimitry Andric 7530b57cec5SDimitry Andric static DiscardPolicy getDiscard(opt::InputArgList &args) { 7540b57cec5SDimitry Andric auto *arg = 7550b57cec5SDimitry Andric args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 7560b57cec5SDimitry Andric if (!arg) 7570b57cec5SDimitry Andric return DiscardPolicy::Default; 7580b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_discard_all) 7590b57cec5SDimitry Andric return DiscardPolicy::All; 7600b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_discard_locals) 7610b57cec5SDimitry Andric return DiscardPolicy::Locals; 7620b57cec5SDimitry Andric return DiscardPolicy::None; 7630b57cec5SDimitry Andric } 7640b57cec5SDimitry Andric 7650b57cec5SDimitry Andric static StringRef getDynamicLinker(opt::InputArgList &args) { 7660b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 76755e4f9d5SDimitry Andric if (!arg) 7680b57cec5SDimitry Andric return ""; 76955e4f9d5SDimitry Andric if (arg->getOption().getID() == OPT_no_dynamic_linker) { 77055e4f9d5SDimitry Andric // --no-dynamic-linker suppresses undefined weak symbols in .dynsym 77155e4f9d5SDimitry Andric config->noDynamicLinker = true; 77255e4f9d5SDimitry Andric return ""; 77355e4f9d5SDimitry Andric } 7740b57cec5SDimitry Andric return arg->getValue(); 7750b57cec5SDimitry Andric } 7760b57cec5SDimitry Andric 77781ad6265SDimitry Andric static int getMemtagMode(opt::InputArgList &args) { 77881ad6265SDimitry Andric StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode); 779*06c3fb27SDimitry Andric if (memtagModeArg.empty()) { 780*06c3fb27SDimitry Andric if (config->androidMemtagStack) 781*06c3fb27SDimitry Andric warn("--android-memtag-mode is unspecified, leaving " 782*06c3fb27SDimitry Andric "--android-memtag-stack a no-op"); 783*06c3fb27SDimitry Andric else if (config->androidMemtagHeap) 784*06c3fb27SDimitry Andric warn("--android-memtag-mode is unspecified, leaving " 785*06c3fb27SDimitry Andric "--android-memtag-heap a no-op"); 786*06c3fb27SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 787*06c3fb27SDimitry Andric } 788*06c3fb27SDimitry Andric 78981ad6265SDimitry Andric if (!config->androidMemtagHeap && !config->androidMemtagStack) { 79081ad6265SDimitry Andric error("when using --android-memtag-mode, at least one of " 79181ad6265SDimitry Andric "--android-memtag-heap or " 79281ad6265SDimitry Andric "--android-memtag-stack is required"); 79381ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 79481ad6265SDimitry Andric } 79581ad6265SDimitry Andric 796*06c3fb27SDimitry Andric if (memtagModeArg == "sync") 79781ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_SYNC; 79881ad6265SDimitry Andric if (memtagModeArg == "async") 79981ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_ASYNC; 80081ad6265SDimitry Andric if (memtagModeArg == "none") 80181ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 80281ad6265SDimitry Andric 80381ad6265SDimitry Andric error("unknown --android-memtag-mode value: \"" + memtagModeArg + 80481ad6265SDimitry Andric "\", should be one of {async, sync, none}"); 80581ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 80681ad6265SDimitry Andric } 80781ad6265SDimitry Andric 8080b57cec5SDimitry Andric static ICFLevel getICF(opt::InputArgList &args) { 8090b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all); 8100b57cec5SDimitry Andric if (!arg || arg->getOption().getID() == OPT_icf_none) 8110b57cec5SDimitry Andric return ICFLevel::None; 8120b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_icf_safe) 8130b57cec5SDimitry Andric return ICFLevel::Safe; 8140b57cec5SDimitry Andric return ICFLevel::All; 8150b57cec5SDimitry Andric } 8160b57cec5SDimitry Andric 8170b57cec5SDimitry Andric static StripPolicy getStrip(opt::InputArgList &args) { 8180b57cec5SDimitry Andric if (args.hasArg(OPT_relocatable)) 8190b57cec5SDimitry Andric return StripPolicy::None; 8200b57cec5SDimitry Andric 8210b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug); 8220b57cec5SDimitry Andric if (!arg) 8230b57cec5SDimitry Andric return StripPolicy::None; 8240b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_strip_all) 8250b57cec5SDimitry Andric return StripPolicy::All; 8260b57cec5SDimitry Andric return StripPolicy::Debug; 8270b57cec5SDimitry Andric } 8280b57cec5SDimitry Andric 8290b57cec5SDimitry Andric static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args, 8300b57cec5SDimitry Andric const opt::Arg &arg) { 8310b57cec5SDimitry Andric uint64_t va = 0; 832*06c3fb27SDimitry Andric if (s.starts_with("0x")) 8330b57cec5SDimitry Andric s = s.drop_front(2); 8340b57cec5SDimitry Andric if (!to_integer(s, va, 16)) 8350b57cec5SDimitry Andric error("invalid argument: " + arg.getAsString(args)); 8360b57cec5SDimitry Andric return va; 8370b57cec5SDimitry Andric } 8380b57cec5SDimitry Andric 8390b57cec5SDimitry Andric static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) { 8400b57cec5SDimitry Andric StringMap<uint64_t> ret; 8410b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section_start)) { 8420b57cec5SDimitry Andric StringRef name; 8430b57cec5SDimitry Andric StringRef addr; 8440b57cec5SDimitry Andric std::tie(name, addr) = StringRef(arg->getValue()).split('='); 8450b57cec5SDimitry Andric ret[name] = parseSectionAddress(addr, args, *arg); 8460b57cec5SDimitry Andric } 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Ttext)) 8490b57cec5SDimitry Andric ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg); 8500b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Tdata)) 8510b57cec5SDimitry Andric ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg); 8520b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Tbss)) 8530b57cec5SDimitry Andric ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg); 8540b57cec5SDimitry Andric return ret; 8550b57cec5SDimitry Andric } 8560b57cec5SDimitry Andric 8570b57cec5SDimitry Andric static SortSectionPolicy getSortSection(opt::InputArgList &args) { 8580b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_sort_section); 8590b57cec5SDimitry Andric if (s == "alignment") 8600b57cec5SDimitry Andric return SortSectionPolicy::Alignment; 8610b57cec5SDimitry Andric if (s == "name") 8620b57cec5SDimitry Andric return SortSectionPolicy::Name; 8630b57cec5SDimitry Andric if (!s.empty()) 8640b57cec5SDimitry Andric error("unknown --sort-section rule: " + s); 8650b57cec5SDimitry Andric return SortSectionPolicy::Default; 8660b57cec5SDimitry Andric } 8670b57cec5SDimitry Andric 8680b57cec5SDimitry Andric static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) { 8690b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_orphan_handling, "place"); 8700b57cec5SDimitry Andric if (s == "warn") 8710b57cec5SDimitry Andric return OrphanHandlingPolicy::Warn; 8720b57cec5SDimitry Andric if (s == "error") 8730b57cec5SDimitry Andric return OrphanHandlingPolicy::Error; 8740b57cec5SDimitry Andric if (s != "place") 8750b57cec5SDimitry Andric error("unknown --orphan-handling mode: " + s); 8760b57cec5SDimitry Andric return OrphanHandlingPolicy::Place; 8770b57cec5SDimitry Andric } 8780b57cec5SDimitry Andric 8790b57cec5SDimitry Andric // Parse --build-id or --build-id=<style>. We handle "tree" as a 8800b57cec5SDimitry Andric // synonym for "sha1" because all our hash functions including 881349cc55cSDimitry Andric // --build-id=sha1 are actually tree hashes for performance reasons. 882bdd1243dSDimitry Andric static std::pair<BuildIdKind, SmallVector<uint8_t, 0>> 8830b57cec5SDimitry Andric getBuildId(opt::InputArgList &args) { 884972a253aSDimitry Andric auto *arg = args.getLastArg(OPT_build_id); 8850b57cec5SDimitry Andric if (!arg) 8860b57cec5SDimitry Andric return {BuildIdKind::None, {}}; 8870b57cec5SDimitry Andric 8880b57cec5SDimitry Andric StringRef s = arg->getValue(); 8890b57cec5SDimitry Andric if (s == "fast") 8900b57cec5SDimitry Andric return {BuildIdKind::Fast, {}}; 8910b57cec5SDimitry Andric if (s == "md5") 8920b57cec5SDimitry Andric return {BuildIdKind::Md5, {}}; 8930b57cec5SDimitry Andric if (s == "sha1" || s == "tree") 8940b57cec5SDimitry Andric return {BuildIdKind::Sha1, {}}; 8950b57cec5SDimitry Andric if (s == "uuid") 8960b57cec5SDimitry Andric return {BuildIdKind::Uuid, {}}; 897*06c3fb27SDimitry Andric if (s.starts_with("0x")) 8980b57cec5SDimitry Andric return {BuildIdKind::Hexstring, parseHex(s.substr(2))}; 8990b57cec5SDimitry Andric 9000b57cec5SDimitry Andric if (s != "none") 9010b57cec5SDimitry Andric error("unknown --build-id style: " + s); 9020b57cec5SDimitry Andric return {BuildIdKind::None, {}}; 9030b57cec5SDimitry Andric } 9040b57cec5SDimitry Andric 9050b57cec5SDimitry Andric static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) { 9060b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none"); 9070b57cec5SDimitry Andric if (s == "android") 9080b57cec5SDimitry Andric return {true, false}; 9090b57cec5SDimitry Andric if (s == "relr") 9100b57cec5SDimitry Andric return {false, true}; 9110b57cec5SDimitry Andric if (s == "android+relr") 9120b57cec5SDimitry Andric return {true, true}; 9130b57cec5SDimitry Andric 9140b57cec5SDimitry Andric if (s != "none") 915349cc55cSDimitry Andric error("unknown --pack-dyn-relocs format: " + s); 9160b57cec5SDimitry Andric return {false, false}; 9170b57cec5SDimitry Andric } 9180b57cec5SDimitry Andric 9190b57cec5SDimitry Andric static void readCallGraph(MemoryBufferRef mb) { 9200b57cec5SDimitry Andric // Build a map from symbol name to section 9210b57cec5SDimitry Andric DenseMap<StringRef, Symbol *> map; 922bdd1243dSDimitry Andric for (ELFFileBase *file : ctx.objectFiles) 9230b57cec5SDimitry Andric for (Symbol *sym : file->getSymbols()) 9240b57cec5SDimitry Andric map[sym->getName()] = sym; 9250b57cec5SDimitry Andric 9260b57cec5SDimitry Andric auto findSection = [&](StringRef name) -> InputSectionBase * { 9270b57cec5SDimitry Andric Symbol *sym = map.lookup(name); 9280b57cec5SDimitry Andric if (!sym) { 9290b57cec5SDimitry Andric if (config->warnSymbolOrdering) 9300b57cec5SDimitry Andric warn(mb.getBufferIdentifier() + ": no such symbol: " + name); 9310b57cec5SDimitry Andric return nullptr; 9320b57cec5SDimitry Andric } 9330b57cec5SDimitry Andric maybeWarnUnorderableSymbol(sym); 9340b57cec5SDimitry Andric 9350b57cec5SDimitry Andric if (Defined *dr = dyn_cast_or_null<Defined>(sym)) 9360b57cec5SDimitry Andric return dyn_cast_or_null<InputSectionBase>(dr->section); 9370b57cec5SDimitry Andric return nullptr; 9380b57cec5SDimitry Andric }; 9390b57cec5SDimitry Andric 9400b57cec5SDimitry Andric for (StringRef line : args::getLines(mb)) { 9410b57cec5SDimitry Andric SmallVector<StringRef, 3> fields; 9420b57cec5SDimitry Andric line.split(fields, ' '); 9430b57cec5SDimitry Andric uint64_t count; 9440b57cec5SDimitry Andric 9450b57cec5SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 9460b57cec5SDimitry Andric error(mb.getBufferIdentifier() + ": parse error"); 9470b57cec5SDimitry Andric return; 9480b57cec5SDimitry Andric } 9490b57cec5SDimitry Andric 9500b57cec5SDimitry Andric if (InputSectionBase *from = findSection(fields[0])) 9510b57cec5SDimitry Andric if (InputSectionBase *to = findSection(fields[1])) 9520b57cec5SDimitry Andric config->callGraphProfile[std::make_pair(from, to)] += count; 9530b57cec5SDimitry Andric } 9540b57cec5SDimitry Andric } 9550b57cec5SDimitry Andric 956fe6060f1SDimitry Andric // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns 957fe6060f1SDimitry Andric // true and populates cgProfile and symbolIndices. 958fe6060f1SDimitry Andric template <class ELFT> 959fe6060f1SDimitry Andric static bool 960fe6060f1SDimitry Andric processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices, 961fe6060f1SDimitry Andric ArrayRef<typename ELFT::CGProfile> &cgProfile, 962fe6060f1SDimitry Andric ObjFile<ELFT> *inputObj) { 963fe6060f1SDimitry Andric if (inputObj->cgProfileSectionIndex == SHN_UNDEF) 964fe6060f1SDimitry Andric return false; 965fe6060f1SDimitry Andric 9660eae32dcSDimitry Andric ArrayRef<Elf_Shdr_Impl<ELFT>> objSections = 9670eae32dcSDimitry Andric inputObj->template getELFShdrs<ELFT>(); 9680eae32dcSDimitry Andric symbolIndices.clear(); 9690eae32dcSDimitry Andric const ELFFile<ELFT> &obj = inputObj->getObj(); 970fe6060f1SDimitry Andric cgProfile = 971fe6060f1SDimitry Andric check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>( 972fe6060f1SDimitry Andric objSections[inputObj->cgProfileSectionIndex])); 973fe6060f1SDimitry Andric 974fe6060f1SDimitry Andric for (size_t i = 0, e = objSections.size(); i < e; ++i) { 975fe6060f1SDimitry Andric const Elf_Shdr_Impl<ELFT> &sec = objSections[i]; 976fe6060f1SDimitry Andric if (sec.sh_info == inputObj->cgProfileSectionIndex) { 977fe6060f1SDimitry Andric if (sec.sh_type == SHT_RELA) { 978fe6060f1SDimitry Andric ArrayRef<typename ELFT::Rela> relas = 979fe6060f1SDimitry Andric CHECK(obj.relas(sec), "could not retrieve cg profile rela section"); 980fe6060f1SDimitry Andric for (const typename ELFT::Rela &rel : relas) 981fe6060f1SDimitry Andric symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 982fe6060f1SDimitry Andric break; 983fe6060f1SDimitry Andric } 984fe6060f1SDimitry Andric if (sec.sh_type == SHT_REL) { 985fe6060f1SDimitry Andric ArrayRef<typename ELFT::Rel> rels = 986fe6060f1SDimitry Andric CHECK(obj.rels(sec), "could not retrieve cg profile rel section"); 987fe6060f1SDimitry Andric for (const typename ELFT::Rel &rel : rels) 988fe6060f1SDimitry Andric symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 989fe6060f1SDimitry Andric break; 990fe6060f1SDimitry Andric } 991fe6060f1SDimitry Andric } 992fe6060f1SDimitry Andric } 993fe6060f1SDimitry Andric if (symbolIndices.empty()) 994fe6060f1SDimitry Andric warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't"); 995fe6060f1SDimitry Andric return !symbolIndices.empty(); 996fe6060f1SDimitry Andric } 997fe6060f1SDimitry Andric 9980b57cec5SDimitry Andric template <class ELFT> static void readCallGraphsFromObjectFiles() { 999fe6060f1SDimitry Andric SmallVector<uint32_t, 32> symbolIndices; 1000fe6060f1SDimitry Andric ArrayRef<typename ELFT::CGProfile> cgProfile; 1001bdd1243dSDimitry Andric for (auto file : ctx.objectFiles) { 10020b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(file); 1003fe6060f1SDimitry Andric if (!processCallGraphRelocations(symbolIndices, cgProfile, obj)) 1004fe6060f1SDimitry Andric continue; 10050b57cec5SDimitry Andric 1006fe6060f1SDimitry Andric if (symbolIndices.size() != cgProfile.size() * 2) 1007fe6060f1SDimitry Andric fatal("number of relocations doesn't match Weights"); 1008fe6060f1SDimitry Andric 1009fe6060f1SDimitry Andric for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) { 1010fe6060f1SDimitry Andric const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i]; 1011fe6060f1SDimitry Andric uint32_t fromIndex = symbolIndices[i * 2]; 1012fe6060f1SDimitry Andric uint32_t toIndex = symbolIndices[i * 2 + 1]; 1013fe6060f1SDimitry Andric auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex)); 1014fe6060f1SDimitry Andric auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex)); 10150b57cec5SDimitry Andric if (!fromSym || !toSym) 10160b57cec5SDimitry Andric continue; 10170b57cec5SDimitry Andric 10180b57cec5SDimitry Andric auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section); 10190b57cec5SDimitry Andric auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section); 10200b57cec5SDimitry Andric if (from && to) 10210b57cec5SDimitry Andric config->callGraphProfile[{from, to}] += cgpe.cgp_weight; 10220b57cec5SDimitry Andric } 10230b57cec5SDimitry Andric } 10240b57cec5SDimitry Andric } 10250b57cec5SDimitry Andric 1026*06c3fb27SDimitry Andric static DebugCompressionType getCompressionType(StringRef s, StringRef option) { 1027*06c3fb27SDimitry Andric DebugCompressionType type = StringSwitch<DebugCompressionType>(s) 1028*06c3fb27SDimitry Andric .Case("zlib", DebugCompressionType::Zlib) 1029*06c3fb27SDimitry Andric .Case("zstd", DebugCompressionType::Zstd) 1030*06c3fb27SDimitry Andric .Default(DebugCompressionType::None); 1031*06c3fb27SDimitry Andric if (type == DebugCompressionType::None) { 1032bdd1243dSDimitry Andric if (s != "none") 1033*06c3fb27SDimitry Andric error("unknown " + option + " value: " + s); 1034*06c3fb27SDimitry Andric } else if (const char *reason = compression::getReasonIfUnsupported( 1035*06c3fb27SDimitry Andric compression::formatFor(type))) { 1036*06c3fb27SDimitry Andric error(option + ": " + reason); 1037*06c3fb27SDimitry Andric } 1038*06c3fb27SDimitry Andric return type; 10390b57cec5SDimitry Andric } 10400b57cec5SDimitry Andric 104185868e8aSDimitry Andric static StringRef getAliasSpelling(opt::Arg *arg) { 104285868e8aSDimitry Andric if (const opt::Arg *alias = arg->getAlias()) 104385868e8aSDimitry Andric return alias->getSpelling(); 104485868e8aSDimitry Andric return arg->getSpelling(); 104585868e8aSDimitry Andric } 104685868e8aSDimitry Andric 10470b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 10480b57cec5SDimitry Andric unsigned id) { 10490b57cec5SDimitry Andric auto *arg = args.getLastArg(id); 10500b57cec5SDimitry Andric if (!arg) 10510b57cec5SDimitry Andric return {"", ""}; 10520b57cec5SDimitry Andric 10530b57cec5SDimitry Andric StringRef s = arg->getValue(); 10540b57cec5SDimitry Andric std::pair<StringRef, StringRef> ret = s.split(';'); 10550b57cec5SDimitry Andric if (ret.second.empty()) 105685868e8aSDimitry Andric error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s); 10570b57cec5SDimitry Andric return ret; 10580b57cec5SDimitry Andric } 10590b57cec5SDimitry Andric 1060*06c3fb27SDimitry Andric // Parse options of the form "old;new[;extra]". 1061*06c3fb27SDimitry Andric static std::tuple<StringRef, StringRef, StringRef> 1062*06c3fb27SDimitry Andric getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) { 1063*06c3fb27SDimitry Andric auto [oldDir, second] = getOldNewOptions(args, id); 1064*06c3fb27SDimitry Andric auto [newDir, extraDir] = second.split(';'); 1065*06c3fb27SDimitry Andric return {oldDir, newDir, extraDir}; 1066*06c3fb27SDimitry Andric } 1067*06c3fb27SDimitry Andric 10680b57cec5SDimitry Andric // Parse the symbol ordering file and warn for any duplicate entries. 1069bdd1243dSDimitry Andric static SmallVector<StringRef, 0> getSymbolOrderingFile(MemoryBufferRef mb) { 1070bdd1243dSDimitry Andric SetVector<StringRef, SmallVector<StringRef, 0>> names; 10710b57cec5SDimitry Andric for (StringRef s : args::getLines(mb)) 10720b57cec5SDimitry Andric if (!names.insert(s) && config->warnSymbolOrdering) 10730b57cec5SDimitry Andric warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s); 10740b57cec5SDimitry Andric 10750b57cec5SDimitry Andric return names.takeVector(); 10760b57cec5SDimitry Andric } 10770b57cec5SDimitry Andric 10785ffd83dbSDimitry Andric static bool getIsRela(opt::InputArgList &args) { 10795ffd83dbSDimitry Andric // If -z rel or -z rela is specified, use the last option. 10805ffd83dbSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 10815ffd83dbSDimitry Andric StringRef s(arg->getValue()); 10825ffd83dbSDimitry Andric if (s == "rel") 10835ffd83dbSDimitry Andric return false; 10845ffd83dbSDimitry Andric if (s == "rela") 10855ffd83dbSDimitry Andric return true; 10865ffd83dbSDimitry Andric } 10875ffd83dbSDimitry Andric 10885ffd83dbSDimitry Andric // Otherwise use the psABI defined relocation entry format. 10895ffd83dbSDimitry Andric uint16_t m = config->emachine; 1090*06c3fb27SDimitry Andric return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || 1091*06c3fb27SDimitry Andric m == EM_LOONGARCH || m == EM_PPC || m == EM_PPC64 || m == EM_RISCV || 1092*06c3fb27SDimitry Andric m == EM_X86_64; 10935ffd83dbSDimitry Andric } 10945ffd83dbSDimitry Andric 10950b57cec5SDimitry Andric static void parseClangOption(StringRef opt, const Twine &msg) { 10960b57cec5SDimitry Andric std::string err; 10970b57cec5SDimitry Andric raw_string_ostream os(err); 10980b57cec5SDimitry Andric 10990b57cec5SDimitry Andric const char *argv[] = {config->progName.data(), opt.data()}; 11000b57cec5SDimitry Andric if (cl::ParseCommandLineOptions(2, argv, "", &os)) 11010b57cec5SDimitry Andric return; 11020b57cec5SDimitry Andric os.flush(); 11030b57cec5SDimitry Andric error(msg + ": " + StringRef(err).trim()); 11040b57cec5SDimitry Andric } 11050b57cec5SDimitry Andric 11060eae32dcSDimitry Andric // Checks the parameter of the bti-report and cet-report options. 11070eae32dcSDimitry Andric static bool isValidReportString(StringRef arg) { 11080eae32dcSDimitry Andric return arg == "none" || arg == "warning" || arg == "error"; 11090eae32dcSDimitry Andric } 11100eae32dcSDimitry Andric 1111*06c3fb27SDimitry Andric // Process a remap pattern 'from-glob=to-file'. 1112*06c3fb27SDimitry Andric static bool remapInputs(StringRef line, const Twine &location) { 1113*06c3fb27SDimitry Andric SmallVector<StringRef, 0> fields; 1114*06c3fb27SDimitry Andric line.split(fields, '='); 1115*06c3fb27SDimitry Andric if (fields.size() != 2 || fields[1].empty()) { 1116*06c3fb27SDimitry Andric error(location + ": parse error, not 'from-glob=to-file'"); 1117*06c3fb27SDimitry Andric return true; 1118*06c3fb27SDimitry Andric } 1119*06c3fb27SDimitry Andric if (!hasWildcard(fields[0])) 1120*06c3fb27SDimitry Andric config->remapInputs[fields[0]] = fields[1]; 1121*06c3fb27SDimitry Andric else if (Expected<GlobPattern> pat = GlobPattern::create(fields[0])) 1122*06c3fb27SDimitry Andric config->remapInputsWildcards.emplace_back(std::move(*pat), fields[1]); 1123*06c3fb27SDimitry Andric else { 1124*06c3fb27SDimitry Andric error(location + ": " + toString(pat.takeError())); 1125*06c3fb27SDimitry Andric return true; 1126*06c3fb27SDimitry Andric } 1127*06c3fb27SDimitry Andric return false; 1128*06c3fb27SDimitry Andric } 1129*06c3fb27SDimitry Andric 11300b57cec5SDimitry Andric // Initializes Config members by the command line options. 11310b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args) { 11320b57cec5SDimitry Andric errorHandler().verbose = args.hasArg(OPT_verbose); 11330b57cec5SDimitry Andric errorHandler().vsDiagnostics = 11340b57cec5SDimitry Andric args.hasArg(OPT_visual_studio_diagnostics_format, false); 11350b57cec5SDimitry Andric 11360b57cec5SDimitry Andric config->allowMultipleDefinition = 11370b57cec5SDimitry Andric args.hasFlag(OPT_allow_multiple_definition, 11380b57cec5SDimitry Andric OPT_no_allow_multiple_definition, false) || 11390b57cec5SDimitry Andric hasZOption(args, "muldefs"); 114081ad6265SDimitry Andric config->androidMemtagHeap = 114181ad6265SDimitry Andric args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false); 114281ad6265SDimitry Andric config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack, 114381ad6265SDimitry Andric OPT_no_android_memtag_stack, false); 114481ad6265SDimitry Andric config->androidMemtagMode = getMemtagMode(args); 11450b57cec5SDimitry Andric config->auxiliaryList = args::getStrings(args, OPT_auxiliary); 1146*06c3fb27SDimitry Andric config->armBe8 = args.hasArg(OPT_be8); 11476e75b2fbSDimitry Andric if (opt::Arg *arg = 11486e75b2fbSDimitry Andric args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions, 11496e75b2fbSDimitry Andric OPT_Bsymbolic_functions, OPT_Bsymbolic)) { 11506e75b2fbSDimitry Andric if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions)) 11516e75b2fbSDimitry Andric config->bsymbolic = BsymbolicKind::NonWeakFunctions; 11526e75b2fbSDimitry Andric else if (arg->getOption().matches(OPT_Bsymbolic_functions)) 11536e75b2fbSDimitry Andric config->bsymbolic = BsymbolicKind::Functions; 1154fe6060f1SDimitry Andric else if (arg->getOption().matches(OPT_Bsymbolic)) 11556e75b2fbSDimitry Andric config->bsymbolic = BsymbolicKind::All; 1156fe6060f1SDimitry Andric } 11570b57cec5SDimitry Andric config->checkSections = 11580b57cec5SDimitry Andric args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 11590b57cec5SDimitry Andric config->chroot = args.getLastArgValue(OPT_chroot); 1160*06c3fb27SDimitry Andric config->compressDebugSections = getCompressionType( 1161*06c3fb27SDimitry Andric args.getLastArgValue(OPT_compress_debug_sections, "none"), 1162*06c3fb27SDimitry Andric "--compress-debug-sections"); 1163fe6060f1SDimitry Andric config->cref = args.hasArg(OPT_cref); 11645ffd83dbSDimitry Andric config->optimizeBBJumps = 11655ffd83dbSDimitry Andric args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false); 11660b57cec5SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true); 1167e8d8bef9SDimitry Andric config->dependencyFile = args.getLastArgValue(OPT_dependency_file); 11680b57cec5SDimitry Andric config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true); 11690b57cec5SDimitry Andric config->disableVerify = args.hasArg(OPT_disable_verify); 11700b57cec5SDimitry Andric config->discard = getDiscard(args); 11710b57cec5SDimitry Andric config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq); 11720b57cec5SDimitry Andric config->dynamicLinker = getDynamicLinker(args); 11730b57cec5SDimitry Andric config->ehFrameHdr = 11740b57cec5SDimitry Andric args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 11750b57cec5SDimitry Andric config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false); 11760b57cec5SDimitry Andric config->emitRelocs = args.hasArg(OPT_emit_relocs); 11770b57cec5SDimitry Andric config->callGraphProfileSort = args.hasFlag( 11780b57cec5SDimitry Andric OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true); 11790b57cec5SDimitry Andric config->enableNewDtags = 11800b57cec5SDimitry Andric args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 11810b57cec5SDimitry Andric config->entry = args.getLastArgValue(OPT_entry); 1182e8d8bef9SDimitry Andric 1183e8d8bef9SDimitry Andric errorHandler().errorHandlingScript = 1184e8d8bef9SDimitry Andric args.getLastArgValue(OPT_error_handling_script); 1185e8d8bef9SDimitry Andric 11860b57cec5SDimitry Andric config->executeOnly = 11870b57cec5SDimitry Andric args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 11880b57cec5SDimitry Andric config->exportDynamic = 118981ad6265SDimitry Andric args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) || 119081ad6265SDimitry Andric args.hasArg(OPT_shared); 11910b57cec5SDimitry Andric config->filterList = args::getStrings(args, OPT_filter); 11920b57cec5SDimitry Andric config->fini = args.getLastArgValue(OPT_fini, "_fini"); 11935ffd83dbSDimitry Andric config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) && 11945ffd83dbSDimitry Andric !args.hasArg(OPT_relocatable); 1195*06c3fb27SDimitry Andric config->cmseImplib = args.hasArg(OPT_cmse_implib); 1196*06c3fb27SDimitry Andric config->cmseInputLib = args.getLastArgValue(OPT_in_implib); 1197*06c3fb27SDimitry Andric config->cmseOutputLib = args.getLastArgValue(OPT_out_implib); 11985ffd83dbSDimitry Andric config->fixCortexA8 = 11995ffd83dbSDimitry Andric args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable); 1200e8d8bef9SDimitry Andric config->fortranCommon = 120181ad6265SDimitry Andric args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false); 12020b57cec5SDimitry Andric config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 12030b57cec5SDimitry Andric config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 12040b57cec5SDimitry Andric config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 12050b57cec5SDimitry Andric config->icf = getICF(args); 12060b57cec5SDimitry Andric config->ignoreDataAddressEquality = 12070b57cec5SDimitry Andric args.hasArg(OPT_ignore_data_address_equality); 12080b57cec5SDimitry Andric config->ignoreFunctionAddressEquality = 12090b57cec5SDimitry Andric args.hasArg(OPT_ignore_function_address_equality); 12100b57cec5SDimitry Andric config->init = args.getLastArgValue(OPT_init, "_init"); 12110b57cec5SDimitry Andric config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline); 12120b57cec5SDimitry Andric config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 12130b57cec5SDimitry Andric config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 1214349cc55cSDimitry Andric config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1215349cc55cSDimitry Andric OPT_no_lto_pgo_warn_mismatch, true); 12160b57cec5SDimitry Andric config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager); 12175ffd83dbSDimitry Andric config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm); 12180b57cec5SDimitry Andric config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes); 12195ffd83dbSDimitry Andric config->ltoWholeProgramVisibility = 1220e8d8bef9SDimitry Andric args.hasFlag(OPT_lto_whole_program_visibility, 1221e8d8bef9SDimitry Andric OPT_no_lto_whole_program_visibility, false); 12220b57cec5SDimitry Andric config->ltoo = args::getInteger(args, OPT_lto_O, 2); 1223*06c3fb27SDimitry Andric if (config->ltoo > 3) 1224*06c3fb27SDimitry Andric error("invalid optimization level for LTO: " + Twine(config->ltoo)); 1225*06c3fb27SDimitry Andric unsigned ltoCgo = 1226*06c3fb27SDimitry Andric args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo)); 1227*06c3fb27SDimitry Andric if (auto level = CodeGenOpt::getLevel(ltoCgo)) 1228*06c3fb27SDimitry Andric config->ltoCgo = *level; 1229*06c3fb27SDimitry Andric else 1230*06c3fb27SDimitry Andric error("invalid codegen optimization level for LTO: " + Twine(ltoCgo)); 123185868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq); 12320b57cec5SDimitry Andric config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1); 12330b57cec5SDimitry Andric config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 12345ffd83dbSDimitry Andric config->ltoBasicBlockSections = 1235e8d8bef9SDimitry Andric args.getLastArgValue(OPT_lto_basic_block_sections); 12365ffd83dbSDimitry Andric config->ltoUniqueBasicBlockSectionNames = 1237e8d8bef9SDimitry Andric args.hasFlag(OPT_lto_unique_basic_block_section_names, 1238e8d8bef9SDimitry Andric OPT_no_lto_unique_basic_block_section_names, false); 12390b57cec5SDimitry Andric config->mapFile = args.getLastArgValue(OPT_Map); 12400b57cec5SDimitry Andric config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0); 12410b57cec5SDimitry Andric config->mergeArmExidx = 12420b57cec5SDimitry Andric args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 1243480093f4SDimitry Andric config->mmapOutputFile = 1244480093f4SDimitry Andric args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true); 12450b57cec5SDimitry Andric config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 12460b57cec5SDimitry Andric config->noinhibitExec = args.hasArg(OPT_noinhibit_exec); 12470b57cec5SDimitry Andric config->nostdlib = args.hasArg(OPT_nostdlib); 12480b57cec5SDimitry Andric config->oFormatBinary = isOutputFormatBinary(args); 12490b57cec5SDimitry Andric config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false); 12500b57cec5SDimitry Andric config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename); 125181ad6265SDimitry Andric config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file); 1252e8d8bef9SDimitry Andric 1253e8d8bef9SDimitry Andric // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 1254e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) { 1255e8d8bef9SDimitry Andric auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue()); 1256e8d8bef9SDimitry Andric if (!resultOrErr) 1257e8d8bef9SDimitry Andric error(arg->getSpelling() + ": invalid argument '" + arg->getValue() + 1258e8d8bef9SDimitry Andric "', only integer or 'auto' is supported"); 1259e8d8bef9SDimitry Andric else 1260e8d8bef9SDimitry Andric config->optRemarksHotnessThreshold = *resultOrErr; 1261e8d8bef9SDimitry Andric } 1262e8d8bef9SDimitry Andric 12630b57cec5SDimitry Andric config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes); 12640b57cec5SDimitry Andric config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness); 12650b57cec5SDimitry Andric config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format); 12660b57cec5SDimitry Andric config->optimize = args::getInteger(args, OPT_O, 1); 12670b57cec5SDimitry Andric config->orphanHandling = getOrphanHandling(args); 12680b57cec5SDimitry Andric config->outputFile = args.getLastArgValue(OPT_o); 126961cfbce3SDimitry Andric config->packageMetadata = args.getLastArgValue(OPT_package_metadata); 12700b57cec5SDimitry Andric config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false); 12710b57cec5SDimitry Andric config->printIcfSections = 12720b57cec5SDimitry Andric args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 12730b57cec5SDimitry Andric config->printGcSections = 12740b57cec5SDimitry Andric args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 1275*06c3fb27SDimitry Andric config->printMemoryUsage = args.hasArg(OPT_print_memory_usage); 12765ffd83dbSDimitry Andric config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats); 12770b57cec5SDimitry Andric config->printSymbolOrder = 12780b57cec5SDimitry Andric args.getLastArgValue(OPT_print_symbol_order); 1279349cc55cSDimitry Andric config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true); 1280*06c3fb27SDimitry Andric config->relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false); 12810b57cec5SDimitry Andric config->rpath = getRpath(args); 12820b57cec5SDimitry Andric config->relocatable = args.hasArg(OPT_relocatable); 1283753f127fSDimitry Andric 1284753f127fSDimitry Andric if (args.hasArg(OPT_save_temps)) { 1285753f127fSDimitry Andric // --save-temps implies saving all temps. 1286753f127fSDimitry Andric for (const char *s : saveTempsValues) 1287753f127fSDimitry Andric config->saveTempsArgs.insert(s); 1288753f127fSDimitry Andric } else { 1289753f127fSDimitry Andric for (auto *arg : args.filtered(OPT_save_temps_eq)) { 1290753f127fSDimitry Andric StringRef s = arg->getValue(); 1291753f127fSDimitry Andric if (llvm::is_contained(saveTempsValues, s)) 1292753f127fSDimitry Andric config->saveTempsArgs.insert(s); 1293753f127fSDimitry Andric else 1294753f127fSDimitry Andric error("unknown --save-temps value: " + s); 1295753f127fSDimitry Andric } 1296753f127fSDimitry Andric } 1297753f127fSDimitry Andric 12980b57cec5SDimitry Andric config->searchPaths = args::getStrings(args, OPT_library_path); 12990b57cec5SDimitry Andric config->sectionStartMap = getSectionStartMap(args); 13000b57cec5SDimitry Andric config->shared = args.hasArg(OPT_shared); 13015ffd83dbSDimitry Andric config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true); 13020b57cec5SDimitry Andric config->soName = args.getLastArgValue(OPT_soname); 13030b57cec5SDimitry Andric config->sortSection = getSortSection(args); 13040b57cec5SDimitry Andric config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384); 13050b57cec5SDimitry Andric config->strip = getStrip(args); 13060b57cec5SDimitry Andric config->sysroot = args.getLastArgValue(OPT_sysroot); 13070b57cec5SDimitry Andric config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 13080b57cec5SDimitry Andric config->target2 = getTarget2(args); 13090b57cec5SDimitry Andric config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir); 13100b57cec5SDimitry Andric config->thinLTOCachePolicy = CHECK( 13110b57cec5SDimitry Andric parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)), 13120b57cec5SDimitry Andric "--thinlto-cache-policy: invalid cache policy"); 131385868e8aSDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 131481ad6265SDimitry Andric config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) || 131581ad6265SDimitry Andric args.hasArg(OPT_thinlto_index_only) || 131681ad6265SDimitry Andric args.hasArg(OPT_thinlto_index_only_eq); 131785868e8aSDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 131885868e8aSDimitry Andric args.hasArg(OPT_thinlto_index_only_eq); 131985868e8aSDimitry Andric config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq); 13200b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 132185868e8aSDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq); 1322*06c3fb27SDimitry Andric std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew, 1323*06c3fb27SDimitry Andric config->thinLTOPrefixReplaceNativeObject) = 1324*06c3fb27SDimitry Andric getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace_eq); 132581ad6265SDimitry Andric if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) { 132681ad6265SDimitry Andric if (args.hasArg(OPT_thinlto_object_suffix_replace_eq)) 132781ad6265SDimitry Andric error("--thinlto-object-suffix-replace is not supported with " 132881ad6265SDimitry Andric "--thinlto-emit-index-files"); 132981ad6265SDimitry Andric else if (args.hasArg(OPT_thinlto_prefix_replace_eq)) 133081ad6265SDimitry Andric error("--thinlto-prefix-replace is not supported with " 133181ad6265SDimitry Andric "--thinlto-emit-index-files"); 133281ad6265SDimitry Andric } 1333*06c3fb27SDimitry Andric if (!config->thinLTOPrefixReplaceNativeObject.empty() && 1334*06c3fb27SDimitry Andric config->thinLTOIndexOnlyArg.empty()) { 1335*06c3fb27SDimitry Andric error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with " 1336*06c3fb27SDimitry Andric "--thinlto-index-only="); 1337*06c3fb27SDimitry Andric } 13385ffd83dbSDimitry Andric config->thinLTOModulesToCompile = 13395ffd83dbSDimitry Andric args::getStrings(args, OPT_thinlto_single_module_eq); 134081ad6265SDimitry Andric config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq); 13415ffd83dbSDimitry Andric config->timeTraceGranularity = 13425ffd83dbSDimitry Andric args::getInteger(args, OPT_time_trace_granularity, 500); 13430b57cec5SDimitry Andric config->trace = args.hasArg(OPT_trace); 13440b57cec5SDimitry Andric config->undefined = args::getStrings(args, OPT_undefined); 13450b57cec5SDimitry Andric config->undefinedVersion = 1346bdd1243dSDimitry Andric args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false); 13475ffd83dbSDimitry Andric config->unique = args.hasArg(OPT_unique); 13480b57cec5SDimitry Andric config->useAndroidRelrTags = args.hasFlag( 13490b57cec5SDimitry Andric OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 13500b57cec5SDimitry Andric config->warnBackrefs = 13510b57cec5SDimitry Andric args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 13520b57cec5SDimitry Andric config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 13530b57cec5SDimitry Andric config->warnSymbolOrdering = 13540b57cec5SDimitry Andric args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 1355349cc55cSDimitry Andric config->whyExtract = args.getLastArgValue(OPT_why_extract); 13560b57cec5SDimitry Andric config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true); 13570b57cec5SDimitry Andric config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true); 13585ffd83dbSDimitry Andric config->zForceBti = hasZOption(args, "force-bti"); 1359480093f4SDimitry Andric config->zForceIbt = hasZOption(args, "force-ibt"); 13600b57cec5SDimitry Andric config->zGlobal = hasZOption(args, "global"); 1361480093f4SDimitry Andric config->zGnustack = getZGnuStack(args); 13620b57cec5SDimitry Andric config->zHazardplt = hasZOption(args, "hazardplt"); 13630b57cec5SDimitry Andric config->zIfuncNoplt = hasZOption(args, "ifunc-noplt"); 13640b57cec5SDimitry Andric config->zInitfirst = hasZOption(args, "initfirst"); 13650b57cec5SDimitry Andric config->zInterpose = hasZOption(args, "interpose"); 13660b57cec5SDimitry Andric config->zKeepTextSectionPrefix = getZFlag( 13670b57cec5SDimitry Andric args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 13680b57cec5SDimitry Andric config->zNodefaultlib = hasZOption(args, "nodefaultlib"); 13690b57cec5SDimitry Andric config->zNodelete = hasZOption(args, "nodelete"); 13700b57cec5SDimitry Andric config->zNodlopen = hasZOption(args, "nodlopen"); 13710b57cec5SDimitry Andric config->zNow = getZFlag(args, "now", "lazy", false); 13720b57cec5SDimitry Andric config->zOrigin = hasZOption(args, "origin"); 13735ffd83dbSDimitry Andric config->zPacPlt = hasZOption(args, "pac-plt"); 13740b57cec5SDimitry Andric config->zRelro = getZFlag(args, "relro", "norelro", true); 13750b57cec5SDimitry Andric config->zRetpolineplt = hasZOption(args, "retpolineplt"); 13760b57cec5SDimitry Andric config->zRodynamic = hasZOption(args, "rodynamic"); 137785868e8aSDimitry Andric config->zSeparate = getZSeparate(args); 1378480093f4SDimitry Andric config->zShstk = hasZOption(args, "shstk"); 13790b57cec5SDimitry Andric config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0); 1380fe6060f1SDimitry Andric config->zStartStopGC = 1381fe6060f1SDimitry Andric getZFlag(args, "start-stop-gc", "nostart-stop-gc", true); 13825ffd83dbSDimitry Andric config->zStartStopVisibility = getZStartStopVisibility(args); 13830b57cec5SDimitry Andric config->zText = getZFlag(args, "text", "notext", true); 13840b57cec5SDimitry Andric config->zWxneeded = hasZOption(args, "wxneeded"); 1385e8d8bef9SDimitry Andric setUnresolvedSymbolPolicy(args); 13864824e7fdSDimitry Andric config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no"; 1387fe6060f1SDimitry Andric 1388fe6060f1SDimitry Andric if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) { 1389fe6060f1SDimitry Andric if (arg->getOption().matches(OPT_eb)) 1390fe6060f1SDimitry Andric config->optEB = true; 1391fe6060f1SDimitry Andric else 1392fe6060f1SDimitry Andric config->optEL = true; 1393fe6060f1SDimitry Andric } 1394fe6060f1SDimitry Andric 1395*06c3fb27SDimitry Andric for (opt::Arg *arg : args.filtered(OPT_remap_inputs)) { 1396*06c3fb27SDimitry Andric StringRef value(arg->getValue()); 1397*06c3fb27SDimitry Andric remapInputs(value, arg->getSpelling()); 1398*06c3fb27SDimitry Andric } 1399*06c3fb27SDimitry Andric for (opt::Arg *arg : args.filtered(OPT_remap_inputs_file)) { 1400*06c3fb27SDimitry Andric StringRef filename(arg->getValue()); 1401*06c3fb27SDimitry Andric std::optional<MemoryBufferRef> buffer = readFile(filename); 1402*06c3fb27SDimitry Andric if (!buffer) 1403*06c3fb27SDimitry Andric continue; 1404*06c3fb27SDimitry Andric // Parse 'from-glob=to-file' lines, ignoring #-led comments. 1405*06c3fb27SDimitry Andric for (auto [lineno, line] : llvm::enumerate(args::getLines(*buffer))) 1406*06c3fb27SDimitry Andric if (remapInputs(line, filename + ":" + Twine(lineno + 1))) 1407*06c3fb27SDimitry Andric break; 1408*06c3fb27SDimitry Andric } 1409*06c3fb27SDimitry Andric 1410fe6060f1SDimitry Andric for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) { 1411fe6060f1SDimitry Andric constexpr StringRef errPrefix = "--shuffle-sections=: "; 1412fe6060f1SDimitry Andric std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 1413fe6060f1SDimitry Andric if (kv.first.empty() || kv.second.empty()) { 1414fe6060f1SDimitry Andric error(errPrefix + "expected <section_glob>=<seed>, but got '" + 1415fe6060f1SDimitry Andric arg->getValue() + "'"); 1416fe6060f1SDimitry Andric continue; 1417fe6060f1SDimitry Andric } 1418fe6060f1SDimitry Andric // Signed so that <section_glob>=-1 is allowed. 1419fe6060f1SDimitry Andric int64_t v; 1420fe6060f1SDimitry Andric if (!to_integer(kv.second, v)) 1421fe6060f1SDimitry Andric error(errPrefix + "expected an integer, but got '" + kv.second + "'"); 1422fe6060f1SDimitry Andric else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1423fe6060f1SDimitry Andric config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v)); 1424fe6060f1SDimitry Andric else 1425fe6060f1SDimitry Andric error(errPrefix + toString(pat.takeError())); 1426fe6060f1SDimitry Andric } 14270b57cec5SDimitry Andric 14280eae32dcSDimitry Andric auto reports = {std::make_pair("bti-report", &config->zBtiReport), 14290eae32dcSDimitry Andric std::make_pair("cet-report", &config->zCetReport)}; 14300eae32dcSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_z)) { 14310eae32dcSDimitry Andric std::pair<StringRef, StringRef> option = 14320eae32dcSDimitry Andric StringRef(arg->getValue()).split('='); 14330eae32dcSDimitry Andric for (auto reportArg : reports) { 14340eae32dcSDimitry Andric if (option.first != reportArg.first) 14350eae32dcSDimitry Andric continue; 14360eae32dcSDimitry Andric if (!isValidReportString(option.second)) { 14370eae32dcSDimitry Andric error(Twine("-z ") + reportArg.first + "= parameter " + option.second + 14380eae32dcSDimitry Andric " is not recognized"); 14390eae32dcSDimitry Andric continue; 14400eae32dcSDimitry Andric } 14410eae32dcSDimitry Andric *reportArg.second = option.second; 14420eae32dcSDimitry Andric } 14430eae32dcSDimitry Andric } 14440eae32dcSDimitry Andric 14455ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_z)) { 14465ffd83dbSDimitry Andric std::pair<StringRef, StringRef> option = 14475ffd83dbSDimitry Andric StringRef(arg->getValue()).split('='); 14485ffd83dbSDimitry Andric if (option.first != "dead-reloc-in-nonalloc") 14495ffd83dbSDimitry Andric continue; 14505ffd83dbSDimitry Andric constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: "; 14515ffd83dbSDimitry Andric std::pair<StringRef, StringRef> kv = option.second.split('='); 14525ffd83dbSDimitry Andric if (kv.first.empty() || kv.second.empty()) { 14535ffd83dbSDimitry Andric error(errPrefix + "expected <section_glob>=<value>"); 14545ffd83dbSDimitry Andric continue; 14555ffd83dbSDimitry Andric } 14565ffd83dbSDimitry Andric uint64_t v; 14575ffd83dbSDimitry Andric if (!to_integer(kv.second, v)) 14585ffd83dbSDimitry Andric error(errPrefix + "expected a non-negative integer, but got '" + 14595ffd83dbSDimitry Andric kv.second + "'"); 14605ffd83dbSDimitry Andric else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 14615ffd83dbSDimitry Andric config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v); 14625ffd83dbSDimitry Andric else 14635ffd83dbSDimitry Andric error(errPrefix + toString(pat.takeError())); 14645ffd83dbSDimitry Andric } 14655ffd83dbSDimitry Andric 1466e8d8bef9SDimitry Andric cl::ResetAllOptionOccurrences(); 1467e8d8bef9SDimitry Andric 14680b57cec5SDimitry Andric // Parse LTO options. 14690b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq)) 147004eeddc0SDimitry Andric parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())), 14710b57cec5SDimitry Andric arg->getSpelling()); 14720b57cec5SDimitry Andric 14735ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus)) 14745ffd83dbSDimitry Andric parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling()); 14755ffd83dbSDimitry Andric 14765ffd83dbSDimitry Andric // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or 1477f3fd488fSDimitry Andric // relative path. Just ignore. If not ended with "lto-wrapper" (or 1478f3fd488fSDimitry Andric // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an 14795ffd83dbSDimitry Andric // unsupported LLVMgold.so option and error. 1480f3fd488fSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) { 1481f3fd488fSDimitry Andric StringRef v(arg->getValue()); 1482*06c3fb27SDimitry Andric if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe")) 14835ffd83dbSDimitry Andric error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() + 14845ffd83dbSDimitry Andric "'"); 1485f3fd488fSDimitry Andric } 14860b57cec5SDimitry Andric 148781ad6265SDimitry Andric config->passPlugins = args::getStrings(args, OPT_load_pass_plugins); 148881ad6265SDimitry Andric 14890b57cec5SDimitry Andric // Parse -mllvm options. 1490bdd1243dSDimitry Andric for (const auto *arg : args.filtered(OPT_mllvm)) { 14910b57cec5SDimitry Andric parseClangOption(arg->getValue(), arg->getSpelling()); 1492bdd1243dSDimitry Andric config->mllvmOpts.emplace_back(arg->getValue()); 1493bdd1243dSDimitry Andric } 14940b57cec5SDimitry Andric 1495*06c3fb27SDimitry Andric config->ltoKind = LtoKind::Default; 1496*06c3fb27SDimitry Andric if (auto *arg = args.getLastArg(OPT_lto)) { 1497*06c3fb27SDimitry Andric StringRef s = arg->getValue(); 1498*06c3fb27SDimitry Andric if (s == "thin") 1499*06c3fb27SDimitry Andric config->ltoKind = LtoKind::UnifiedThin; 1500*06c3fb27SDimitry Andric else if (s == "full") 1501*06c3fb27SDimitry Andric config->ltoKind = LtoKind::UnifiedRegular; 1502*06c3fb27SDimitry Andric else if (s == "default") 1503*06c3fb27SDimitry Andric config->ltoKind = LtoKind::Default; 1504*06c3fb27SDimitry Andric else 1505*06c3fb27SDimitry Andric error("unknown LTO mode: " + s); 1506*06c3fb27SDimitry Andric } 1507*06c3fb27SDimitry Andric 15085ffd83dbSDimitry Andric // --threads= takes a positive integer and provides the default value for 1509*06c3fb27SDimitry Andric // --thinlto-jobs=. If unspecified, cap the number of threads since 1510*06c3fb27SDimitry Andric // overhead outweighs optimization for used parallel algorithms for the 1511*06c3fb27SDimitry Andric // non-LTO parts. 15125ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 15135ffd83dbSDimitry Andric StringRef v(arg->getValue()); 15145ffd83dbSDimitry Andric unsigned threads = 0; 15155ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 15165ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 15175ffd83dbSDimitry Andric arg->getValue() + "'"); 15185ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 15195ffd83dbSDimitry Andric config->thinLTOJobs = v; 1520*06c3fb27SDimitry Andric } else if (parallel::strategy.compute_thread_count() > 16) { 1521*06c3fb27SDimitry Andric log("set maximum concurrency to 16, specify --threads= to change"); 1522*06c3fb27SDimitry Andric parallel::strategy = hardware_concurrency(16); 15235ffd83dbSDimitry Andric } 1524bdd1243dSDimitry Andric if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq)) 15255ffd83dbSDimitry Andric config->thinLTOJobs = arg->getValue(); 1526bdd1243dSDimitry Andric config->threadCount = parallel::strategy.compute_thread_count(); 15275ffd83dbSDimitry Andric 15280b57cec5SDimitry Andric if (config->ltoPartitions == 0) 15290b57cec5SDimitry Andric error("--lto-partitions: number of threads must be > 0"); 15305ffd83dbSDimitry Andric if (!get_threadpool_strategy(config->thinLTOJobs)) 15315ffd83dbSDimitry Andric error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 15320b57cec5SDimitry Andric 15330b57cec5SDimitry Andric if (config->splitStackAdjustSize < 0) 15340b57cec5SDimitry Andric error("--split-stack-adjust-size: size must be >= 0"); 15350b57cec5SDimitry Andric 1536480093f4SDimitry Andric // The text segment is traditionally the first segment, whose address equals 1537480093f4SDimitry Andric // the base address. However, lld places the R PT_LOAD first. -Ttext-segment 1538480093f4SDimitry Andric // is an old-fashioned option that does not play well with lld's layout. 1539480093f4SDimitry Andric // Suggest --image-base as a likely alternative. 1540480093f4SDimitry Andric if (args.hasArg(OPT_Ttext_segment)) 1541480093f4SDimitry Andric error("-Ttext-segment is not supported. Use --image-base if you " 1542480093f4SDimitry Andric "intend to set the base address"); 1543480093f4SDimitry Andric 15440b57cec5SDimitry Andric // Parse ELF{32,64}{LE,BE} and CPU type. 15450b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_m)) { 15460b57cec5SDimitry Andric StringRef s = arg->getValue(); 15470b57cec5SDimitry Andric std::tie(config->ekind, config->emachine, config->osabi) = 15480b57cec5SDimitry Andric parseEmulation(s); 15490b57cec5SDimitry Andric config->mipsN32Abi = 1550*06c3fb27SDimitry Andric (s.starts_with("elf32btsmipn32") || s.starts_with("elf32ltsmipn32")); 15510b57cec5SDimitry Andric config->emulation = s; 15520b57cec5SDimitry Andric } 15530b57cec5SDimitry Andric 1554349cc55cSDimitry Andric // Parse --hash-style={sysv,gnu,both}. 15550b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_hash_style)) { 15560b57cec5SDimitry Andric StringRef s = arg->getValue(); 15570b57cec5SDimitry Andric if (s == "sysv") 15580b57cec5SDimitry Andric config->sysvHash = true; 15590b57cec5SDimitry Andric else if (s == "gnu") 15600b57cec5SDimitry Andric config->gnuHash = true; 15610b57cec5SDimitry Andric else if (s == "both") 15620b57cec5SDimitry Andric config->sysvHash = config->gnuHash = true; 15630b57cec5SDimitry Andric else 1564349cc55cSDimitry Andric error("unknown --hash-style: " + s); 15650b57cec5SDimitry Andric } 15660b57cec5SDimitry Andric 15670b57cec5SDimitry Andric if (args.hasArg(OPT_print_map)) 15680b57cec5SDimitry Andric config->mapFile = "-"; 15690b57cec5SDimitry Andric 15700b57cec5SDimitry Andric // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 15710b57cec5SDimitry Andric // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 15720b57cec5SDimitry Andric // it. 15730b57cec5SDimitry Andric if (config->nmagic || config->omagic) 15740b57cec5SDimitry Andric config->zRelro = false; 15750b57cec5SDimitry Andric 15760b57cec5SDimitry Andric std::tie(config->buildId, config->buildIdVector) = getBuildId(args); 15770b57cec5SDimitry Andric 157881ad6265SDimitry Andric if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) { 157981ad6265SDimitry Andric config->relrGlibc = true; 158081ad6265SDimitry Andric config->relrPackDynRelocs = true; 158181ad6265SDimitry Andric } else { 15820b57cec5SDimitry Andric std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) = 15830b57cec5SDimitry Andric getPackDynRelocs(args); 158481ad6265SDimitry Andric } 15850b57cec5SDimitry Andric 15860b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){ 15870b57cec5SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 15880b57cec5SDimitry Andric error("--symbol-ordering-file and --call-graph-order-file " 15890b57cec5SDimitry Andric "may not be used together"); 1590bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) { 15910b57cec5SDimitry Andric config->symbolOrderingFile = getSymbolOrderingFile(*buffer); 15920b57cec5SDimitry Andric // Also need to disable CallGraphProfileSort to prevent 15930b57cec5SDimitry Andric // LLD order symbols with CGProfile 15940b57cec5SDimitry Andric config->callGraphProfileSort = false; 15950b57cec5SDimitry Andric } 15960b57cec5SDimitry Andric } 15970b57cec5SDimitry Andric 159885868e8aSDimitry Andric assert(config->versionDefinitions.empty()); 159985868e8aSDimitry Andric config->versionDefinitions.push_back( 16006e75b2fbSDimitry Andric {"local", (uint16_t)VER_NDX_LOCAL, {}, {}}); 16016e75b2fbSDimitry Andric config->versionDefinitions.push_back( 16026e75b2fbSDimitry Andric {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}}); 160385868e8aSDimitry Andric 16040b57cec5SDimitry Andric // If --retain-symbol-file is used, we'll keep only the symbols listed in 16050b57cec5SDimitry Andric // the file and discard all others. 16060b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) { 16076e75b2fbSDimitry Andric config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back( 160885868e8aSDimitry Andric {"*", /*isExternCpp=*/false, /*hasWildcard=*/true}); 1609bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 16100b57cec5SDimitry Andric for (StringRef s : args::getLines(*buffer)) 16116e75b2fbSDimitry Andric config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back( 161285868e8aSDimitry Andric {s, /*isExternCpp=*/false, /*hasWildcard=*/false}); 16130b57cec5SDimitry Andric } 16140b57cec5SDimitry Andric 16155ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) { 16165ffd83dbSDimitry Andric StringRef pattern(arg->getValue()); 16175ffd83dbSDimitry Andric if (Expected<GlobPattern> pat = GlobPattern::create(pattern)) 16185ffd83dbSDimitry Andric config->warnBackrefsExclude.push_back(std::move(*pat)); 16195ffd83dbSDimitry Andric else 16205ffd83dbSDimitry Andric error(arg->getSpelling() + ": " + toString(pat.takeError())); 16215ffd83dbSDimitry Andric } 16225ffd83dbSDimitry Andric 1623349cc55cSDimitry Andric // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols 1624349cc55cSDimitry Andric // which should be exported. For -shared, references to matched non-local 1625349cc55cSDimitry Andric // STV_DEFAULT symbols are not bound to definitions within the shared object, 1626349cc55cSDimitry Andric // even if other options express a symbolic intention: -Bsymbolic, 16275ffd83dbSDimitry Andric // -Bsymbolic-functions (if STT_FUNC), --dynamic-list. 16280b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export_dynamic_symbol)) 16290b57cec5SDimitry Andric config->dynamicList.push_back( 16305ffd83dbSDimitry Andric {arg->getValue(), /*isExternCpp=*/false, 16315ffd83dbSDimitry Andric /*hasWildcard=*/hasWildcard(arg->getValue())}); 16320b57cec5SDimitry Andric 1633349cc55cSDimitry Andric // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol 1634349cc55cSDimitry Andric // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic 1635349cc55cSDimitry Andric // like semantics. 1636349cc55cSDimitry Andric config->symbolic = 1637349cc55cSDimitry Andric config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list); 1638349cc55cSDimitry Andric for (auto *arg : 1639349cc55cSDimitry Andric args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list)) 1640bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1641349cc55cSDimitry Andric readDynamicList(*buffer); 1642349cc55cSDimitry Andric 16430b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_version_script)) 1644bdd1243dSDimitry Andric if (std::optional<std::string> path = searchScript(arg->getValue())) { 1645bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(*path)) 16460b57cec5SDimitry Andric readVersionScript(*buffer); 16470b57cec5SDimitry Andric } else { 16480b57cec5SDimitry Andric error(Twine("cannot find version script ") + arg->getValue()); 16490b57cec5SDimitry Andric } 16500b57cec5SDimitry Andric } 16510b57cec5SDimitry Andric 16520b57cec5SDimitry Andric // Some Config members do not directly correspond to any particular 16530b57cec5SDimitry Andric // command line options, but computed based on other Config values. 16540b57cec5SDimitry Andric // This function initialize such members. See Config.h for the details 16550b57cec5SDimitry Andric // of these values. 16560b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args) { 16570b57cec5SDimitry Andric ELFKind k = config->ekind; 16580b57cec5SDimitry Andric uint16_t m = config->emachine; 16590b57cec5SDimitry Andric 16600b57cec5SDimitry Andric config->copyRelocs = (config->relocatable || config->emitRelocs); 16610b57cec5SDimitry Andric config->is64 = (k == ELF64LEKind || k == ELF64BEKind); 16620b57cec5SDimitry Andric config->isLE = (k == ELF32LEKind || k == ELF64LEKind); 16630b57cec5SDimitry Andric config->endianness = config->isLE ? endianness::little : endianness::big; 16640b57cec5SDimitry Andric config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS); 16650b57cec5SDimitry Andric config->isPic = config->pie || config->shared; 16660b57cec5SDimitry Andric config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic); 16670b57cec5SDimitry Andric config->wordsize = config->is64 ? 8 : 4; 16680b57cec5SDimitry Andric 16690b57cec5SDimitry Andric // ELF defines two different ways to store relocation addends as shown below: 16700b57cec5SDimitry Andric // 16715ffd83dbSDimitry Andric // Rel: Addends are stored to the location where relocations are applied. It 16725ffd83dbSDimitry Andric // cannot pack the full range of addend values for all relocation types, but 16735ffd83dbSDimitry Andric // this only affects relocation types that we don't support emitting as 16745ffd83dbSDimitry Andric // dynamic relocations (see getDynRel). 16750b57cec5SDimitry Andric // Rela: Addends are stored as part of relocation entry. 16760b57cec5SDimitry Andric // 16770b57cec5SDimitry Andric // In other words, Rela makes it easy to read addends at the price of extra 16785ffd83dbSDimitry Andric // 4 or 8 byte for each relocation entry. 16790b57cec5SDimitry Andric // 16805ffd83dbSDimitry Andric // We pick the format for dynamic relocations according to the psABI for each 16815ffd83dbSDimitry Andric // processor, but a contrary choice can be made if the dynamic loader 16825ffd83dbSDimitry Andric // supports. 16835ffd83dbSDimitry Andric config->isRela = getIsRela(args); 16840b57cec5SDimitry Andric 16850b57cec5SDimitry Andric // If the output uses REL relocations we must store the dynamic relocation 16860b57cec5SDimitry Andric // addends to the output sections. We also store addends for RELA relocations 16870b57cec5SDimitry Andric // if --apply-dynamic-relocs is used. 16880b57cec5SDimitry Andric // We default to not writing the addends when using RELA relocations since 16890b57cec5SDimitry Andric // any standard conforming tool can find it in r_addend. 16900b57cec5SDimitry Andric config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs, 16910b57cec5SDimitry Andric OPT_no_apply_dynamic_relocs, false) || 16920b57cec5SDimitry Andric !config->isRela; 1693fe6060f1SDimitry Andric // Validation of dynamic relocation addends is on by default for assertions 1694fe6060f1SDimitry Andric // builds (for supported targets) and disabled otherwise. Ideally we would 1695fe6060f1SDimitry Andric // enable the debug checks for all targets, but currently not all targets 1696fe6060f1SDimitry Andric // have support for reading Elf_Rel addends, so we only enable for a subset. 1697fe6060f1SDimitry Andric #ifndef NDEBUG 1698bdd1243dSDimitry Andric bool checkDynamicRelocsDefault = m == EM_AARCH64 || m == EM_ARM || 1699*06c3fb27SDimitry Andric m == EM_386 || m == EM_LOONGARCH || 1700*06c3fb27SDimitry Andric m == EM_MIPS || m == EM_RISCV || 1701*06c3fb27SDimitry Andric m == EM_X86_64; 1702fe6060f1SDimitry Andric #else 1703fe6060f1SDimitry Andric bool checkDynamicRelocsDefault = false; 1704fe6060f1SDimitry Andric #endif 1705fe6060f1SDimitry Andric config->checkDynamicRelocs = 1706fe6060f1SDimitry Andric args.hasFlag(OPT_check_dynamic_relocations, 1707fe6060f1SDimitry Andric OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault); 17080b57cec5SDimitry Andric config->tocOptimize = 17090b57cec5SDimitry Andric args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64); 1710e8d8bef9SDimitry Andric config->pcRelOptimize = 1711e8d8bef9SDimitry Andric args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64); 17120b57cec5SDimitry Andric } 17130b57cec5SDimitry Andric 17140b57cec5SDimitry Andric static bool isFormatBinary(StringRef s) { 17150b57cec5SDimitry Andric if (s == "binary") 17160b57cec5SDimitry Andric return true; 17170b57cec5SDimitry Andric if (s == "elf" || s == "default") 17180b57cec5SDimitry Andric return false; 1719349cc55cSDimitry Andric error("unknown --format value: " + s + 17200b57cec5SDimitry Andric " (supported formats: elf, default, binary)"); 17210b57cec5SDimitry Andric return false; 17220b57cec5SDimitry Andric } 17230b57cec5SDimitry Andric 17240b57cec5SDimitry Andric void LinkerDriver::createFiles(opt::InputArgList &args) { 1725e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Load input files"); 17260b57cec5SDimitry Andric // For --{push,pop}-state. 17270b57cec5SDimitry Andric std::vector<std::tuple<bool, bool, bool>> stack; 17280b57cec5SDimitry Andric 17290b57cec5SDimitry Andric // Iterate over argv to process input files and positional arguments. 1730e8d8bef9SDimitry Andric InputFile::isInGroup = false; 173181ad6265SDimitry Andric bool hasInput = false; 17320b57cec5SDimitry Andric for (auto *arg : args) { 17330b57cec5SDimitry Andric switch (arg->getOption().getID()) { 17340b57cec5SDimitry Andric case OPT_library: 17350b57cec5SDimitry Andric addLibrary(arg->getValue()); 173681ad6265SDimitry Andric hasInput = true; 17370b57cec5SDimitry Andric break; 17380b57cec5SDimitry Andric case OPT_INPUT: 17390b57cec5SDimitry Andric addFile(arg->getValue(), /*withLOption=*/false); 174081ad6265SDimitry Andric hasInput = true; 17410b57cec5SDimitry Andric break; 17420b57cec5SDimitry Andric case OPT_defsym: { 17430b57cec5SDimitry Andric StringRef from; 17440b57cec5SDimitry Andric StringRef to; 17450b57cec5SDimitry Andric std::tie(from, to) = StringRef(arg->getValue()).split('='); 17460b57cec5SDimitry Andric if (from.empty() || to.empty()) 1747349cc55cSDimitry Andric error("--defsym: syntax error: " + StringRef(arg->getValue())); 17480b57cec5SDimitry Andric else 1749349cc55cSDimitry Andric readDefsym(from, MemoryBufferRef(to, "--defsym")); 17500b57cec5SDimitry Andric break; 17510b57cec5SDimitry Andric } 17520b57cec5SDimitry Andric case OPT_script: 1753bdd1243dSDimitry Andric if (std::optional<std::string> path = searchScript(arg->getValue())) { 1754bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> mb = readFile(*path)) 17550b57cec5SDimitry Andric readLinkerScript(*mb); 17560b57cec5SDimitry Andric break; 17570b57cec5SDimitry Andric } 17580b57cec5SDimitry Andric error(Twine("cannot find linker script ") + arg->getValue()); 17590b57cec5SDimitry Andric break; 17600b57cec5SDimitry Andric case OPT_as_needed: 17610b57cec5SDimitry Andric config->asNeeded = true; 17620b57cec5SDimitry Andric break; 17630b57cec5SDimitry Andric case OPT_format: 17640b57cec5SDimitry Andric config->formatBinary = isFormatBinary(arg->getValue()); 17650b57cec5SDimitry Andric break; 17660b57cec5SDimitry Andric case OPT_no_as_needed: 17670b57cec5SDimitry Andric config->asNeeded = false; 17680b57cec5SDimitry Andric break; 17690b57cec5SDimitry Andric case OPT_Bstatic: 17700b57cec5SDimitry Andric case OPT_omagic: 17710b57cec5SDimitry Andric case OPT_nmagic: 17720b57cec5SDimitry Andric config->isStatic = true; 17730b57cec5SDimitry Andric break; 17740b57cec5SDimitry Andric case OPT_Bdynamic: 17750b57cec5SDimitry Andric config->isStatic = false; 17760b57cec5SDimitry Andric break; 17770b57cec5SDimitry Andric case OPT_whole_archive: 17780b57cec5SDimitry Andric inWholeArchive = true; 17790b57cec5SDimitry Andric break; 17800b57cec5SDimitry Andric case OPT_no_whole_archive: 17810b57cec5SDimitry Andric inWholeArchive = false; 17820b57cec5SDimitry Andric break; 17830b57cec5SDimitry Andric case OPT_just_symbols: 1784bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) { 1785fcaf7f86SDimitry Andric files.push_back(createObjFile(*mb)); 17860b57cec5SDimitry Andric files.back()->justSymbols = true; 17870b57cec5SDimitry Andric } 17880b57cec5SDimitry Andric break; 1789*06c3fb27SDimitry Andric case OPT_in_implib: 1790*06c3fb27SDimitry Andric if (armCmseImpLib) 1791*06c3fb27SDimitry Andric error("multiple CMSE import libraries not supported"); 1792*06c3fb27SDimitry Andric else if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) 1793*06c3fb27SDimitry Andric armCmseImpLib = createObjFile(*mb); 1794*06c3fb27SDimitry Andric break; 17950b57cec5SDimitry Andric case OPT_start_group: 17960b57cec5SDimitry Andric if (InputFile::isInGroup) 17970b57cec5SDimitry Andric error("nested --start-group"); 17980b57cec5SDimitry Andric InputFile::isInGroup = true; 17990b57cec5SDimitry Andric break; 18000b57cec5SDimitry Andric case OPT_end_group: 18010b57cec5SDimitry Andric if (!InputFile::isInGroup) 18020b57cec5SDimitry Andric error("stray --end-group"); 18030b57cec5SDimitry Andric InputFile::isInGroup = false; 18040b57cec5SDimitry Andric ++InputFile::nextGroupId; 18050b57cec5SDimitry Andric break; 18060b57cec5SDimitry Andric case OPT_start_lib: 18070b57cec5SDimitry Andric if (inLib) 18080b57cec5SDimitry Andric error("nested --start-lib"); 18090b57cec5SDimitry Andric if (InputFile::isInGroup) 18100b57cec5SDimitry Andric error("may not nest --start-lib in --start-group"); 18110b57cec5SDimitry Andric inLib = true; 18120b57cec5SDimitry Andric InputFile::isInGroup = true; 18130b57cec5SDimitry Andric break; 18140b57cec5SDimitry Andric case OPT_end_lib: 18150b57cec5SDimitry Andric if (!inLib) 18160b57cec5SDimitry Andric error("stray --end-lib"); 18170b57cec5SDimitry Andric inLib = false; 18180b57cec5SDimitry Andric InputFile::isInGroup = false; 18190b57cec5SDimitry Andric ++InputFile::nextGroupId; 18200b57cec5SDimitry Andric break; 18210b57cec5SDimitry Andric case OPT_push_state: 18220b57cec5SDimitry Andric stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive); 18230b57cec5SDimitry Andric break; 18240b57cec5SDimitry Andric case OPT_pop_state: 18250b57cec5SDimitry Andric if (stack.empty()) { 18260b57cec5SDimitry Andric error("unbalanced --push-state/--pop-state"); 18270b57cec5SDimitry Andric break; 18280b57cec5SDimitry Andric } 18290b57cec5SDimitry Andric std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back(); 18300b57cec5SDimitry Andric stack.pop_back(); 18310b57cec5SDimitry Andric break; 18320b57cec5SDimitry Andric } 18330b57cec5SDimitry Andric } 18340b57cec5SDimitry Andric 183581ad6265SDimitry Andric if (files.empty() && !hasInput && errorCount() == 0) 18360b57cec5SDimitry Andric error("no input files"); 18370b57cec5SDimitry Andric } 18380b57cec5SDimitry Andric 18390b57cec5SDimitry Andric // If -m <machine_type> was not given, infer it from object files. 18400b57cec5SDimitry Andric void LinkerDriver::inferMachineType() { 18410b57cec5SDimitry Andric if (config->ekind != ELFNoneKind) 18420b57cec5SDimitry Andric return; 18430b57cec5SDimitry Andric 18440b57cec5SDimitry Andric for (InputFile *f : files) { 18450b57cec5SDimitry Andric if (f->ekind == ELFNoneKind) 18460b57cec5SDimitry Andric continue; 18470b57cec5SDimitry Andric config->ekind = f->ekind; 18480b57cec5SDimitry Andric config->emachine = f->emachine; 18490b57cec5SDimitry Andric config->osabi = f->osabi; 18500b57cec5SDimitry Andric config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f); 18510b57cec5SDimitry Andric return; 18520b57cec5SDimitry Andric } 18530b57cec5SDimitry Andric error("target emulation unknown: -m or at least one .o file required"); 18540b57cec5SDimitry Andric } 18550b57cec5SDimitry Andric 18560b57cec5SDimitry Andric // Parse -z max-page-size=<value>. The default value is defined by 18570b57cec5SDimitry Andric // each target. 18580b57cec5SDimitry Andric static uint64_t getMaxPageSize(opt::InputArgList &args) { 18590b57cec5SDimitry Andric uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size", 18600b57cec5SDimitry Andric target->defaultMaxPageSize); 1861972a253aSDimitry Andric if (!isPowerOf2_64(val)) { 18620b57cec5SDimitry Andric error("max-page-size: value isn't a power of 2"); 1863972a253aSDimitry Andric return target->defaultMaxPageSize; 1864972a253aSDimitry Andric } 18650b57cec5SDimitry Andric if (config->nmagic || config->omagic) { 18660b57cec5SDimitry Andric if (val != target->defaultMaxPageSize) 18670b57cec5SDimitry Andric warn("-z max-page-size set, but paging disabled by omagic or nmagic"); 18680b57cec5SDimitry Andric return 1; 18690b57cec5SDimitry Andric } 18700b57cec5SDimitry Andric return val; 18710b57cec5SDimitry Andric } 18720b57cec5SDimitry Andric 18730b57cec5SDimitry Andric // Parse -z common-page-size=<value>. The default value is defined by 18740b57cec5SDimitry Andric // each target. 18750b57cec5SDimitry Andric static uint64_t getCommonPageSize(opt::InputArgList &args) { 18760b57cec5SDimitry Andric uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size", 18770b57cec5SDimitry Andric target->defaultCommonPageSize); 1878972a253aSDimitry Andric if (!isPowerOf2_64(val)) { 18790b57cec5SDimitry Andric error("common-page-size: value isn't a power of 2"); 1880972a253aSDimitry Andric return target->defaultCommonPageSize; 1881972a253aSDimitry Andric } 18820b57cec5SDimitry Andric if (config->nmagic || config->omagic) { 18830b57cec5SDimitry Andric if (val != target->defaultCommonPageSize) 18840b57cec5SDimitry Andric warn("-z common-page-size set, but paging disabled by omagic or nmagic"); 18850b57cec5SDimitry Andric return 1; 18860b57cec5SDimitry Andric } 18870b57cec5SDimitry Andric // commonPageSize can't be larger than maxPageSize. 18880b57cec5SDimitry Andric if (val > config->maxPageSize) 18890b57cec5SDimitry Andric val = config->maxPageSize; 18900b57cec5SDimitry Andric return val; 18910b57cec5SDimitry Andric } 18920b57cec5SDimitry Andric 1893349cc55cSDimitry Andric // Parses --image-base option. 1894bdd1243dSDimitry Andric static std::optional<uint64_t> getImageBase(opt::InputArgList &args) { 18950b57cec5SDimitry Andric // Because we are using "Config->maxPageSize" here, this function has to be 18960b57cec5SDimitry Andric // called after the variable is initialized. 18970b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_image_base); 18980b57cec5SDimitry Andric if (!arg) 1899bdd1243dSDimitry Andric return std::nullopt; 19000b57cec5SDimitry Andric 19010b57cec5SDimitry Andric StringRef s = arg->getValue(); 19020b57cec5SDimitry Andric uint64_t v; 19030b57cec5SDimitry Andric if (!to_integer(s, v)) { 1904349cc55cSDimitry Andric error("--image-base: number expected, but got " + s); 19050b57cec5SDimitry Andric return 0; 19060b57cec5SDimitry Andric } 19070b57cec5SDimitry Andric if ((v % config->maxPageSize) != 0) 1908349cc55cSDimitry Andric warn("--image-base: address isn't multiple of page size: " + s); 19090b57cec5SDimitry Andric return v; 19100b57cec5SDimitry Andric } 19110b57cec5SDimitry Andric 19120b57cec5SDimitry Andric // Parses `--exclude-libs=lib,lib,...`. 19130b57cec5SDimitry Andric // The library names may be delimited by commas or colons. 19140b57cec5SDimitry Andric static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) { 19150b57cec5SDimitry Andric DenseSet<StringRef> ret; 19160b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_exclude_libs)) { 19170b57cec5SDimitry Andric StringRef s = arg->getValue(); 19180b57cec5SDimitry Andric for (;;) { 19190b57cec5SDimitry Andric size_t pos = s.find_first_of(",:"); 19200b57cec5SDimitry Andric if (pos == StringRef::npos) 19210b57cec5SDimitry Andric break; 19220b57cec5SDimitry Andric ret.insert(s.substr(0, pos)); 19230b57cec5SDimitry Andric s = s.substr(pos + 1); 19240b57cec5SDimitry Andric } 19250b57cec5SDimitry Andric ret.insert(s); 19260b57cec5SDimitry Andric } 19270b57cec5SDimitry Andric return ret; 19280b57cec5SDimitry Andric } 19290b57cec5SDimitry Andric 1930349cc55cSDimitry Andric // Handles the --exclude-libs option. If a static library file is specified 1931349cc55cSDimitry Andric // by the --exclude-libs option, all public symbols from the archive become 19320b57cec5SDimitry Andric // private unless otherwise specified by version scripts or something. 19330b57cec5SDimitry Andric // A special library name "ALL" means all archive files. 19340b57cec5SDimitry Andric // 19350b57cec5SDimitry Andric // This is not a popular option, but some programs such as bionic libc use it. 19360b57cec5SDimitry Andric static void excludeLibs(opt::InputArgList &args) { 19370b57cec5SDimitry Andric DenseSet<StringRef> libs = getExcludeLibs(args); 19380b57cec5SDimitry Andric bool all = libs.count("ALL"); 19390b57cec5SDimitry Andric 19400b57cec5SDimitry Andric auto visit = [&](InputFile *file) { 194181ad6265SDimitry Andric if (file->archiveName.empty() || 194281ad6265SDimitry Andric !(all || libs.count(path::filename(file->archiveName)))) 194381ad6265SDimitry Andric return; 194481ad6265SDimitry Andric ArrayRef<Symbol *> symbols = file->getSymbols(); 194581ad6265SDimitry Andric if (isa<ELFFileBase>(file)) 194681ad6265SDimitry Andric symbols = cast<ELFFileBase>(file)->getGlobalSymbols(); 194781ad6265SDimitry Andric for (Symbol *sym : symbols) 194881ad6265SDimitry Andric if (!sym->isUndefined() && sym->file == file) 19490b57cec5SDimitry Andric sym->versionId = VER_NDX_LOCAL; 19500b57cec5SDimitry Andric }; 19510b57cec5SDimitry Andric 1952bdd1243dSDimitry Andric for (ELFFileBase *file : ctx.objectFiles) 19530b57cec5SDimitry Andric visit(file); 19540b57cec5SDimitry Andric 1955bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.bitcodeFiles) 19560b57cec5SDimitry Andric visit(file); 19570b57cec5SDimitry Andric } 19580b57cec5SDimitry Andric 19595ffd83dbSDimitry Andric // Force Sym to be entered in the output. 1960349cc55cSDimitry Andric static void handleUndefined(Symbol *sym, const char *option) { 19610b57cec5SDimitry Andric // Since a symbol may not be used inside the program, LTO may 19620b57cec5SDimitry Andric // eliminate it. Mark the symbol as "used" to prevent it. 19630b57cec5SDimitry Andric sym->isUsedInRegularObj = true; 19640b57cec5SDimitry Andric 1965349cc55cSDimitry Andric if (!sym->isLazy()) 1966349cc55cSDimitry Andric return; 19674824e7fdSDimitry Andric sym->extract(); 1968349cc55cSDimitry Andric if (!config->whyExtract.empty()) 1969bdd1243dSDimitry Andric ctx.whyExtractRecords.emplace_back(option, sym->file, *sym); 19700b57cec5SDimitry Andric } 19710b57cec5SDimitry Andric 1972480093f4SDimitry Andric // As an extension to GNU linkers, lld supports a variant of `-u` 19730b57cec5SDimitry Andric // which accepts wildcard patterns. All symbols that match a given 19740b57cec5SDimitry Andric // pattern are handled as if they were given by `-u`. 19750b57cec5SDimitry Andric static void handleUndefinedGlob(StringRef arg) { 19760b57cec5SDimitry Andric Expected<GlobPattern> pat = GlobPattern::create(arg); 19770b57cec5SDimitry Andric if (!pat) { 19780b57cec5SDimitry Andric error("--undefined-glob: " + toString(pat.takeError())); 19790b57cec5SDimitry Andric return; 19800b57cec5SDimitry Andric } 19810b57cec5SDimitry Andric 19824824e7fdSDimitry Andric // Calling sym->extract() in the loop is not safe because it may add new 19834824e7fdSDimitry Andric // symbols to the symbol table, invalidating the current iterator. 19841fd87a68SDimitry Andric SmallVector<Symbol *, 0> syms; 1985bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols()) 198604eeddc0SDimitry Andric if (!sym->isPlaceholder() && pat->match(sym->getName())) 19870b57cec5SDimitry Andric syms.push_back(sym); 19880b57cec5SDimitry Andric 19890b57cec5SDimitry Andric for (Symbol *sym : syms) 1990349cc55cSDimitry Andric handleUndefined(sym, "--undefined-glob"); 19910b57cec5SDimitry Andric } 19920b57cec5SDimitry Andric 19930b57cec5SDimitry Andric static void handleLibcall(StringRef name) { 1994bdd1243dSDimitry Andric Symbol *sym = symtab.find(name); 19950b57cec5SDimitry Andric if (!sym || !sym->isLazy()) 19960b57cec5SDimitry Andric return; 19970b57cec5SDimitry Andric 19980b57cec5SDimitry Andric MemoryBufferRef mb; 199981ad6265SDimitry Andric mb = cast<LazyObject>(sym)->file->mb; 20000b57cec5SDimitry Andric 20010b57cec5SDimitry Andric if (isBitcode(mb)) 20024824e7fdSDimitry Andric sym->extract(); 20030b57cec5SDimitry Andric } 20040b57cec5SDimitry Andric 200581ad6265SDimitry Andric static void writeArchiveStats() { 200681ad6265SDimitry Andric if (config->printArchiveStats.empty()) 200781ad6265SDimitry Andric return; 200881ad6265SDimitry Andric 200981ad6265SDimitry Andric std::error_code ec; 2010*06c3fb27SDimitry Andric raw_fd_ostream os = ctx.openAuxiliaryFile(config->printArchiveStats, ec); 201181ad6265SDimitry Andric if (ec) { 201281ad6265SDimitry Andric error("--print-archive-stats=: cannot open " + config->printArchiveStats + 201381ad6265SDimitry Andric ": " + ec.message()); 201481ad6265SDimitry Andric return; 201581ad6265SDimitry Andric } 201681ad6265SDimitry Andric 201781ad6265SDimitry Andric os << "members\textracted\tarchive\n"; 201881ad6265SDimitry Andric 201981ad6265SDimitry Andric SmallVector<StringRef, 0> archives; 202081ad6265SDimitry Andric DenseMap<CachedHashStringRef, unsigned> all, extracted; 2021bdd1243dSDimitry Andric for (ELFFileBase *file : ctx.objectFiles) 202281ad6265SDimitry Andric if (file->archiveName.size()) 202381ad6265SDimitry Andric ++extracted[CachedHashStringRef(file->archiveName)]; 2024bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.bitcodeFiles) 202581ad6265SDimitry Andric if (file->archiveName.size()) 202681ad6265SDimitry Andric ++extracted[CachedHashStringRef(file->archiveName)]; 2027bdd1243dSDimitry Andric for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) { 202881ad6265SDimitry Andric unsigned &v = extracted[CachedHashString(f.first)]; 202981ad6265SDimitry Andric os << f.second << '\t' << v << '\t' << f.first << '\n'; 203081ad6265SDimitry Andric // If the archive occurs multiple times, other instances have a count of 0. 203181ad6265SDimitry Andric v = 0; 203281ad6265SDimitry Andric } 203381ad6265SDimitry Andric } 203481ad6265SDimitry Andric 203581ad6265SDimitry Andric static void writeWhyExtract() { 203681ad6265SDimitry Andric if (config->whyExtract.empty()) 203781ad6265SDimitry Andric return; 203881ad6265SDimitry Andric 203981ad6265SDimitry Andric std::error_code ec; 2040*06c3fb27SDimitry Andric raw_fd_ostream os = ctx.openAuxiliaryFile(config->whyExtract, ec); 204181ad6265SDimitry Andric if (ec) { 204281ad6265SDimitry Andric error("cannot open --why-extract= file " + config->whyExtract + ": " + 204381ad6265SDimitry Andric ec.message()); 204481ad6265SDimitry Andric return; 204581ad6265SDimitry Andric } 204681ad6265SDimitry Andric 204781ad6265SDimitry Andric os << "reference\textracted\tsymbol\n"; 2048bdd1243dSDimitry Andric for (auto &entry : ctx.whyExtractRecords) { 204981ad6265SDimitry Andric os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t' 205081ad6265SDimitry Andric << toString(std::get<2>(entry)) << '\n'; 205181ad6265SDimitry Andric } 205281ad6265SDimitry Andric } 205381ad6265SDimitry Andric 205481ad6265SDimitry Andric static void reportBackrefs() { 2055bdd1243dSDimitry Andric for (auto &ref : ctx.backwardReferences) { 205681ad6265SDimitry Andric const Symbol &sym = *ref.first; 205781ad6265SDimitry Andric std::string to = toString(ref.second.second); 205881ad6265SDimitry Andric // Some libraries have known problems and can cause noise. Filter them out 205981ad6265SDimitry Andric // with --warn-backrefs-exclude=. The value may look like (for --start-lib) 206081ad6265SDimitry Andric // *.o or (archive member) *.a(*.o). 206181ad6265SDimitry Andric bool exclude = false; 206281ad6265SDimitry Andric for (const llvm::GlobPattern &pat : config->warnBackrefsExclude) 206381ad6265SDimitry Andric if (pat.match(to)) { 206481ad6265SDimitry Andric exclude = true; 206581ad6265SDimitry Andric break; 206681ad6265SDimitry Andric } 206781ad6265SDimitry Andric if (!exclude) 206881ad6265SDimitry Andric warn("backward reference detected: " + sym.getName() + " in " + 206981ad6265SDimitry Andric toString(ref.second.first) + " refers to " + to); 207081ad6265SDimitry Andric } 207181ad6265SDimitry Andric } 207281ad6265SDimitry Andric 2073e8d8bef9SDimitry Andric // Handle --dependency-file=<path>. If that option is given, lld creates a 2074e8d8bef9SDimitry Andric // file at a given path with the following contents: 2075e8d8bef9SDimitry Andric // 2076e8d8bef9SDimitry Andric // <output-file>: <input-file> ... 2077e8d8bef9SDimitry Andric // 2078e8d8bef9SDimitry Andric // <input-file>: 2079e8d8bef9SDimitry Andric // 2080e8d8bef9SDimitry Andric // where <output-file> is a pathname of an output file and <input-file> 2081e8d8bef9SDimitry Andric // ... is a list of pathnames of all input files. `make` command can read a 2082e8d8bef9SDimitry Andric // file in the above format and interpret it as a dependency info. We write 2083e8d8bef9SDimitry Andric // phony targets for every <input-file> to avoid an error when that file is 2084e8d8bef9SDimitry Andric // removed. 2085e8d8bef9SDimitry Andric // 2086e8d8bef9SDimitry Andric // This option is useful if you want to make your final executable to depend 2087e8d8bef9SDimitry Andric // on all input files including system libraries. Here is why. 2088e8d8bef9SDimitry Andric // 2089e8d8bef9SDimitry Andric // When you write a Makefile, you usually write it so that the final 2090e8d8bef9SDimitry Andric // executable depends on all user-generated object files. Normally, you 2091e8d8bef9SDimitry Andric // don't make your executable to depend on system libraries (such as libc) 2092e8d8bef9SDimitry Andric // because you don't know the exact paths of libraries, even though system 2093e8d8bef9SDimitry Andric // libraries that are linked to your executable statically are technically a 2094e8d8bef9SDimitry Andric // part of your program. By using --dependency-file option, you can make 2095e8d8bef9SDimitry Andric // lld to dump dependency info so that you can maintain exact dependencies 2096e8d8bef9SDimitry Andric // easily. 2097e8d8bef9SDimitry Andric static void writeDependencyFile() { 2098e8d8bef9SDimitry Andric std::error_code ec; 2099*06c3fb27SDimitry Andric raw_fd_ostream os = ctx.openAuxiliaryFile(config->dependencyFile, ec); 2100e8d8bef9SDimitry Andric if (ec) { 2101e8d8bef9SDimitry Andric error("cannot open " + config->dependencyFile + ": " + ec.message()); 2102e8d8bef9SDimitry Andric return; 2103e8d8bef9SDimitry Andric } 2104e8d8bef9SDimitry Andric 2105e8d8bef9SDimitry Andric // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja: 2106e8d8bef9SDimitry Andric // * A space is escaped by a backslash which itself must be escaped. 2107e8d8bef9SDimitry Andric // * A hash sign is escaped by a single backslash. 2108e8d8bef9SDimitry Andric // * $ is escapes as $$. 2109e8d8bef9SDimitry Andric auto printFilename = [](raw_fd_ostream &os, StringRef filename) { 2110e8d8bef9SDimitry Andric llvm::SmallString<256> nativePath; 2111e8d8bef9SDimitry Andric llvm::sys::path::native(filename.str(), nativePath); 2112e8d8bef9SDimitry Andric llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true); 2113e8d8bef9SDimitry Andric for (unsigned i = 0, e = nativePath.size(); i != e; ++i) { 2114e8d8bef9SDimitry Andric if (nativePath[i] == '#') { 2115e8d8bef9SDimitry Andric os << '\\'; 2116e8d8bef9SDimitry Andric } else if (nativePath[i] == ' ') { 2117e8d8bef9SDimitry Andric os << '\\'; 2118e8d8bef9SDimitry Andric unsigned j = i; 2119e8d8bef9SDimitry Andric while (j > 0 && nativePath[--j] == '\\') 2120e8d8bef9SDimitry Andric os << '\\'; 2121e8d8bef9SDimitry Andric } else if (nativePath[i] == '$') { 2122e8d8bef9SDimitry Andric os << '$'; 2123e8d8bef9SDimitry Andric } 2124e8d8bef9SDimitry Andric os << nativePath[i]; 2125e8d8bef9SDimitry Andric } 2126e8d8bef9SDimitry Andric }; 2127e8d8bef9SDimitry Andric 2128e8d8bef9SDimitry Andric os << config->outputFile << ":"; 2129e8d8bef9SDimitry Andric for (StringRef path : config->dependencyFiles) { 2130e8d8bef9SDimitry Andric os << " \\\n "; 2131e8d8bef9SDimitry Andric printFilename(os, path); 2132e8d8bef9SDimitry Andric } 2133e8d8bef9SDimitry Andric os << "\n"; 2134e8d8bef9SDimitry Andric 2135e8d8bef9SDimitry Andric for (StringRef path : config->dependencyFiles) { 2136e8d8bef9SDimitry Andric os << "\n"; 2137e8d8bef9SDimitry Andric printFilename(os, path); 2138e8d8bef9SDimitry Andric os << ":\n"; 2139e8d8bef9SDimitry Andric } 2140e8d8bef9SDimitry Andric } 2141e8d8bef9SDimitry Andric 21420b57cec5SDimitry Andric // Replaces common symbols with defined symbols reside in .bss sections. 21430b57cec5SDimitry Andric // This function is called after all symbol names are resolved. As a 21440b57cec5SDimitry Andric // result, the passes after the symbol resolution won't see any 21450b57cec5SDimitry Andric // symbols of type CommonSymbol. 21460b57cec5SDimitry Andric static void replaceCommonSymbols() { 2147e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Replace common symbols"); 2148bdd1243dSDimitry Andric for (ELFFileBase *file : ctx.objectFiles) { 21490eae32dcSDimitry Andric if (!file->hasCommonSyms) 21500eae32dcSDimitry Andric continue; 21510eae32dcSDimitry Andric for (Symbol *sym : file->getGlobalSymbols()) { 21520b57cec5SDimitry Andric auto *s = dyn_cast<CommonSymbol>(sym); 21530b57cec5SDimitry Andric if (!s) 2154480093f4SDimitry Andric continue; 21550b57cec5SDimitry Andric 21560b57cec5SDimitry Andric auto *bss = make<BssSection>("COMMON", s->size, s->alignment); 21570b57cec5SDimitry Andric bss->file = s->file; 2158bdd1243dSDimitry Andric ctx.inputSections.push_back(bss); 2159bdd1243dSDimitry Andric Defined(s->file, StringRef(), s->binding, s->stOther, s->type, 2160bdd1243dSDimitry Andric /*value=*/0, s->size, bss) 2161bdd1243dSDimitry Andric .overwrite(*s); 2162480093f4SDimitry Andric } 21630b57cec5SDimitry Andric } 21640eae32dcSDimitry Andric } 21650b57cec5SDimitry Andric 216681ad6265SDimitry Andric // If all references to a DSO happen to be weak, the DSO is not added to 216781ad6265SDimitry Andric // DT_NEEDED. If that happens, replace ShardSymbol with Undefined to avoid 216881ad6265SDimitry Andric // dangling references to an unneeded DSO. Use a weak binding to avoid 216981ad6265SDimitry Andric // --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols. 217081ad6265SDimitry Andric static void demoteSharedAndLazySymbols() { 217181ad6265SDimitry Andric llvm::TimeTraceScope timeScope("Demote shared and lazy symbols"); 2172bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols()) { 21730b57cec5SDimitry Andric auto *s = dyn_cast<SharedSymbol>(sym); 217481ad6265SDimitry Andric if (!(s && !cast<SharedFile>(s->file)->isNeeded) && !sym->isLazy()) 2175480093f4SDimitry Andric continue; 21760b57cec5SDimitry Andric 217781ad6265SDimitry Andric uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK); 2178bdd1243dSDimitry Andric Undefined(nullptr, sym->getName(), binding, sym->stOther, sym->type) 2179bdd1243dSDimitry Andric .overwrite(*sym); 2180349cc55cSDimitry Andric sym->versionId = VER_NDX_GLOBAL; 2181480093f4SDimitry Andric } 21820b57cec5SDimitry Andric } 21830b57cec5SDimitry Andric 21840b57cec5SDimitry Andric // The section referred to by `s` is considered address-significant. Set the 21850b57cec5SDimitry Andric // keepUnique flag on the section if appropriate. 21860b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 21870b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 21880b57cec5SDimitry Andric if (d->section) 21890b57cec5SDimitry Andric // We don't need to keep text sections unique under --icf=all even if they 21900b57cec5SDimitry Andric // are address-significant. 21910b57cec5SDimitry Andric if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR)) 21920b57cec5SDimitry Andric d->section->keepUnique = true; 21930b57cec5SDimitry Andric } 21940b57cec5SDimitry Andric 21950b57cec5SDimitry Andric // Record sections that define symbols mentioned in --keep-unique <symbol> 21960b57cec5SDimitry Andric // and symbols referred to by address-significance tables. These sections are 21970b57cec5SDimitry Andric // ineligible for ICF. 21980b57cec5SDimitry Andric template <class ELFT> 21990b57cec5SDimitry Andric static void findKeepUniqueSections(opt::InputArgList &args) { 22000b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_keep_unique)) { 22010b57cec5SDimitry Andric StringRef name = arg->getValue(); 2202bdd1243dSDimitry Andric auto *d = dyn_cast_or_null<Defined>(symtab.find(name)); 22030b57cec5SDimitry Andric if (!d || !d->section) { 22040b57cec5SDimitry Andric warn("could not find symbol " + name + " to keep unique"); 22050b57cec5SDimitry Andric continue; 22060b57cec5SDimitry Andric } 22070b57cec5SDimitry Andric d->section->keepUnique = true; 22080b57cec5SDimitry Andric } 22090b57cec5SDimitry Andric 22100b57cec5SDimitry Andric // --icf=all --ignore-data-address-equality means that we can ignore 22110b57cec5SDimitry Andric // the dynsym and address-significance tables entirely. 22120b57cec5SDimitry Andric if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality) 22130b57cec5SDimitry Andric return; 22140b57cec5SDimitry Andric 22150b57cec5SDimitry Andric // Symbols in the dynsym could be address-significant in other executables 22160b57cec5SDimitry Andric // or DSOs, so we conservatively mark them as address-significant. 2217bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols()) 22180b57cec5SDimitry Andric if (sym->includeInDynsym()) 22190b57cec5SDimitry Andric markAddrsig(sym); 22200b57cec5SDimitry Andric 22210b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 22220b57cec5SDimitry Andric // referenced symbol as address-significant. 2223bdd1243dSDimitry Andric for (InputFile *f : ctx.objectFiles) { 22240b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(f); 22250b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 22260b57cec5SDimitry Andric if (obj->addrsigSec) { 22270b57cec5SDimitry Andric ArrayRef<uint8_t> contents = 2228e8d8bef9SDimitry Andric check(obj->getObj().getSectionContents(*obj->addrsigSec)); 22290b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 22300b57cec5SDimitry Andric while (cur != contents.end()) { 22310b57cec5SDimitry Andric unsigned size; 22320b57cec5SDimitry Andric const char *err; 22330b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 22340b57cec5SDimitry Andric if (err) 22350b57cec5SDimitry Andric fatal(toString(f) + ": could not decode addrsig section: " + err); 22360b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 22370b57cec5SDimitry Andric cur += size; 22380b57cec5SDimitry Andric } 22390b57cec5SDimitry Andric } else { 22400b57cec5SDimitry Andric // If an object file does not have an address-significance table, 22410b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 22420b57cec5SDimitry Andric for (Symbol *s : syms) 22430b57cec5SDimitry Andric markAddrsig(s); 22440b57cec5SDimitry Andric } 22450b57cec5SDimitry Andric } 22460b57cec5SDimitry Andric } 22470b57cec5SDimitry Andric 22480b57cec5SDimitry Andric // This function reads a symbol partition specification section. These sections 22490b57cec5SDimitry Andric // are used to control which partition a symbol is allocated to. See 22500b57cec5SDimitry Andric // https://lld.llvm.org/Partitions.html for more details on partitions. 22510b57cec5SDimitry Andric template <typename ELFT> 22520b57cec5SDimitry Andric static void readSymbolPartitionSection(InputSectionBase *s) { 22530b57cec5SDimitry Andric // Read the relocation that refers to the partition's entry point symbol. 22540b57cec5SDimitry Andric Symbol *sym; 2255349cc55cSDimitry Andric const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>(); 2256349cc55cSDimitry Andric if (rels.areRelocsRel()) 2257349cc55cSDimitry Andric sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]); 22580b57cec5SDimitry Andric else 2259349cc55cSDimitry Andric sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]); 22600b57cec5SDimitry Andric if (!isa<Defined>(sym) || !sym->includeInDynsym()) 22610b57cec5SDimitry Andric return; 22620b57cec5SDimitry Andric 2263bdd1243dSDimitry Andric StringRef partName = reinterpret_cast<const char *>(s->content().data()); 22640b57cec5SDimitry Andric for (Partition &part : partitions) { 22650b57cec5SDimitry Andric if (part.name == partName) { 22660b57cec5SDimitry Andric sym->partition = part.getNumber(); 22670b57cec5SDimitry Andric return; 22680b57cec5SDimitry Andric } 22690b57cec5SDimitry Andric } 22700b57cec5SDimitry Andric 22710b57cec5SDimitry Andric // Forbid partitions from being used on incompatible targets, and forbid them 22720b57cec5SDimitry Andric // from being used together with various linker features that assume a single 22730b57cec5SDimitry Andric // set of output sections. 22740b57cec5SDimitry Andric if (script->hasSectionsCommand) 22750b57cec5SDimitry Andric error(toString(s->file) + 22760b57cec5SDimitry Andric ": partitions cannot be used with the SECTIONS command"); 22770b57cec5SDimitry Andric if (script->hasPhdrsCommands()) 22780b57cec5SDimitry Andric error(toString(s->file) + 22790b57cec5SDimitry Andric ": partitions cannot be used with the PHDRS command"); 22800b57cec5SDimitry Andric if (!config->sectionStartMap.empty()) 22810b57cec5SDimitry Andric error(toString(s->file) + ": partitions cannot be used with " 22820b57cec5SDimitry Andric "--section-start, -Ttext, -Tdata or -Tbss"); 22830b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 22840b57cec5SDimitry Andric error(toString(s->file) + ": partitions cannot be used on this target"); 22850b57cec5SDimitry Andric 22860b57cec5SDimitry Andric // Impose a limit of no more than 254 partitions. This limit comes from the 22870b57cec5SDimitry Andric // sizes of the Partition fields in InputSectionBase and Symbol, as well as 22880b57cec5SDimitry Andric // the amount of space devoted to the partition number in RankFlags. 22890b57cec5SDimitry Andric if (partitions.size() == 254) 22900b57cec5SDimitry Andric fatal("may not have more than 254 partitions"); 22910b57cec5SDimitry Andric 22920b57cec5SDimitry Andric partitions.emplace_back(); 22930b57cec5SDimitry Andric Partition &newPart = partitions.back(); 22940b57cec5SDimitry Andric newPart.name = partName; 22950b57cec5SDimitry Andric sym->partition = newPart.getNumber(); 22960b57cec5SDimitry Andric } 22970b57cec5SDimitry Andric 2298fe6060f1SDimitry Andric static Symbol *addUnusedUndefined(StringRef name, 2299fe6060f1SDimitry Andric uint8_t binding = STB_GLOBAL) { 2300bdd1243dSDimitry Andric return symtab.addSymbol(Undefined{nullptr, name, binding, STV_DEFAULT, 0}); 23015ffd83dbSDimitry Andric } 23025ffd83dbSDimitry Andric 230304eeddc0SDimitry Andric static void markBuffersAsDontNeed(bool skipLinkedOutput) { 230404eeddc0SDimitry Andric // With --thinlto-index-only, all buffers are nearly unused from now on 230504eeddc0SDimitry Andric // (except symbol/section names used by infrequent passes). Mark input file 230604eeddc0SDimitry Andric // buffers as MADV_DONTNEED so that these pages can be reused by the expensive 230704eeddc0SDimitry Andric // thin link, saving memory. 230804eeddc0SDimitry Andric if (skipLinkedOutput) { 2309bdd1243dSDimitry Andric for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers)) 231004eeddc0SDimitry Andric mb.dontNeedIfMmap(); 231104eeddc0SDimitry Andric return; 231204eeddc0SDimitry Andric } 231304eeddc0SDimitry Andric 231404eeddc0SDimitry Andric // Otherwise, just mark MemoryBuffers backing BitcodeFiles. 231504eeddc0SDimitry Andric DenseSet<const char *> bufs; 2316bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.bitcodeFiles) 231704eeddc0SDimitry Andric bufs.insert(file->mb.getBufferStart()); 2318bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.lazyBitcodeFiles) 231904eeddc0SDimitry Andric bufs.insert(file->mb.getBufferStart()); 2320bdd1243dSDimitry Andric for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers)) 232104eeddc0SDimitry Andric if (bufs.count(mb.getBufferStart())) 232204eeddc0SDimitry Andric mb.dontNeedIfMmap(); 232304eeddc0SDimitry Andric } 232404eeddc0SDimitry Andric 23250b57cec5SDimitry Andric // This function is where all the optimizations of link-time 23260b57cec5SDimitry Andric // optimization takes place. When LTO is in use, some input files are 23270b57cec5SDimitry Andric // not in native object file format but in the LLVM bitcode format. 23280b57cec5SDimitry Andric // This function compiles bitcode files into a few big native files 23290b57cec5SDimitry Andric // using LLVM functions and replaces bitcode symbols with the results. 23300b57cec5SDimitry Andric // Because all bitcode files that the program consists of are passed to 23310b57cec5SDimitry Andric // the compiler at once, it can do a whole-program optimization. 233204eeddc0SDimitry Andric template <class ELFT> 233304eeddc0SDimitry Andric void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) { 23345ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("LTO"); 23350b57cec5SDimitry Andric // Compile bitcode files and replace bitcode symbols. 23360b57cec5SDimitry Andric lto.reset(new BitcodeCompiler); 2337bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.bitcodeFiles) 23380b57cec5SDimitry Andric lto->add(*file); 23390b57cec5SDimitry Andric 2340bdd1243dSDimitry Andric if (!ctx.bitcodeFiles.empty()) 234104eeddc0SDimitry Andric markBuffersAsDontNeed(skipLinkedOutput); 234204eeddc0SDimitry Andric 23430b57cec5SDimitry Andric for (InputFile *file : lto->compile()) { 23440b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(file); 23450b57cec5SDimitry Andric obj->parse(/*ignoreComdats=*/true); 23465ffd83dbSDimitry Andric 23475ffd83dbSDimitry Andric // Parse '@' in symbol names for non-relocatable output. 23485ffd83dbSDimitry Andric if (!config->relocatable) 23490b57cec5SDimitry Andric for (Symbol *sym : obj->getGlobalSymbols()) 235004eeddc0SDimitry Andric if (sym->hasVersionSuffix) 23510b57cec5SDimitry Andric sym->parseSymbolVersion(); 2352bdd1243dSDimitry Andric ctx.objectFiles.push_back(obj); 23530b57cec5SDimitry Andric } 23540b57cec5SDimitry Andric } 23550b57cec5SDimitry Andric 23560b57cec5SDimitry Andric // The --wrap option is a feature to rename symbols so that you can write 2357349cc55cSDimitry Andric // wrappers for existing functions. If you pass `--wrap=foo`, all 2358e8d8bef9SDimitry Andric // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are 2359e8d8bef9SDimitry Andric // expected to write `__wrap_foo` function as a wrapper). The original 2360e8d8bef9SDimitry Andric // symbol becomes accessible as `__real_foo`, so you can call that from your 23610b57cec5SDimitry Andric // wrapper. 23620b57cec5SDimitry Andric // 2363349cc55cSDimitry Andric // This data structure is instantiated for each --wrap option. 23640b57cec5SDimitry Andric struct WrappedSymbol { 23650b57cec5SDimitry Andric Symbol *sym; 23660b57cec5SDimitry Andric Symbol *real; 23670b57cec5SDimitry Andric Symbol *wrap; 23680b57cec5SDimitry Andric }; 23690b57cec5SDimitry Andric 2370349cc55cSDimitry Andric // Handles --wrap option. 23710b57cec5SDimitry Andric // 23720b57cec5SDimitry Andric // This function instantiates wrapper symbols. At this point, they seem 23730b57cec5SDimitry Andric // like they are not being used at all, so we explicitly set some flags so 23740b57cec5SDimitry Andric // that LTO won't eliminate them. 23750b57cec5SDimitry Andric static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) { 23760b57cec5SDimitry Andric std::vector<WrappedSymbol> v; 23770b57cec5SDimitry Andric DenseSet<StringRef> seen; 23780b57cec5SDimitry Andric 23790b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wrap)) { 23800b57cec5SDimitry Andric StringRef name = arg->getValue(); 23810b57cec5SDimitry Andric if (!seen.insert(name).second) 23820b57cec5SDimitry Andric continue; 23830b57cec5SDimitry Andric 2384bdd1243dSDimitry Andric Symbol *sym = symtab.find(name); 23850b57cec5SDimitry Andric if (!sym) 23860b57cec5SDimitry Andric continue; 23870b57cec5SDimitry Andric 2388fe6060f1SDimitry Andric Symbol *wrap = 238904eeddc0SDimitry Andric addUnusedUndefined(saver().save("__wrap_" + name), sym->binding); 2390bdd1243dSDimitry Andric 2391bdd1243dSDimitry Andric // If __real_ is referenced, pull in the symbol if it is lazy. Do this after 2392bdd1243dSDimitry Andric // processing __wrap_ as that may have referenced __real_. 2393bdd1243dSDimitry Andric StringRef realName = saver().save("__real_" + name); 2394bdd1243dSDimitry Andric if (symtab.find(realName)) 2395bdd1243dSDimitry Andric addUnusedUndefined(name, sym->binding); 2396bdd1243dSDimitry Andric 2397bdd1243dSDimitry Andric Symbol *real = addUnusedUndefined(realName); 23980b57cec5SDimitry Andric v.push_back({sym, real, wrap}); 23990b57cec5SDimitry Andric 24000b57cec5SDimitry Andric // We want to tell LTO not to inline symbols to be overwritten 24010b57cec5SDimitry Andric // because LTO doesn't know the final symbol contents after renaming. 240281ad6265SDimitry Andric real->scriptDefined = true; 240381ad6265SDimitry Andric sym->scriptDefined = true; 24040b57cec5SDimitry Andric 240581ad6265SDimitry Andric // If a symbol is referenced in any object file, bitcode file or shared 240681ad6265SDimitry Andric // object, mark its redirection target (foo for __real_foo and __wrap_foo 240781ad6265SDimitry Andric // for foo) as referenced after redirection, which will be used to tell LTO 240881ad6265SDimitry Andric // to not eliminate the redirection target. If the object file defining the 240981ad6265SDimitry Andric // symbol also references it, we cannot easily distinguish the case from 241081ad6265SDimitry Andric // cases where the symbol is not referenced. Retain the redirection target 241181ad6265SDimitry Andric // in this case because we choose to wrap symbol references regardless of 241281ad6265SDimitry Andric // whether the symbol is defined 2413e8d8bef9SDimitry Andric // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358). 241481ad6265SDimitry Andric if (real->referenced || real->isDefined()) 241581ad6265SDimitry Andric sym->referencedAfterWrap = true; 2416e8d8bef9SDimitry Andric if (sym->referenced || sym->isDefined()) 241781ad6265SDimitry Andric wrap->referencedAfterWrap = true; 24180b57cec5SDimitry Andric } 24190b57cec5SDimitry Andric return v; 24200b57cec5SDimitry Andric } 24210b57cec5SDimitry Andric 2422bdd1243dSDimitry Andric static void combineVersionedSymbol(Symbol &sym, 2423bdd1243dSDimitry Andric DenseMap<Symbol *, Symbol *> &map) { 2424bdd1243dSDimitry Andric const char *suffix1 = sym.getVersionSuffix(); 2425bdd1243dSDimitry Andric if (suffix1[0] != '@' || suffix1[1] == '@') 2426bdd1243dSDimitry Andric return; 2427bdd1243dSDimitry Andric 2428bdd1243dSDimitry Andric // Check the existing symbol foo. We have two special cases to handle: 2429bdd1243dSDimitry Andric // 2430bdd1243dSDimitry Andric // * There is a definition of foo@v1 and foo@@v1. 2431bdd1243dSDimitry Andric // * There is a definition of foo@v1 and foo. 2432bdd1243dSDimitry Andric Defined *sym2 = dyn_cast_or_null<Defined>(symtab.find(sym.getName())); 2433bdd1243dSDimitry Andric if (!sym2) 2434bdd1243dSDimitry Andric return; 2435bdd1243dSDimitry Andric const char *suffix2 = sym2->getVersionSuffix(); 2436bdd1243dSDimitry Andric if (suffix2[0] == '@' && suffix2[1] == '@' && 2437bdd1243dSDimitry Andric strcmp(suffix1 + 1, suffix2 + 2) == 0) { 2438bdd1243dSDimitry Andric // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1. 2439bdd1243dSDimitry Andric map.try_emplace(&sym, sym2); 2440bdd1243dSDimitry Andric // If both foo@v1 and foo@@v1 are defined and non-weak, report a 2441bdd1243dSDimitry Andric // duplicate definition error. 2442bdd1243dSDimitry Andric if (sym.isDefined()) { 2443bdd1243dSDimitry Andric sym2->checkDuplicate(cast<Defined>(sym)); 2444bdd1243dSDimitry Andric sym2->resolve(cast<Defined>(sym)); 2445bdd1243dSDimitry Andric } else if (sym.isUndefined()) { 2446bdd1243dSDimitry Andric sym2->resolve(cast<Undefined>(sym)); 2447bdd1243dSDimitry Andric } else { 2448bdd1243dSDimitry Andric sym2->resolve(cast<SharedSymbol>(sym)); 2449bdd1243dSDimitry Andric } 2450bdd1243dSDimitry Andric // Eliminate foo@v1 from the symbol table. 2451bdd1243dSDimitry Andric sym.symbolKind = Symbol::PlaceholderKind; 2452bdd1243dSDimitry Andric sym.isUsedInRegularObj = false; 2453bdd1243dSDimitry Andric } else if (auto *sym1 = dyn_cast<Defined>(&sym)) { 2454bdd1243dSDimitry Andric if (sym2->versionId > VER_NDX_GLOBAL 2455bdd1243dSDimitry Andric ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1 2456bdd1243dSDimitry Andric : sym1->section == sym2->section && sym1->value == sym2->value) { 2457bdd1243dSDimitry Andric // Due to an assembler design flaw, if foo is defined, .symver foo, 2458bdd1243dSDimitry Andric // foo@v1 defines both foo and foo@v1. Unless foo is bound to a 2459bdd1243dSDimitry Andric // different version, GNU ld makes foo@v1 canonical and eliminates 2460bdd1243dSDimitry Andric // foo. Emulate its behavior, otherwise we would have foo or foo@@v1 2461bdd1243dSDimitry Andric // beside foo@v1. foo@v1 and foo combining does not apply if they are 2462bdd1243dSDimitry Andric // not defined in the same place. 2463bdd1243dSDimitry Andric map.try_emplace(sym2, &sym); 2464bdd1243dSDimitry Andric sym2->symbolKind = Symbol::PlaceholderKind; 2465bdd1243dSDimitry Andric sym2->isUsedInRegularObj = false; 2466bdd1243dSDimitry Andric } 2467bdd1243dSDimitry Andric } 2468bdd1243dSDimitry Andric } 2469bdd1243dSDimitry Andric 2470349cc55cSDimitry Andric // Do renaming for --wrap and foo@v1 by updating pointers to symbols. 24710b57cec5SDimitry Andric // 24720b57cec5SDimitry Andric // When this function is executed, only InputFiles and symbol table 24730b57cec5SDimitry Andric // contain pointers to symbol objects. We visit them to replace pointers, 24740b57cec5SDimitry Andric // so that wrapped symbols are swapped as instructed by the command line. 2475e8d8bef9SDimitry Andric static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) { 2476e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Redirect symbols"); 24770b57cec5SDimitry Andric DenseMap<Symbol *, Symbol *> map; 24780b57cec5SDimitry Andric for (const WrappedSymbol &w : wrapped) { 24790b57cec5SDimitry Andric map[w.sym] = w.wrap; 24800b57cec5SDimitry Andric map[w.real] = w.sym; 24810b57cec5SDimitry Andric } 2482e8d8bef9SDimitry Andric 2483bdd1243dSDimitry Andric // If there are version definitions (versionDefinitions.size() > 2), enumerate 2484bdd1243dSDimitry Andric // symbols with a non-default version (foo@v1) and check whether it should be 2485bdd1243dSDimitry Andric // combined with foo or foo@@v1. 2486bdd1243dSDimitry Andric if (config->versionDefinitions.size() > 2) 2487bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols()) 2488bdd1243dSDimitry Andric if (sym->hasVersionSuffix) 2489bdd1243dSDimitry Andric combineVersionedSymbol(*sym, map); 2490e8d8bef9SDimitry Andric 2491e8d8bef9SDimitry Andric if (map.empty()) 2492e8d8bef9SDimitry Andric return; 24930b57cec5SDimitry Andric 24940b57cec5SDimitry Andric // Update pointers in input files. 2495bdd1243dSDimitry Andric parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) { 24960eae32dcSDimitry Andric for (Symbol *&sym : file->getMutableGlobalSymbols()) 24970eae32dcSDimitry Andric if (Symbol *s = map.lookup(sym)) 24980eae32dcSDimitry Andric sym = s; 24990b57cec5SDimitry Andric }); 25000b57cec5SDimitry Andric 25010b57cec5SDimitry Andric // Update pointers in the symbol table. 25020b57cec5SDimitry Andric for (const WrappedSymbol &w : wrapped) 2503bdd1243dSDimitry Andric symtab.wrap(w.sym, w.real, w.wrap); 25040b57cec5SDimitry Andric } 25050b57cec5SDimitry Andric 25060eae32dcSDimitry Andric static void checkAndReportMissingFeature(StringRef config, uint32_t features, 25070eae32dcSDimitry Andric uint32_t mask, const Twine &report) { 25080eae32dcSDimitry Andric if (!(features & mask)) { 25090eae32dcSDimitry Andric if (config == "error") 25100eae32dcSDimitry Andric error(report); 25110eae32dcSDimitry Andric else if (config == "warning") 25120eae32dcSDimitry Andric warn(report); 25130eae32dcSDimitry Andric } 25140eae32dcSDimitry Andric } 25150eae32dcSDimitry Andric 2516bdd1243dSDimitry Andric // To enable CET (x86's hardware-assisted control flow enforcement), each 25170b57cec5SDimitry Andric // source file must be compiled with -fcf-protection. Object files compiled 25180b57cec5SDimitry Andric // with the flag contain feature flags indicating that they are compatible 25190b57cec5SDimitry Andric // with CET. We enable the feature only when all object files are compatible 25200b57cec5SDimitry Andric // with CET. 25210b57cec5SDimitry Andric // 25220b57cec5SDimitry Andric // This is also the case with AARCH64's BTI and PAC which use the similar 25230b57cec5SDimitry Andric // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism. 25241fd87a68SDimitry Andric static uint32_t getAndFeatures() { 25250b57cec5SDimitry Andric if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 25260b57cec5SDimitry Andric config->emachine != EM_AARCH64) 25270b57cec5SDimitry Andric return 0; 25280b57cec5SDimitry Andric 25290b57cec5SDimitry Andric uint32_t ret = -1; 2530bdd1243dSDimitry Andric for (ELFFileBase *f : ctx.objectFiles) { 25311fd87a68SDimitry Andric uint32_t features = f->andFeatures; 25320eae32dcSDimitry Andric 25330eae32dcSDimitry Andric checkAndReportMissingFeature( 25340eae32dcSDimitry Andric config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI, 25350eae32dcSDimitry Andric toString(f) + ": -z bti-report: file does not have " 25360eae32dcSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 25370eae32dcSDimitry Andric 25380eae32dcSDimitry Andric checkAndReportMissingFeature( 25390eae32dcSDimitry Andric config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT, 25400eae32dcSDimitry Andric toString(f) + ": -z cet-report: file does not have " 25410eae32dcSDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 25420eae32dcSDimitry Andric 25430eae32dcSDimitry Andric checkAndReportMissingFeature( 25440eae32dcSDimitry Andric config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK, 25450eae32dcSDimitry Andric toString(f) + ": -z cet-report: file does not have " 25460eae32dcSDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_SHSTK property"); 25470eae32dcSDimitry Andric 25485ffd83dbSDimitry Andric if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) { 25490eae32dcSDimitry Andric features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI; 25500eae32dcSDimitry Andric if (config->zBtiReport == "none") 25515ffd83dbSDimitry Andric warn(toString(f) + ": -z force-bti: file does not have " 25525ffd83dbSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 2553480093f4SDimitry Andric } else if (config->zForceIbt && 2554480093f4SDimitry Andric !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) { 25550eae32dcSDimitry Andric if (config->zCetReport == "none") 2556480093f4SDimitry Andric warn(toString(f) + ": -z force-ibt: file does not have " 2557480093f4SDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 2558480093f4SDimitry Andric features |= GNU_PROPERTY_X86_FEATURE_1_IBT; 2559480093f4SDimitry Andric } 25605ffd83dbSDimitry Andric if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) { 25615ffd83dbSDimitry Andric warn(toString(f) + ": -z pac-plt: file does not have " 25625ffd83dbSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property"); 25635ffd83dbSDimitry Andric features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC; 25645ffd83dbSDimitry Andric } 25650b57cec5SDimitry Andric ret &= features; 25660b57cec5SDimitry Andric } 25670b57cec5SDimitry Andric 2568480093f4SDimitry Andric // Force enable Shadow Stack. 2569480093f4SDimitry Andric if (config->zShstk) 2570480093f4SDimitry Andric ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK; 25710b57cec5SDimitry Andric 25720b57cec5SDimitry Andric return ret; 25730b57cec5SDimitry Andric } 25740b57cec5SDimitry Andric 2575bdd1243dSDimitry Andric static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) { 2576bdd1243dSDimitry Andric switch (file->ekind) { 257781ad6265SDimitry Andric case ELF32LEKind: 2578bdd1243dSDimitry Andric cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 257981ad6265SDimitry Andric break; 258081ad6265SDimitry Andric case ELF32BEKind: 2581bdd1243dSDimitry Andric cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 258281ad6265SDimitry Andric break; 258381ad6265SDimitry Andric case ELF64LEKind: 2584bdd1243dSDimitry Andric cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 258581ad6265SDimitry Andric break; 258681ad6265SDimitry Andric case ELF64BEKind: 2587bdd1243dSDimitry Andric cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 258881ad6265SDimitry Andric break; 258981ad6265SDimitry Andric default: 259081ad6265SDimitry Andric llvm_unreachable(""); 259181ad6265SDimitry Andric } 259281ad6265SDimitry Andric } 259381ad6265SDimitry Andric 259481ad6265SDimitry Andric static void postParseObjectFile(ELFFileBase *file) { 2595bdd1243dSDimitry Andric switch (file->ekind) { 259681ad6265SDimitry Andric case ELF32LEKind: 259781ad6265SDimitry Andric cast<ObjFile<ELF32LE>>(file)->postParse(); 259881ad6265SDimitry Andric break; 259981ad6265SDimitry Andric case ELF32BEKind: 260081ad6265SDimitry Andric cast<ObjFile<ELF32BE>>(file)->postParse(); 260181ad6265SDimitry Andric break; 260281ad6265SDimitry Andric case ELF64LEKind: 260381ad6265SDimitry Andric cast<ObjFile<ELF64LE>>(file)->postParse(); 260481ad6265SDimitry Andric break; 260581ad6265SDimitry Andric case ELF64BEKind: 260681ad6265SDimitry Andric cast<ObjFile<ELF64BE>>(file)->postParse(); 260781ad6265SDimitry Andric break; 260881ad6265SDimitry Andric default: 260981ad6265SDimitry Andric llvm_unreachable(""); 261081ad6265SDimitry Andric } 261181ad6265SDimitry Andric } 261281ad6265SDimitry Andric 26130b57cec5SDimitry Andric // Do actual linking. Note that when this function is called, 26140b57cec5SDimitry Andric // all linker scripts have already been parsed. 26151fd87a68SDimitry Andric void LinkerDriver::link(opt::InputArgList &args) { 26165ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link")); 2617349cc55cSDimitry Andric // If a --hash-style option was not given, set to a default value, 26180b57cec5SDimitry Andric // which varies depending on the target. 26190b57cec5SDimitry Andric if (!args.hasArg(OPT_hash_style)) { 26200b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 26210b57cec5SDimitry Andric config->sysvHash = true; 26220b57cec5SDimitry Andric else 26230b57cec5SDimitry Andric config->sysvHash = config->gnuHash = true; 26240b57cec5SDimitry Andric } 26250b57cec5SDimitry Andric 26260b57cec5SDimitry Andric // Default output filename is "a.out" by the Unix tradition. 26270b57cec5SDimitry Andric if (config->outputFile.empty()) 26280b57cec5SDimitry Andric config->outputFile = "a.out"; 26290b57cec5SDimitry Andric 26300b57cec5SDimitry Andric // Fail early if the output file or map file is not writable. If a user has a 26310b57cec5SDimitry Andric // long link, e.g. due to a large LTO link, they do not wish to run it and 26320b57cec5SDimitry Andric // find that it failed because there was a mistake in their command-line. 2633e8d8bef9SDimitry Andric { 2634e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Create output files"); 26350b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) 2636e8d8bef9SDimitry Andric error("cannot open output file " + config->outputFile + ": " + 2637e8d8bef9SDimitry Andric e.message()); 26380b57cec5SDimitry Andric if (auto e = tryCreateFile(config->mapFile)) 26390b57cec5SDimitry Andric error("cannot open map file " + config->mapFile + ": " + e.message()); 2640349cc55cSDimitry Andric if (auto e = tryCreateFile(config->whyExtract)) 2641349cc55cSDimitry Andric error("cannot open --why-extract= file " + config->whyExtract + ": " + 2642349cc55cSDimitry Andric e.message()); 2643e8d8bef9SDimitry Andric } 26440b57cec5SDimitry Andric if (errorCount()) 26450b57cec5SDimitry Andric return; 26460b57cec5SDimitry Andric 26470b57cec5SDimitry Andric // Use default entry point name if no name was given via the command 26480b57cec5SDimitry Andric // line nor linker scripts. For some reason, MIPS entry point name is 26490b57cec5SDimitry Andric // different from others. 26500b57cec5SDimitry Andric config->warnMissingEntry = 26510b57cec5SDimitry Andric (!config->entry.empty() || (!config->shared && !config->relocatable)); 26520b57cec5SDimitry Andric if (config->entry.empty() && !config->relocatable) 26530b57cec5SDimitry Andric config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start"; 26540b57cec5SDimitry Andric 26550b57cec5SDimitry Andric // Handle --trace-symbol. 26560b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_trace_symbol)) 2657bdd1243dSDimitry Andric symtab.insert(arg->getValue())->traced = true; 26580b57cec5SDimitry Andric 26595ffd83dbSDimitry Andric // Handle -u/--undefined before input files. If both a.a and b.so define foo, 26604824e7fdSDimitry Andric // -u foo a.a b.so will extract a.a. 26615ffd83dbSDimitry Andric for (StringRef name : config->undefined) 2662e8d8bef9SDimitry Andric addUnusedUndefined(name)->referenced = true; 26635ffd83dbSDimitry Andric 26640b57cec5SDimitry Andric // Add all files to the symbol table. This will add almost all 26650b57cec5SDimitry Andric // symbols that we need to the symbol table. This process might 26660b57cec5SDimitry Andric // add files to the link, via autolinking, these files are always 26670b57cec5SDimitry Andric // appended to the Files vector. 26685ffd83dbSDimitry Andric { 26695ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("Parse input files"); 2670e8d8bef9SDimitry Andric for (size_t i = 0; i < files.size(); ++i) { 2671e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName()); 26720b57cec5SDimitry Andric parseFile(files[i]); 26735ffd83dbSDimitry Andric } 2674*06c3fb27SDimitry Andric if (armCmseImpLib) 2675*06c3fb27SDimitry Andric parseArmCMSEImportLib(*armCmseImpLib); 2676e8d8bef9SDimitry Andric } 26770b57cec5SDimitry Andric 26780b57cec5SDimitry Andric // Now that we have every file, we can decide if we will need a 26790b57cec5SDimitry Andric // dynamic symbol table. 26800b57cec5SDimitry Andric // We need one if we were asked to export dynamic symbols or if we are 26810b57cec5SDimitry Andric // producing a shared library. 26820b57cec5SDimitry Andric // We also need one if any shared libraries are used and for pie executables 26830b57cec5SDimitry Andric // (probably because the dynamic linker needs it). 26840b57cec5SDimitry Andric config->hasDynSymTab = 2685bdd1243dSDimitry Andric !ctx.sharedFiles.empty() || config->isPic || config->exportDynamic; 26860b57cec5SDimitry Andric 26870b57cec5SDimitry Andric // Some symbols (such as __ehdr_start) are defined lazily only when there 26880b57cec5SDimitry Andric // are undefined symbols for them, so we add these to trigger that logic. 268981ad6265SDimitry Andric for (StringRef name : script->referencedSymbols) { 269081ad6265SDimitry Andric Symbol *sym = addUnusedUndefined(name); 269181ad6265SDimitry Andric sym->isUsedInRegularObj = true; 269281ad6265SDimitry Andric sym->referenced = true; 269381ad6265SDimitry Andric } 26940b57cec5SDimitry Andric 26955ffd83dbSDimitry Andric // Prevent LTO from removing any definition referenced by -u. 26965ffd83dbSDimitry Andric for (StringRef name : config->undefined) 2697bdd1243dSDimitry Andric if (Defined *sym = dyn_cast_or_null<Defined>(symtab.find(name))) 26985ffd83dbSDimitry Andric sym->isUsedInRegularObj = true; 26990b57cec5SDimitry Andric 27000b57cec5SDimitry Andric // If an entry symbol is in a static archive, pull out that file now. 2701bdd1243dSDimitry Andric if (Symbol *sym = symtab.find(config->entry)) 2702349cc55cSDimitry Andric handleUndefined(sym, "--entry"); 27030b57cec5SDimitry Andric 27040b57cec5SDimitry Andric // Handle the `--undefined-glob <pattern>` options. 27050b57cec5SDimitry Andric for (StringRef pat : args::getStrings(args, OPT_undefined_glob)) 27060b57cec5SDimitry Andric handleUndefinedGlob(pat); 27070b57cec5SDimitry Andric 2708480093f4SDimitry Andric // Mark -init and -fini symbols so that the LTO doesn't eliminate them. 2709bdd1243dSDimitry Andric if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->init))) 2710480093f4SDimitry Andric sym->isUsedInRegularObj = true; 2711bdd1243dSDimitry Andric if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->fini))) 2712480093f4SDimitry Andric sym->isUsedInRegularObj = true; 2713480093f4SDimitry Andric 27140b57cec5SDimitry Andric // If any of our inputs are bitcode files, the LTO code generator may create 27150b57cec5SDimitry Andric // references to certain library functions that might not be explicit in the 27160b57cec5SDimitry Andric // bitcode file's symbol table. If any of those library functions are defined 27170b57cec5SDimitry Andric // in a bitcode file in an archive member, we need to arrange to use LTO to 27180b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 27190b57cec5SDimitry Andric // 27200b57cec5SDimitry Andric // However, adding all libcall symbols to the link can have undesired 27210b57cec5SDimitry Andric // consequences. For example, the libgcc implementation of 27220b57cec5SDimitry Andric // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 27230b57cec5SDimitry Andric // that aborts the program if the Linux kernel does not support 64-bit 27240b57cec5SDimitry Andric // atomics, which would prevent the program from running even if it does not 27250b57cec5SDimitry Andric // use 64-bit atomics. 27260b57cec5SDimitry Andric // 27270b57cec5SDimitry Andric // Therefore, we only add libcall symbols to the link before LTO if we have 27280b57cec5SDimitry Andric // to, i.e. if the symbol's definition is in bitcode. Any other required 27290b57cec5SDimitry Andric // libcall symbols will be added to the link after LTO when we add the LTO 27300b57cec5SDimitry Andric // object file to the link. 2731bdd1243dSDimitry Andric if (!ctx.bitcodeFiles.empty()) 273285868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 27330b57cec5SDimitry Andric handleLibcall(s); 27340b57cec5SDimitry Andric 273581ad6265SDimitry Andric // Archive members defining __wrap symbols may be extracted. 273681ad6265SDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 273781ad6265SDimitry Andric 273881ad6265SDimitry Andric // No more lazy bitcode can be extracted at this point. Do post parse work 273981ad6265SDimitry Andric // like checking duplicate symbols. 2740bdd1243dSDimitry Andric parallelForEach(ctx.objectFiles, [](ELFFileBase *file) { 2741bdd1243dSDimitry Andric initSectionsAndLocalSyms(file, /*ignoreComdats=*/false); 2742bdd1243dSDimitry Andric }); 2743bdd1243dSDimitry Andric parallelForEach(ctx.objectFiles, postParseObjectFile); 2744bdd1243dSDimitry Andric parallelForEach(ctx.bitcodeFiles, 274581ad6265SDimitry Andric [](BitcodeFile *file) { file->postParse(); }); 2746bdd1243dSDimitry Andric for (auto &it : ctx.nonPrevailingSyms) { 274781ad6265SDimitry Andric Symbol &sym = *it.first; 2748bdd1243dSDimitry Andric Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type, 2749bdd1243dSDimitry Andric it.second) 2750bdd1243dSDimitry Andric .overwrite(sym); 275181ad6265SDimitry Andric cast<Undefined>(sym).nonPrevailing = true; 275281ad6265SDimitry Andric } 2753bdd1243dSDimitry Andric ctx.nonPrevailingSyms.clear(); 2754bdd1243dSDimitry Andric for (const DuplicateSymbol &d : ctx.duplicates) 275581ad6265SDimitry Andric reportDuplicate(*d.sym, d.file, d.section, d.value); 2756bdd1243dSDimitry Andric ctx.duplicates.clear(); 275781ad6265SDimitry Andric 27580b57cec5SDimitry Andric // Return if there were name resolution errors. 27590b57cec5SDimitry Andric if (errorCount()) 27600b57cec5SDimitry Andric return; 27610b57cec5SDimitry Andric 27620b57cec5SDimitry Andric // We want to declare linker script's symbols early, 27630b57cec5SDimitry Andric // so that we can version them. 27640b57cec5SDimitry Andric // They also might be exported if referenced by DSOs. 27650b57cec5SDimitry Andric script->declareSymbols(); 27660b57cec5SDimitry Andric 2767e8d8bef9SDimitry Andric // Handle --exclude-libs. This is before scanVersionScript() due to a 2768e8d8bef9SDimitry Andric // workaround for Android ndk: for a defined versioned symbol in an archive 2769e8d8bef9SDimitry Andric // without a version node in the version script, Android does not expect a 2770e8d8bef9SDimitry Andric // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295). 2771e8d8bef9SDimitry Andric // GNU ld errors in this case. 27720b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_libs)) 27730b57cec5SDimitry Andric excludeLibs(args); 27740b57cec5SDimitry Andric 27750b57cec5SDimitry Andric // Create elfHeader early. We need a dummy section in 27760b57cec5SDimitry Andric // addReservedSymbols to mark the created symbols as not absolute. 27770b57cec5SDimitry Andric Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC); 27780b57cec5SDimitry Andric 27790b57cec5SDimitry Andric // We need to create some reserved symbols such as _end. Create them. 27800b57cec5SDimitry Andric if (!config->relocatable) 27810b57cec5SDimitry Andric addReservedSymbols(); 27820b57cec5SDimitry Andric 27830b57cec5SDimitry Andric // Apply version scripts. 27840b57cec5SDimitry Andric // 27850b57cec5SDimitry Andric // For a relocatable output, version scripts don't make sense, and 27860b57cec5SDimitry Andric // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 27870b57cec5SDimitry Andric // name "foo@ver1") rather do harm, so we don't call this if -r is given. 2788e8d8bef9SDimitry Andric if (!config->relocatable) { 2789e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Process symbol versions"); 2790bdd1243dSDimitry Andric symtab.scanVersionScript(); 2791e8d8bef9SDimitry Andric } 27920b57cec5SDimitry Andric 279304eeddc0SDimitry Andric // Skip the normal linked output if some LTO options are specified. 279404eeddc0SDimitry Andric // 279504eeddc0SDimitry Andric // For --thinlto-index-only, index file creation is performed in 279604eeddc0SDimitry Andric // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and 279704eeddc0SDimitry Andric // --plugin-opt=emit-asm create output files in bitcode or assembly code, 279804eeddc0SDimitry Andric // respectively. When only certain thinLTO modules are specified for 279904eeddc0SDimitry Andric // compilation, the intermediate object file are the expected output. 280004eeddc0SDimitry Andric const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM || 280104eeddc0SDimitry Andric config->ltoEmitAsm || 280204eeddc0SDimitry Andric !config->thinLTOModulesToCompile.empty(); 280304eeddc0SDimitry Andric 28040b57cec5SDimitry Andric // Do link-time optimization if given files are LLVM bitcode files. 28050b57cec5SDimitry Andric // This compiles bitcode files into real object files. 28060b57cec5SDimitry Andric // 28070b57cec5SDimitry Andric // With this the symbol table should be complete. After this, no new names 28080b57cec5SDimitry Andric // except a few linker-synthesized ones will be added to the symbol table. 2809bdd1243dSDimitry Andric const size_t numObjsBeforeLTO = ctx.objectFiles.size(); 28101fd87a68SDimitry Andric invokeELFT(compileBitcodeFiles, skipLinkedOutput); 281104eeddc0SDimitry Andric 281281ad6265SDimitry Andric // Symbol resolution finished. Report backward reference problems, 281381ad6265SDimitry Andric // --print-archive-stats=, and --why-extract=. 281404eeddc0SDimitry Andric reportBackrefs(); 281581ad6265SDimitry Andric writeArchiveStats(); 281681ad6265SDimitry Andric writeWhyExtract(); 281704eeddc0SDimitry Andric if (errorCount()) 281804eeddc0SDimitry Andric return; 281904eeddc0SDimitry Andric 282004eeddc0SDimitry Andric // Bail out if normal linked output is skipped due to LTO. 282104eeddc0SDimitry Andric if (skipLinkedOutput) 282204eeddc0SDimitry Andric return; 28235ffd83dbSDimitry Andric 282481ad6265SDimitry Andric // compileBitcodeFiles may have produced lto.tmp object files. After this, no 282581ad6265SDimitry Andric // more file will be added. 2826bdd1243dSDimitry Andric auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO); 2827bdd1243dSDimitry Andric parallelForEach(newObjectFiles, [](ELFFileBase *file) { 2828bdd1243dSDimitry Andric initSectionsAndLocalSyms(file, /*ignoreComdats=*/true); 2829bdd1243dSDimitry Andric }); 283081ad6265SDimitry Andric parallelForEach(newObjectFiles, postParseObjectFile); 2831bdd1243dSDimitry Andric for (const DuplicateSymbol &d : ctx.duplicates) 283281ad6265SDimitry Andric reportDuplicate(*d.sym, d.file, d.section, d.value); 283381ad6265SDimitry Andric 2834e8d8bef9SDimitry Andric // Handle --exclude-libs again because lto.tmp may reference additional 2835e8d8bef9SDimitry Andric // libcalls symbols defined in an excluded archive. This may override 2836e8d8bef9SDimitry Andric // versionId set by scanVersionScript(). 2837e8d8bef9SDimitry Andric if (args.hasArg(OPT_exclude_libs)) 2838e8d8bef9SDimitry Andric excludeLibs(args); 2839e8d8bef9SDimitry Andric 2840*06c3fb27SDimitry Andric // Record [__acle_se_<sym>, <sym>] pairs for later processing. 2841*06c3fb27SDimitry Andric processArmCmseSymbols(); 2842*06c3fb27SDimitry Andric 2843349cc55cSDimitry Andric // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1. 2844e8d8bef9SDimitry Andric redirectSymbols(wrapped); 28450b57cec5SDimitry Andric 284604eeddc0SDimitry Andric // Replace common symbols with regular symbols. 284704eeddc0SDimitry Andric replaceCommonSymbols(); 284804eeddc0SDimitry Andric 2849e8d8bef9SDimitry Andric { 2850e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Aggregate sections"); 28510b57cec5SDimitry Andric // Now that we have a complete list of input files. 28520b57cec5SDimitry Andric // Beyond this point, no new files are added. 28530b57cec5SDimitry Andric // Aggregate all input sections into one place. 2854bdd1243dSDimitry Andric for (InputFile *f : ctx.objectFiles) { 2855bdd1243dSDimitry Andric for (InputSectionBase *s : f->getSections()) { 2856bdd1243dSDimitry Andric if (!s || s == &InputSection::discarded) 2857bdd1243dSDimitry Andric continue; 2858bdd1243dSDimitry Andric if (LLVM_UNLIKELY(isa<EhInputSection>(s))) 2859bdd1243dSDimitry Andric ctx.ehInputSections.push_back(cast<EhInputSection>(s)); 2860bdd1243dSDimitry Andric else 2861bdd1243dSDimitry Andric ctx.inputSections.push_back(s); 2862bdd1243dSDimitry Andric } 2863bdd1243dSDimitry Andric } 2864bdd1243dSDimitry Andric for (BinaryFile *f : ctx.binaryFiles) 28650b57cec5SDimitry Andric for (InputSectionBase *s : f->getSections()) 2866bdd1243dSDimitry Andric ctx.inputSections.push_back(cast<InputSection>(s)); 2867e8d8bef9SDimitry Andric } 28680b57cec5SDimitry Andric 2869e8d8bef9SDimitry Andric { 2870e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Strip sections"); 2871bdd1243dSDimitry Andric if (ctx.hasSympart.load(std::memory_order_relaxed)) { 2872bdd1243dSDimitry Andric llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) { 287381ad6265SDimitry Andric if (s->type != SHT_LLVM_SYMPART) 287481ad6265SDimitry Andric return false; 28751fd87a68SDimitry Andric invokeELFT(readSymbolPartitionSection, s); 28760b57cec5SDimitry Andric return true; 287781ad6265SDimitry Andric }); 28780b57cec5SDimitry Andric } 28790b57cec5SDimitry Andric // We do not want to emit debug sections if --strip-all 2880349cc55cSDimitry Andric // or --strip-debug are given. 288181ad6265SDimitry Andric if (config->strip != StripPolicy::None) { 2882bdd1243dSDimitry Andric llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) { 2883d65cd7a5SDimitry Andric if (isDebugSection(*s)) 2884d65cd7a5SDimitry Andric return true; 2885d65cd7a5SDimitry Andric if (auto *isec = dyn_cast<InputSection>(s)) 2886d65cd7a5SDimitry Andric if (InputSectionBase *rel = isec->getRelocatedSection()) 2887d65cd7a5SDimitry Andric if (isDebugSection(*rel)) 2888d65cd7a5SDimitry Andric return true; 2889d65cd7a5SDimitry Andric 2890d65cd7a5SDimitry Andric return false; 28910b57cec5SDimitry Andric }); 2892e8d8bef9SDimitry Andric } 289381ad6265SDimitry Andric } 2894e8d8bef9SDimitry Andric 2895e8d8bef9SDimitry Andric // Since we now have a complete set of input files, we can create 2896e8d8bef9SDimitry Andric // a .d file to record build dependencies. 2897e8d8bef9SDimitry Andric if (!config->dependencyFile.empty()) 2898e8d8bef9SDimitry Andric writeDependencyFile(); 28990b57cec5SDimitry Andric 29000b57cec5SDimitry Andric // Now that the number of partitions is fixed, save a pointer to the main 29010b57cec5SDimitry Andric // partition. 29020b57cec5SDimitry Andric mainPart = &partitions[0]; 29030b57cec5SDimitry Andric 29040b57cec5SDimitry Andric // Read .note.gnu.property sections from input object files which 29050b57cec5SDimitry Andric // contain a hint to tweak linker's and loader's behaviors. 29061fd87a68SDimitry Andric config->andFeatures = getAndFeatures(); 29070b57cec5SDimitry Andric 29080b57cec5SDimitry Andric // The Target instance handles target-specific stuff, such as applying 29090b57cec5SDimitry Andric // relocations or writing a PLT section. It also contains target-dependent 29100b57cec5SDimitry Andric // values such as a default image base address. 29110b57cec5SDimitry Andric target = getTarget(); 29120b57cec5SDimitry Andric 29130b57cec5SDimitry Andric config->eflags = target->calcEFlags(); 29140b57cec5SDimitry Andric // maxPageSize (sometimes called abi page size) is the maximum page size that 29150b57cec5SDimitry Andric // the output can be run on. For example if the OS can use 4k or 64k page 29160b57cec5SDimitry Andric // sizes then maxPageSize must be 64k for the output to be useable on both. 29170b57cec5SDimitry Andric // All important alignment decisions must use this value. 29180b57cec5SDimitry Andric config->maxPageSize = getMaxPageSize(args); 29190b57cec5SDimitry Andric // commonPageSize is the most common page size that the output will be run on. 29200b57cec5SDimitry Andric // For example if an OS can use 4k or 64k page sizes and 4k is more common 29210b57cec5SDimitry Andric // than 64k then commonPageSize is set to 4k. commonPageSize can be used for 29220b57cec5SDimitry Andric // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 29230b57cec5SDimitry Andric // is limited to writing trap instructions on the last executable segment. 29240b57cec5SDimitry Andric config->commonPageSize = getCommonPageSize(args); 29250b57cec5SDimitry Andric 29260b57cec5SDimitry Andric config->imageBase = getImageBase(args); 29270b57cec5SDimitry Andric 292885868e8aSDimitry Andric // This adds a .comment section containing a version string. 29290b57cec5SDimitry Andric if (!config->relocatable) 2930bdd1243dSDimitry Andric ctx.inputSections.push_back(createCommentSection()); 29310b57cec5SDimitry Andric 293285868e8aSDimitry Andric // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection. 2933*06c3fb27SDimitry Andric invokeELFT(splitSections,); 293485868e8aSDimitry Andric 293585868e8aSDimitry Andric // Garbage collection and removal of shared symbols from unused shared objects. 2936*06c3fb27SDimitry Andric invokeELFT(markLive,); 293781ad6265SDimitry Andric demoteSharedAndLazySymbols(); 293885868e8aSDimitry Andric 293985868e8aSDimitry Andric // Make copies of any input sections that need to be copied into each 294085868e8aSDimitry Andric // partition. 294185868e8aSDimitry Andric copySectionsIntoPartitions(); 294285868e8aSDimitry Andric 294385868e8aSDimitry Andric // Create synthesized sections such as .got and .plt. This is called before 294485868e8aSDimitry Andric // processSectionCommands() so that they can be placed by SECTIONS commands. 2945*06c3fb27SDimitry Andric invokeELFT(createSyntheticSections,); 294685868e8aSDimitry Andric 294785868e8aSDimitry Andric // Some input sections that are used for exception handling need to be moved 294885868e8aSDimitry Andric // into synthetic sections. Do that now so that they aren't assigned to 294985868e8aSDimitry Andric // output sections in the usual way. 295085868e8aSDimitry Andric if (!config->relocatable) 295185868e8aSDimitry Andric combineEhSections(); 295285868e8aSDimitry Andric 2953bdd1243dSDimitry Andric // Merge .riscv.attributes sections. 2954bdd1243dSDimitry Andric if (config->emachine == EM_RISCV) 2955bdd1243dSDimitry Andric mergeRISCVAttributesSections(); 2956bdd1243dSDimitry Andric 2957e8d8bef9SDimitry Andric { 2958e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Assign sections"); 2959e8d8bef9SDimitry Andric 296085868e8aSDimitry Andric // Create output sections described by SECTIONS commands. 296185868e8aSDimitry Andric script->processSectionCommands(); 296285868e8aSDimitry Andric 2963e8d8bef9SDimitry Andric // Linker scripts control how input sections are assigned to output 2964e8d8bef9SDimitry Andric // sections. Input sections that were not handled by scripts are called 2965e8d8bef9SDimitry Andric // "orphans", and they are assigned to output sections by the default rule. 2966e8d8bef9SDimitry Andric // Process that. 296785868e8aSDimitry Andric script->addOrphanSections(); 2968e8d8bef9SDimitry Andric } 2969e8d8bef9SDimitry Andric 2970e8d8bef9SDimitry Andric { 2971e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Merge/finalize input sections"); 297285868e8aSDimitry Andric 297385868e8aSDimitry Andric // Migrate InputSectionDescription::sectionBases to sections. This includes 297485868e8aSDimitry Andric // merging MergeInputSections into a single MergeSyntheticSection. From this 297585868e8aSDimitry Andric // point onwards InputSectionDescription::sections should be used instead of 297685868e8aSDimitry Andric // sectionBases. 29774824e7fdSDimitry Andric for (SectionCommand *cmd : script->sectionCommands) 297881ad6265SDimitry Andric if (auto *osd = dyn_cast<OutputDesc>(cmd)) 297981ad6265SDimitry Andric osd->osec.finalizeInputSections(); 2980e8d8bef9SDimitry Andric } 298185868e8aSDimitry Andric 298285868e8aSDimitry Andric // Two input sections with different output sections should not be folded. 298385868e8aSDimitry Andric // ICF runs after processSectionCommands() so that we know the output sections. 29840b57cec5SDimitry Andric if (config->icf != ICFLevel::None) { 29851fd87a68SDimitry Andric invokeELFT(findKeepUniqueSections, args); 2986*06c3fb27SDimitry Andric invokeELFT(doIcf,); 29870b57cec5SDimitry Andric } 29880b57cec5SDimitry Andric 29890b57cec5SDimitry Andric // Read the callgraph now that we know what was gced or icfed 29900b57cec5SDimitry Andric if (config->callGraphProfileSort) { 29910b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) 2992bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 29930b57cec5SDimitry Andric readCallGraph(*buffer); 2994*06c3fb27SDimitry Andric invokeELFT(readCallGraphsFromObjectFiles,); 29950b57cec5SDimitry Andric } 29960b57cec5SDimitry Andric 29970b57cec5SDimitry Andric // Write the result to the file. 2998*06c3fb27SDimitry Andric invokeELFT(writeResult,); 29990b57cec5SDimitry Andric } 3000