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" 55*5f757f3fSDimitry Andric #include "llvm/Object/IRObjectFile.h" 56e8d8bef9SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h" 570b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 580b57cec5SDimitry Andric #include "llvm/Support/Compression.h" 5981ad6265SDimitry Andric #include "llvm/Support/FileSystem.h" 600b57cec5SDimitry Andric #include "llvm/Support/GlobPattern.h" 610b57cec5SDimitry Andric #include "llvm/Support/LEB128.h" 625ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h" 630b57cec5SDimitry Andric #include "llvm/Support/Path.h" 640b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h" 650b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h" 665ffd83dbSDimitry Andric #include "llvm/Support/TimeProfiler.h" 670b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 680b57cec5SDimitry Andric #include <cstdlib> 6906c3fb27SDimitry Andric #include <tuple> 700b57cec5SDimitry Andric #include <utility> 710b57cec5SDimitry Andric 720b57cec5SDimitry Andric using namespace llvm; 730b57cec5SDimitry Andric using namespace llvm::ELF; 740b57cec5SDimitry Andric using namespace llvm::object; 750b57cec5SDimitry Andric using namespace llvm::sys; 760b57cec5SDimitry Andric using namespace llvm::support; 775ffd83dbSDimitry Andric using namespace lld; 785ffd83dbSDimitry Andric using namespace lld::elf; 790b57cec5SDimitry Andric 80bdd1243dSDimitry Andric ConfigWrapper elf::config; 81bdd1243dSDimitry Andric Ctx elf::ctx; 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args); 840b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args); 850b57cec5SDimitry Andric 861fd87a68SDimitry Andric void elf::errorOrWarn(const Twine &msg) { 871fd87a68SDimitry Andric if (config->noinhibitExec) 881fd87a68SDimitry Andric warn(msg); 891fd87a68SDimitry Andric else 901fd87a68SDimitry Andric error(msg); 911fd87a68SDimitry Andric } 921fd87a68SDimitry Andric 93bdd1243dSDimitry Andric void Ctx::reset() { 94bdd1243dSDimitry Andric driver = LinkerDriver(); 95bdd1243dSDimitry Andric memoryBuffers.clear(); 96bdd1243dSDimitry Andric objectFiles.clear(); 97bdd1243dSDimitry Andric sharedFiles.clear(); 98bdd1243dSDimitry Andric binaryFiles.clear(); 99bdd1243dSDimitry Andric bitcodeFiles.clear(); 100bdd1243dSDimitry Andric lazyBitcodeFiles.clear(); 101bdd1243dSDimitry Andric inputSections.clear(); 102bdd1243dSDimitry Andric ehInputSections.clear(); 103bdd1243dSDimitry Andric duplicates.clear(); 104bdd1243dSDimitry Andric nonPrevailingSyms.clear(); 105bdd1243dSDimitry Andric whyExtractRecords.clear(); 106bdd1243dSDimitry Andric backwardReferences.clear(); 107*5f757f3fSDimitry Andric auxiliaryFiles.clear(); 108bdd1243dSDimitry Andric hasSympart.store(false, std::memory_order_relaxed); 109*5f757f3fSDimitry Andric hasTlsIe.store(false, std::memory_order_relaxed); 110bdd1243dSDimitry Andric needsTlsLd.store(false, std::memory_order_relaxed); 111*5f757f3fSDimitry Andric scriptSymOrderCounter = 1; 112*5f757f3fSDimitry Andric scriptSymOrder.clear(); 113*5f757f3fSDimitry Andric ltoAllVtablesHaveTypeInfos = false; 114bdd1243dSDimitry Andric } 115bdd1243dSDimitry Andric 11606c3fb27SDimitry Andric llvm::raw_fd_ostream Ctx::openAuxiliaryFile(llvm::StringRef filename, 11706c3fb27SDimitry Andric std::error_code &ec) { 11806c3fb27SDimitry Andric using namespace llvm::sys::fs; 11906c3fb27SDimitry Andric OpenFlags flags = 12006c3fb27SDimitry Andric auxiliaryFiles.insert(filename).second ? OF_None : OF_Append; 12106c3fb27SDimitry Andric return {filename, ec, flags}; 12206c3fb27SDimitry Andric } 12306c3fb27SDimitry Andric 12406c3fb27SDimitry Andric namespace lld { 12506c3fb27SDimitry Andric namespace elf { 12606c3fb27SDimitry Andric bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS, 12706c3fb27SDimitry Andric llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) { 12806c3fb27SDimitry Andric // This driver-specific context will be freed later by unsafeLldMain(). 12904eeddc0SDimitry Andric auto *ctx = new CommonLinkerContext; 130480093f4SDimitry Andric 13104eeddc0SDimitry Andric ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); 13204eeddc0SDimitry Andric ctx->e.cleanupCallback = []() { 133bdd1243dSDimitry Andric elf::ctx.reset(); 134bdd1243dSDimitry Andric symtab = SymbolTable(); 135bdd1243dSDimitry Andric 1360b57cec5SDimitry Andric outputSections.clear(); 13704eeddc0SDimitry Andric symAux.clear(); 1380b57cec5SDimitry Andric 1390b57cec5SDimitry Andric tar = nullptr; 14004eeddc0SDimitry Andric in.reset(); 1410b57cec5SDimitry Andric 14204eeddc0SDimitry Andric partitions.clear(); 14304eeddc0SDimitry Andric partitions.emplace_back(); 1440b57cec5SDimitry Andric 1450b57cec5SDimitry Andric SharedFile::vernauxNum = 0; 146e8d8bef9SDimitry Andric }; 14704eeddc0SDimitry Andric ctx->e.logName = args::getFilenameWithoutExe(args[0]); 14804eeddc0SDimitry Andric ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use " 14981ad6265SDimitry Andric "--error-limit=0 to see all errors)"; 150e8d8bef9SDimitry Andric 151bdd1243dSDimitry Andric config = ConfigWrapper(); 1520eae32dcSDimitry Andric script = std::make_unique<LinkerScript>(); 153bdd1243dSDimitry Andric 154bdd1243dSDimitry Andric symAux.emplace_back(); 155e8d8bef9SDimitry Andric 15604eeddc0SDimitry Andric partitions.clear(); 15704eeddc0SDimitry Andric partitions.emplace_back(); 1580b57cec5SDimitry Andric 1590b57cec5SDimitry Andric config->progName = args[0]; 1600b57cec5SDimitry Andric 161bdd1243dSDimitry Andric elf::ctx.driver.linkerMain(args); 1620b57cec5SDimitry Andric 16304eeddc0SDimitry Andric return errorCount() == 0; 1640b57cec5SDimitry Andric } 16506c3fb27SDimitry Andric } // namespace elf 16606c3fb27SDimitry Andric } // namespace lld 1670b57cec5SDimitry Andric 1680b57cec5SDimitry Andric // Parses a linker -m option. 1690b57cec5SDimitry Andric static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) { 1700b57cec5SDimitry Andric uint8_t osabi = 0; 1710b57cec5SDimitry Andric StringRef s = emul; 17206c3fb27SDimitry Andric if (s.ends_with("_fbsd")) { 1730b57cec5SDimitry Andric s = s.drop_back(5); 1740b57cec5SDimitry Andric osabi = ELFOSABI_FREEBSD; 1750b57cec5SDimitry Andric } 1760b57cec5SDimitry Andric 1770b57cec5SDimitry Andric std::pair<ELFKind, uint16_t> ret = 1780b57cec5SDimitry Andric StringSwitch<std::pair<ELFKind, uint16_t>>(s) 179fe6060f1SDimitry Andric .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64}) 180fe6060f1SDimitry Andric .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64}) 1810b57cec5SDimitry Andric .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 18206c3fb27SDimitry Andric .Cases("armelfb", "armelfb_linux_eabi", {ELF32BEKind, EM_ARM}) 1830b57cec5SDimitry Andric .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 1840b57cec5SDimitry Andric .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 1850b57cec5SDimitry Andric .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 1860b57cec5SDimitry Andric .Case("elf32lriscv", {ELF32LEKind, EM_RISCV}) 1870b57cec5SDimitry Andric .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC}) 188e8d8bef9SDimitry Andric .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC}) 18906c3fb27SDimitry Andric .Case("elf32loongarch", {ELF32LEKind, EM_LOONGARCH}) 1900b57cec5SDimitry Andric .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 1910b57cec5SDimitry Andric .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 1920b57cec5SDimitry Andric .Case("elf64lriscv", {ELF64LEKind, EM_RISCV}) 1930b57cec5SDimitry Andric .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 1940b57cec5SDimitry Andric .Case("elf64lppc", {ELF64LEKind, EM_PPC64}) 1950b57cec5SDimitry Andric .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 1960b57cec5SDimitry Andric .Case("elf_i386", {ELF32LEKind, EM_386}) 1970b57cec5SDimitry Andric .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 1985ffd83dbSDimitry Andric .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9}) 199e8d8bef9SDimitry Andric .Case("msp430elf", {ELF32LEKind, EM_MSP430}) 200bdd1243dSDimitry Andric .Case("elf64_amdgpu", {ELF64LEKind, EM_AMDGPU}) 20106c3fb27SDimitry Andric .Case("elf64loongarch", {ELF64LEKind, EM_LOONGARCH}) 2020b57cec5SDimitry Andric .Default({ELFNoneKind, EM_NONE}); 2030b57cec5SDimitry Andric 2040b57cec5SDimitry Andric if (ret.first == ELFNoneKind) 2050b57cec5SDimitry Andric error("unknown emulation: " + emul); 206e8d8bef9SDimitry Andric if (ret.second == EM_MSP430) 207e8d8bef9SDimitry Andric osabi = ELFOSABI_STANDALONE; 208bdd1243dSDimitry Andric else if (ret.second == EM_AMDGPU) 209bdd1243dSDimitry Andric osabi = ELFOSABI_AMDGPU_HSA; 2100b57cec5SDimitry Andric return std::make_tuple(ret.first, ret.second, osabi); 2110b57cec5SDimitry Andric } 2120b57cec5SDimitry Andric 2130b57cec5SDimitry Andric // Returns slices of MB by parsing MB as an archive file. 2140b57cec5SDimitry Andric // Each slice consists of a member file in the archive. 2150b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 2160b57cec5SDimitry Andric MemoryBufferRef mb) { 2170b57cec5SDimitry Andric std::unique_ptr<Archive> file = 2180b57cec5SDimitry Andric CHECK(Archive::create(mb), 2190b57cec5SDimitry Andric mb.getBufferIdentifier() + ": failed to parse archive"); 2200b57cec5SDimitry Andric 2210b57cec5SDimitry Andric std::vector<std::pair<MemoryBufferRef, uint64_t>> v; 2220b57cec5SDimitry Andric Error err = Error::success(); 2230b57cec5SDimitry Andric bool addToTar = file->isThin() && tar; 224480093f4SDimitry Andric for (const Archive::Child &c : file->children(err)) { 2250b57cec5SDimitry Andric MemoryBufferRef mbref = 2260b57cec5SDimitry Andric CHECK(c.getMemoryBufferRef(), 2270b57cec5SDimitry Andric mb.getBufferIdentifier() + 2280b57cec5SDimitry Andric ": could not get the buffer for a child of the archive"); 2290b57cec5SDimitry Andric if (addToTar) 2300b57cec5SDimitry Andric tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer()); 2310b57cec5SDimitry Andric v.push_back(std::make_pair(mbref, c.getChildOffset())); 2320b57cec5SDimitry Andric } 2330b57cec5SDimitry Andric if (err) 2340b57cec5SDimitry Andric fatal(mb.getBufferIdentifier() + ": Archive::children failed: " + 2350b57cec5SDimitry Andric toString(std::move(err))); 2360b57cec5SDimitry Andric 2370b57cec5SDimitry Andric // Take ownership of memory buffers created for members of thin archives. 2381fd87a68SDimitry Andric std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers(); 239bdd1243dSDimitry Andric std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers)); 2400b57cec5SDimitry Andric 2410b57cec5SDimitry Andric return v; 2420b57cec5SDimitry Andric } 2430b57cec5SDimitry Andric 244fcaf7f86SDimitry Andric static bool isBitcode(MemoryBufferRef mb) { 245fcaf7f86SDimitry Andric return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode; 246fcaf7f86SDimitry Andric } 247fcaf7f86SDimitry Andric 248*5f757f3fSDimitry Andric bool LinkerDriver::tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName, 249*5f757f3fSDimitry Andric uint64_t offsetInArchive, bool lazy) { 250*5f757f3fSDimitry Andric if (!config->fatLTOObjects) 251*5f757f3fSDimitry Andric return false; 252*5f757f3fSDimitry Andric Expected<MemoryBufferRef> fatLTOData = 253*5f757f3fSDimitry Andric IRObjectFile::findBitcodeInMemBuffer(mb); 254*5f757f3fSDimitry Andric if (errorToBool(fatLTOData.takeError())) 255*5f757f3fSDimitry Andric return false; 256*5f757f3fSDimitry Andric files.push_back( 257*5f757f3fSDimitry Andric make<BitcodeFile>(*fatLTOData, archiveName, offsetInArchive, lazy)); 258*5f757f3fSDimitry Andric return true; 259*5f757f3fSDimitry Andric } 260*5f757f3fSDimitry Andric 2610b57cec5SDimitry Andric // Opens a file and create a file object. Path has to be resolved already. 2620b57cec5SDimitry Andric void LinkerDriver::addFile(StringRef path, bool withLOption) { 2630b57cec5SDimitry Andric using namespace sys::fs; 2640b57cec5SDimitry Andric 265bdd1243dSDimitry Andric std::optional<MemoryBufferRef> buffer = readFile(path); 26681ad6265SDimitry Andric if (!buffer) 2670b57cec5SDimitry Andric return; 2680b57cec5SDimitry Andric MemoryBufferRef mbref = *buffer; 2690b57cec5SDimitry Andric 2700b57cec5SDimitry Andric if (config->formatBinary) { 2710b57cec5SDimitry Andric files.push_back(make<BinaryFile>(mbref)); 2720b57cec5SDimitry Andric return; 2730b57cec5SDimitry Andric } 2740b57cec5SDimitry Andric 2750b57cec5SDimitry Andric switch (identify_magic(mbref.getBuffer())) { 2760b57cec5SDimitry Andric case file_magic::unknown: 2770b57cec5SDimitry Andric readLinkerScript(mbref); 2780b57cec5SDimitry Andric return; 2790b57cec5SDimitry Andric case file_magic::archive: { 280bdd1243dSDimitry Andric auto members = getArchiveMembers(mbref); 2810b57cec5SDimitry Andric if (inWholeArchive) { 282bdd1243dSDimitry Andric for (const std::pair<MemoryBufferRef, uint64_t> &p : members) { 283fcaf7f86SDimitry Andric if (isBitcode(p.first)) 284fcaf7f86SDimitry Andric files.push_back(make<BitcodeFile>(p.first, path, p.second, false)); 285*5f757f3fSDimitry Andric else if (!tryAddFatLTOFile(p.first, path, p.second, false)) 286fcaf7f86SDimitry Andric files.push_back(createObjFile(p.first, path)); 287fcaf7f86SDimitry Andric } 2880b57cec5SDimitry Andric return; 2890b57cec5SDimitry Andric } 2900b57cec5SDimitry Andric 29181ad6265SDimitry Andric archiveFiles.emplace_back(path, members.size()); 2920b57cec5SDimitry Andric 29381ad6265SDimitry Andric // Handle archives and --start-lib/--end-lib using the same code path. This 29481ad6265SDimitry Andric // scans all the ELF relocatable object files and bitcode files in the 29581ad6265SDimitry Andric // archive rather than just the index file, with the benefit that the 29681ad6265SDimitry Andric // symbols are only loaded once. For many projects archives see high 29781ad6265SDimitry Andric // utilization rates and it is a net performance win. --start-lib scans 29881ad6265SDimitry Andric // symbols in the same order that llvm-ar adds them to the index, so in the 29981ad6265SDimitry Andric // common case the semantics are identical. If the archive symbol table was 30081ad6265SDimitry Andric // created in a different order, or is incomplete, this strategy has 30181ad6265SDimitry Andric // different semantics. Such output differences are considered user error. 30281ad6265SDimitry Andric // 303d56accc7SDimitry Andric // All files within the archive get the same group ID to allow mutual 304d56accc7SDimitry Andric // references for --warn-backrefs. 305d56accc7SDimitry Andric bool saved = InputFile::isInGroup; 306d56accc7SDimitry Andric InputFile::isInGroup = true; 30781ad6265SDimitry Andric for (const std::pair<MemoryBufferRef, uint64_t> &p : members) { 30804eeddc0SDimitry Andric auto magic = identify_magic(p.first.getBuffer()); 309*5f757f3fSDimitry Andric if (magic == file_magic::elf_relocatable) { 310*5f757f3fSDimitry Andric if (!tryAddFatLTOFile(p.first, path, p.second, true)) 311fcaf7f86SDimitry Andric files.push_back(createObjFile(p.first, path, true)); 312*5f757f3fSDimitry Andric } else if (magic == file_magic::bitcode) 313fcaf7f86SDimitry Andric files.push_back(make<BitcodeFile>(p.first, path, p.second, true)); 31404eeddc0SDimitry Andric else 31581ad6265SDimitry Andric warn(path + ": archive member '" + p.first.getBufferIdentifier() + 31604eeddc0SDimitry Andric "' is neither ET_REL nor LLVM bitcode"); 31704eeddc0SDimitry Andric } 318d56accc7SDimitry Andric InputFile::isInGroup = saved; 319d56accc7SDimitry Andric if (!saved) 320d56accc7SDimitry Andric ++InputFile::nextGroupId; 3210b57cec5SDimitry Andric return; 3220b57cec5SDimitry Andric } 323bdd1243dSDimitry Andric case file_magic::elf_shared_object: { 3240b57cec5SDimitry Andric if (config->isStatic || config->relocatable) { 3250b57cec5SDimitry Andric error("attempted static link of dynamic object " + path); 3260b57cec5SDimitry Andric return; 3270b57cec5SDimitry Andric } 3280b57cec5SDimitry Andric 329349cc55cSDimitry Andric // Shared objects are identified by soname. soname is (if specified) 330349cc55cSDimitry Andric // DT_SONAME and falls back to filename. If a file was specified by -lfoo, 331349cc55cSDimitry Andric // the directory part is ignored. Note that path may be a temporary and 332349cc55cSDimitry Andric // cannot be stored into SharedFile::soName. 333349cc55cSDimitry Andric path = mbref.getBufferIdentifier(); 334bdd1243dSDimitry Andric auto *f = 335bdd1243dSDimitry Andric make<SharedFile>(mbref, withLOption ? path::filename(path) : path); 336bdd1243dSDimitry Andric f->init(); 337bdd1243dSDimitry Andric files.push_back(f); 3380b57cec5SDimitry Andric return; 339bdd1243dSDimitry Andric } 3400b57cec5SDimitry Andric case file_magic::bitcode: 341fcaf7f86SDimitry Andric files.push_back(make<BitcodeFile>(mbref, "", 0, inLib)); 342fcaf7f86SDimitry Andric break; 3430b57cec5SDimitry Andric case file_magic::elf_relocatable: 344*5f757f3fSDimitry Andric if (!tryAddFatLTOFile(mbref, "", 0, inLib)) 345fcaf7f86SDimitry Andric files.push_back(createObjFile(mbref, "", inLib)); 3460b57cec5SDimitry Andric break; 3470b57cec5SDimitry Andric default: 3480b57cec5SDimitry Andric error(path + ": unknown file type"); 3490b57cec5SDimitry Andric } 3500b57cec5SDimitry Andric } 3510b57cec5SDimitry Andric 3520b57cec5SDimitry Andric // Add a given library by searching it from input search paths. 3530b57cec5SDimitry Andric void LinkerDriver::addLibrary(StringRef name) { 354bdd1243dSDimitry Andric if (std::optional<std::string> path = searchLibrary(name)) 355972a253aSDimitry Andric addFile(saver().save(*path), /*withLOption=*/true); 3560b57cec5SDimitry Andric else 357e8d8bef9SDimitry Andric error("unable to find library -l" + name, ErrorTag::LibNotFound, {name}); 3580b57cec5SDimitry Andric } 3590b57cec5SDimitry Andric 3600b57cec5SDimitry Andric // This function is called on startup. We need this for LTO since 3610b57cec5SDimitry Andric // LTO calls LLVM functions to compile bitcode files to native code. 3620b57cec5SDimitry Andric // Technically this can be delayed until we read bitcode files, but 3630b57cec5SDimitry Andric // we don't bother to do lazily because the initialization is fast. 3640b57cec5SDimitry Andric static void initLLVM() { 3650b57cec5SDimitry Andric InitializeAllTargets(); 3660b57cec5SDimitry Andric InitializeAllTargetMCs(); 3670b57cec5SDimitry Andric InitializeAllAsmPrinters(); 3680b57cec5SDimitry Andric InitializeAllAsmParsers(); 3690b57cec5SDimitry Andric } 3700b57cec5SDimitry Andric 3710b57cec5SDimitry Andric // Some command line options or some combinations of them are not allowed. 3720b57cec5SDimitry Andric // This function checks for such errors. 3730b57cec5SDimitry Andric static void checkOptions() { 3740b57cec5SDimitry Andric // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 3750b57cec5SDimitry Andric // table which is a relatively new feature. 3760b57cec5SDimitry Andric if (config->emachine == EM_MIPS && config->gnuHash) 3770b57cec5SDimitry Andric error("the .gnu.hash section is not compatible with the MIPS target"); 3780b57cec5SDimitry Andric 37906c3fb27SDimitry Andric if (config->emachine == EM_ARM) { 38006c3fb27SDimitry Andric if (!config->cmseImplib) { 38106c3fb27SDimitry Andric if (!config->cmseInputLib.empty()) 38206c3fb27SDimitry Andric error("--in-implib may not be used without --cmse-implib"); 38306c3fb27SDimitry Andric if (!config->cmseOutputLib.empty()) 38406c3fb27SDimitry Andric error("--out-implib may not be used without --cmse-implib"); 38506c3fb27SDimitry Andric } 38606c3fb27SDimitry Andric } else { 38706c3fb27SDimitry Andric if (config->cmseImplib) 38806c3fb27SDimitry Andric error("--cmse-implib is only supported on ARM targets"); 38906c3fb27SDimitry Andric if (!config->cmseInputLib.empty()) 39006c3fb27SDimitry Andric error("--in-implib is only supported on ARM targets"); 39106c3fb27SDimitry Andric if (!config->cmseOutputLib.empty()) 39206c3fb27SDimitry Andric error("--out-implib is only supported on ARM targets"); 39306c3fb27SDimitry Andric } 39406c3fb27SDimitry Andric 3950b57cec5SDimitry Andric if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64) 3960b57cec5SDimitry Andric error("--fix-cortex-a53-843419 is only supported on AArch64 targets"); 3970b57cec5SDimitry Andric 39885868e8aSDimitry Andric if (config->fixCortexA8 && config->emachine != EM_ARM) 39985868e8aSDimitry Andric error("--fix-cortex-a8 is only supported on ARM targets"); 40085868e8aSDimitry Andric 40106c3fb27SDimitry Andric if (config->armBe8 && config->emachine != EM_ARM) 40206c3fb27SDimitry Andric error("--be8 is only supported on ARM targets"); 40306c3fb27SDimitry Andric 40406c3fb27SDimitry Andric if (config->fixCortexA8 && !config->isLE) 40506c3fb27SDimitry Andric error("--fix-cortex-a8 is not supported on big endian targets"); 40606c3fb27SDimitry Andric 4070b57cec5SDimitry Andric if (config->tocOptimize && config->emachine != EM_PPC64) 408e8d8bef9SDimitry Andric error("--toc-optimize is only supported on PowerPC64 targets"); 409e8d8bef9SDimitry Andric 410e8d8bef9SDimitry Andric if (config->pcRelOptimize && config->emachine != EM_PPC64) 411e8d8bef9SDimitry Andric error("--pcrel-optimize is only supported on PowerPC64 targets"); 4120b57cec5SDimitry Andric 41306c3fb27SDimitry Andric if (config->relaxGP && config->emachine != EM_RISCV) 41406c3fb27SDimitry Andric error("--relax-gp is only supported on RISC-V targets"); 41506c3fb27SDimitry Andric 4160b57cec5SDimitry Andric if (config->pie && config->shared) 4170b57cec5SDimitry Andric error("-shared and -pie may not be used together"); 4180b57cec5SDimitry Andric 4190b57cec5SDimitry Andric if (!config->shared && !config->filterList.empty()) 4200b57cec5SDimitry Andric error("-F may not be used without -shared"); 4210b57cec5SDimitry Andric 4220b57cec5SDimitry Andric if (!config->shared && !config->auxiliaryList.empty()) 4230b57cec5SDimitry Andric error("-f may not be used without -shared"); 4240b57cec5SDimitry Andric 42585868e8aSDimitry Andric if (config->strip == StripPolicy::All && config->emitRelocs) 42685868e8aSDimitry Andric error("--strip-all and --emit-relocs may not be used together"); 42785868e8aSDimitry Andric 4280b57cec5SDimitry Andric if (config->zText && config->zIfuncNoplt) 4290b57cec5SDimitry Andric error("-z text and -z ifunc-noplt may not be used together"); 4300b57cec5SDimitry Andric 4310b57cec5SDimitry Andric if (config->relocatable) { 4320b57cec5SDimitry Andric if (config->shared) 4330b57cec5SDimitry Andric error("-r and -shared may not be used together"); 4340b57cec5SDimitry Andric if (config->gdbIndex) 4350b57cec5SDimitry Andric error("-r and --gdb-index may not be used together"); 4360b57cec5SDimitry Andric if (config->icf != ICFLevel::None) 4370b57cec5SDimitry Andric error("-r and --icf may not be used together"); 4380b57cec5SDimitry Andric if (config->pie) 4390b57cec5SDimitry Andric error("-r and -pie may not be used together"); 44085868e8aSDimitry Andric if (config->exportDynamic) 44185868e8aSDimitry Andric error("-r and --export-dynamic may not be used together"); 4420b57cec5SDimitry Andric } 4430b57cec5SDimitry Andric 4440b57cec5SDimitry Andric if (config->executeOnly) { 4450b57cec5SDimitry Andric if (config->emachine != EM_AARCH64) 446349cc55cSDimitry Andric error("--execute-only is only supported on AArch64 targets"); 4470b57cec5SDimitry Andric 4480b57cec5SDimitry Andric if (config->singleRoRx && !script->hasSectionsCommand) 449349cc55cSDimitry Andric error("--execute-only and --no-rosegment cannot be used together"); 4500b57cec5SDimitry Andric } 4510b57cec5SDimitry Andric 452480093f4SDimitry Andric if (config->zRetpolineplt && config->zForceIbt) 453480093f4SDimitry Andric error("-z force-ibt may not be used with -z retpolineplt"); 4540b57cec5SDimitry Andric 4550b57cec5SDimitry Andric if (config->emachine != EM_AARCH64) { 4565ffd83dbSDimitry Andric if (config->zPacPlt) 457480093f4SDimitry Andric error("-z pac-plt only supported on AArch64"); 4585ffd83dbSDimitry Andric if (config->zForceBti) 459480093f4SDimitry Andric error("-z force-bti only supported on AArch64"); 4600eae32dcSDimitry Andric if (config->zBtiReport != "none") 4610eae32dcSDimitry Andric error("-z bti-report only supported on AArch64"); 4620b57cec5SDimitry Andric } 4630eae32dcSDimitry Andric 4640eae32dcSDimitry Andric if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 4650eae32dcSDimitry Andric config->zCetReport != "none") 4660eae32dcSDimitry Andric error("-z cet-report only supported on X86 and X86_64"); 4670b57cec5SDimitry Andric } 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric static const char *getReproduceOption(opt::InputArgList &args) { 4700b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 4710b57cec5SDimitry Andric return arg->getValue(); 4720b57cec5SDimitry Andric return getenv("LLD_REPRODUCE"); 4730b57cec5SDimitry Andric } 4740b57cec5SDimitry Andric 4750b57cec5SDimitry Andric static bool hasZOption(opt::InputArgList &args, StringRef key) { 4760b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_z)) 4770b57cec5SDimitry Andric if (key == arg->getValue()) 4780b57cec5SDimitry Andric return true; 4790b57cec5SDimitry Andric return false; 4800b57cec5SDimitry Andric } 4810b57cec5SDimitry Andric 4820b57cec5SDimitry Andric static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2, 4830b57cec5SDimitry Andric bool Default) { 4840b57cec5SDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 4850b57cec5SDimitry Andric if (k1 == arg->getValue()) 4860b57cec5SDimitry Andric return true; 4870b57cec5SDimitry Andric if (k2 == arg->getValue()) 4880b57cec5SDimitry Andric return false; 4890b57cec5SDimitry Andric } 4900b57cec5SDimitry Andric return Default; 4910b57cec5SDimitry Andric } 4920b57cec5SDimitry Andric 49385868e8aSDimitry Andric static SeparateSegmentKind getZSeparate(opt::InputArgList &args) { 49485868e8aSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 49585868e8aSDimitry Andric StringRef v = arg->getValue(); 49685868e8aSDimitry Andric if (v == "noseparate-code") 49785868e8aSDimitry Andric return SeparateSegmentKind::None; 49885868e8aSDimitry Andric if (v == "separate-code") 49985868e8aSDimitry Andric return SeparateSegmentKind::Code; 50085868e8aSDimitry Andric if (v == "separate-loadable-segments") 50185868e8aSDimitry Andric return SeparateSegmentKind::Loadable; 50285868e8aSDimitry Andric } 50385868e8aSDimitry Andric return SeparateSegmentKind::None; 50485868e8aSDimitry Andric } 50585868e8aSDimitry Andric 506480093f4SDimitry Andric static GnuStackKind getZGnuStack(opt::InputArgList &args) { 507480093f4SDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 508480093f4SDimitry Andric if (StringRef("execstack") == arg->getValue()) 509480093f4SDimitry Andric return GnuStackKind::Exec; 510480093f4SDimitry Andric if (StringRef("noexecstack") == arg->getValue()) 511480093f4SDimitry Andric return GnuStackKind::NoExec; 512480093f4SDimitry Andric if (StringRef("nognustack") == arg->getValue()) 513480093f4SDimitry Andric return GnuStackKind::None; 514480093f4SDimitry Andric } 515480093f4SDimitry Andric 516480093f4SDimitry Andric return GnuStackKind::NoExec; 517480093f4SDimitry Andric } 518480093f4SDimitry Andric 5195ffd83dbSDimitry Andric static uint8_t getZStartStopVisibility(opt::InputArgList &args) { 5205ffd83dbSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 5215ffd83dbSDimitry Andric std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 5225ffd83dbSDimitry Andric if (kv.first == "start-stop-visibility") { 5235ffd83dbSDimitry Andric if (kv.second == "default") 5245ffd83dbSDimitry Andric return STV_DEFAULT; 5255ffd83dbSDimitry Andric else if (kv.second == "internal") 5265ffd83dbSDimitry Andric return STV_INTERNAL; 5275ffd83dbSDimitry Andric else if (kv.second == "hidden") 5285ffd83dbSDimitry Andric return STV_HIDDEN; 5295ffd83dbSDimitry Andric else if (kv.second == "protected") 5305ffd83dbSDimitry Andric return STV_PROTECTED; 5315ffd83dbSDimitry Andric error("unknown -z start-stop-visibility= value: " + StringRef(kv.second)); 5325ffd83dbSDimitry Andric } 5335ffd83dbSDimitry Andric } 5345ffd83dbSDimitry Andric return STV_PROTECTED; 5355ffd83dbSDimitry Andric } 5365ffd83dbSDimitry Andric 53781ad6265SDimitry Andric constexpr const char *knownZFlags[] = { 53881ad6265SDimitry Andric "combreloc", 53981ad6265SDimitry Andric "copyreloc", 54081ad6265SDimitry Andric "defs", 54181ad6265SDimitry Andric "execstack", 54281ad6265SDimitry Andric "force-bti", 54381ad6265SDimitry Andric "force-ibt", 54481ad6265SDimitry Andric "global", 54581ad6265SDimitry Andric "hazardplt", 54681ad6265SDimitry Andric "ifunc-noplt", 54781ad6265SDimitry Andric "initfirst", 54881ad6265SDimitry Andric "interpose", 54981ad6265SDimitry Andric "keep-text-section-prefix", 55081ad6265SDimitry Andric "lazy", 55181ad6265SDimitry Andric "muldefs", 55281ad6265SDimitry Andric "nocombreloc", 55381ad6265SDimitry Andric "nocopyreloc", 55481ad6265SDimitry Andric "nodefaultlib", 55581ad6265SDimitry Andric "nodelete", 55681ad6265SDimitry Andric "nodlopen", 55781ad6265SDimitry Andric "noexecstack", 55881ad6265SDimitry Andric "nognustack", 55981ad6265SDimitry Andric "nokeep-text-section-prefix", 56081ad6265SDimitry Andric "nopack-relative-relocs", 56181ad6265SDimitry Andric "norelro", 56281ad6265SDimitry Andric "noseparate-code", 56381ad6265SDimitry Andric "nostart-stop-gc", 56481ad6265SDimitry Andric "notext", 56581ad6265SDimitry Andric "now", 56681ad6265SDimitry Andric "origin", 56781ad6265SDimitry Andric "pac-plt", 56881ad6265SDimitry Andric "pack-relative-relocs", 56981ad6265SDimitry Andric "rel", 57081ad6265SDimitry Andric "rela", 57181ad6265SDimitry Andric "relro", 57281ad6265SDimitry Andric "retpolineplt", 57381ad6265SDimitry Andric "rodynamic", 57481ad6265SDimitry Andric "separate-code", 57581ad6265SDimitry Andric "separate-loadable-segments", 57681ad6265SDimitry Andric "shstk", 57781ad6265SDimitry Andric "start-stop-gc", 57881ad6265SDimitry Andric "text", 57981ad6265SDimitry Andric "undefs", 58081ad6265SDimitry Andric "wxneeded", 58181ad6265SDimitry Andric }; 58281ad6265SDimitry Andric 5830b57cec5SDimitry Andric static bool isKnownZFlag(StringRef s) { 58481ad6265SDimitry Andric return llvm::is_contained(knownZFlags, s) || 58506c3fb27SDimitry Andric s.starts_with("common-page-size=") || s.starts_with("bti-report=") || 58606c3fb27SDimitry Andric s.starts_with("cet-report=") || 58706c3fb27SDimitry Andric s.starts_with("dead-reloc-in-nonalloc=") || 58806c3fb27SDimitry Andric s.starts_with("max-page-size=") || s.starts_with("stack-size=") || 58906c3fb27SDimitry Andric s.starts_with("start-stop-visibility="); 5900b57cec5SDimitry Andric } 5910b57cec5SDimitry Andric 5924824e7fdSDimitry Andric // Report a warning for an unknown -z option. 5930b57cec5SDimitry Andric static void checkZOptions(opt::InputArgList &args) { 5940b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_z)) 5950b57cec5SDimitry Andric if (!isKnownZFlag(arg->getValue())) 5964824e7fdSDimitry Andric warn("unknown -z value: " + StringRef(arg->getValue())); 5970b57cec5SDimitry Andric } 5980b57cec5SDimitry Andric 599753f127fSDimitry Andric constexpr const char *saveTempsValues[] = { 600753f127fSDimitry Andric "resolution", "preopt", "promote", "internalize", "import", 601753f127fSDimitry Andric "opt", "precodegen", "prelink", "combinedindex"}; 602753f127fSDimitry Andric 603e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 6040b57cec5SDimitry Andric ELFOptTable parser; 6050b57cec5SDimitry Andric opt::InputArgList args = parser.parse(argsArr.slice(1)); 6060b57cec5SDimitry Andric 60781ad6265SDimitry Andric // Interpret these flags early because error()/warn() depend on them. 6080b57cec5SDimitry Andric errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20); 6094824e7fdSDimitry Andric errorHandler().fatalWarnings = 610bdd1243dSDimitry Andric args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) && 611bdd1243dSDimitry Andric !args.hasArg(OPT_no_warnings); 612bdd1243dSDimitry Andric errorHandler().suppressWarnings = args.hasArg(OPT_no_warnings); 6130b57cec5SDimitry Andric checkZOptions(args); 6140b57cec5SDimitry Andric 6150b57cec5SDimitry Andric // Handle -help 6160b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 6170b57cec5SDimitry Andric printHelp(); 6180b57cec5SDimitry Andric return; 6190b57cec5SDimitry Andric } 6200b57cec5SDimitry Andric 6210b57cec5SDimitry Andric // Handle -v or -version. 6220b57cec5SDimitry Andric // 6230b57cec5SDimitry Andric // A note about "compatible with GNU linkers" message: this is a hack for 624349cc55cSDimitry Andric // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as 625349cc55cSDimitry Andric // a GNU compatible linker. See 626349cc55cSDimitry Andric // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>. 6270b57cec5SDimitry Andric // 6280b57cec5SDimitry Andric // This is somewhat ugly hack, but in reality, we had no choice other 6290b57cec5SDimitry Andric // than doing this. Considering the very long release cycle of Libtool, 6300b57cec5SDimitry Andric // it is not easy to improve it to recognize LLD as a GNU compatible 6310b57cec5SDimitry Andric // linker in a timely manner. Even if we can make it, there are still a 6320b57cec5SDimitry Andric // lot of "configure" scripts out there that are generated by old version 6330b57cec5SDimitry Andric // of Libtool. We cannot convince every software developer to migrate to 6340b57cec5SDimitry Andric // the latest version and re-generate scripts. So we have this hack. 6350b57cec5SDimitry Andric if (args.hasArg(OPT_v) || args.hasArg(OPT_version)) 6360b57cec5SDimitry Andric message(getLLDVersion() + " (compatible with GNU linkers)"); 6370b57cec5SDimitry Andric 6380b57cec5SDimitry Andric if (const char *path = getReproduceOption(args)) { 6390b57cec5SDimitry Andric // Note that --reproduce is a debug option so you can ignore it 6400b57cec5SDimitry Andric // if you are trying to understand the whole picture of the code. 6410b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 6420b57cec5SDimitry Andric TarWriter::create(path, path::stem(path)); 6430b57cec5SDimitry Andric if (errOrWriter) { 6440b57cec5SDimitry Andric tar = std::move(*errOrWriter); 6450b57cec5SDimitry Andric tar->append("response.txt", createResponseFile(args)); 6460b57cec5SDimitry Andric tar->append("version.txt", getLLDVersion() + "\n"); 647e8d8bef9SDimitry Andric StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 648e8d8bef9SDimitry Andric if (!ltoSampleProfile.empty()) 649e8d8bef9SDimitry Andric readFile(ltoSampleProfile); 6500b57cec5SDimitry Andric } else { 6510b57cec5SDimitry Andric error("--reproduce: " + toString(errOrWriter.takeError())); 6520b57cec5SDimitry Andric } 6530b57cec5SDimitry Andric } 6540b57cec5SDimitry Andric 6550b57cec5SDimitry Andric readConfigs(args); 6560b57cec5SDimitry Andric 6570b57cec5SDimitry Andric // The behavior of -v or --version is a bit strange, but this is 6580b57cec5SDimitry Andric // needed for compatibility with GNU linkers. 6590b57cec5SDimitry Andric if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT)) 6600b57cec5SDimitry Andric return; 6610b57cec5SDimitry Andric if (args.hasArg(OPT_version)) 6620b57cec5SDimitry Andric return; 6630b57cec5SDimitry Andric 6645ffd83dbSDimitry Andric // Initialize time trace profiler. 6655ffd83dbSDimitry Andric if (config->timeTraceEnabled) 6665ffd83dbSDimitry Andric timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName); 6675ffd83dbSDimitry Andric 6685ffd83dbSDimitry Andric { 6695ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("ExecuteLinker"); 6705ffd83dbSDimitry Andric 6710b57cec5SDimitry Andric initLLVM(); 6720b57cec5SDimitry Andric createFiles(args); 6730b57cec5SDimitry Andric if (errorCount()) 6740b57cec5SDimitry Andric return; 6750b57cec5SDimitry Andric 6760b57cec5SDimitry Andric inferMachineType(); 6770b57cec5SDimitry Andric setConfigs(args); 6780b57cec5SDimitry Andric checkOptions(); 6790b57cec5SDimitry Andric if (errorCount()) 6800b57cec5SDimitry Andric return; 6810b57cec5SDimitry Andric 6821fd87a68SDimitry Andric link(args); 6830b57cec5SDimitry Andric } 6840b57cec5SDimitry Andric 6855ffd83dbSDimitry Andric if (config->timeTraceEnabled) { 686349cc55cSDimitry Andric checkError(timeTraceProfilerWrite( 68781ad6265SDimitry Andric args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile)); 6885ffd83dbSDimitry Andric timeTraceProfilerCleanup(); 6895ffd83dbSDimitry Andric } 6905ffd83dbSDimitry Andric } 6915ffd83dbSDimitry Andric 6920b57cec5SDimitry Andric static std::string getRpath(opt::InputArgList &args) { 693bdd1243dSDimitry Andric SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath); 6940b57cec5SDimitry Andric return llvm::join(v.begin(), v.end(), ":"); 6950b57cec5SDimitry Andric } 6960b57cec5SDimitry Andric 6970b57cec5SDimitry Andric // Determines what we should do if there are remaining unresolved 6980b57cec5SDimitry Andric // symbols after the name resolution. 699e8d8bef9SDimitry Andric static void setUnresolvedSymbolPolicy(opt::InputArgList &args) { 7000b57cec5SDimitry Andric UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols, 7010b57cec5SDimitry Andric OPT_warn_unresolved_symbols, true) 7020b57cec5SDimitry Andric ? UnresolvedPolicy::ReportError 7030b57cec5SDimitry Andric : UnresolvedPolicy::Warn; 704349cc55cSDimitry Andric // -shared implies --unresolved-symbols=ignore-all because missing 705e8d8bef9SDimitry Andric // symbols are likely to be resolved at runtime. 706e8d8bef9SDimitry Andric bool diagRegular = !config->shared, diagShlib = !config->shared; 7070b57cec5SDimitry Andric 708e8d8bef9SDimitry Andric for (const opt::Arg *arg : args) { 7090b57cec5SDimitry Andric switch (arg->getOption().getID()) { 7100b57cec5SDimitry Andric case OPT_unresolved_symbols: { 7110b57cec5SDimitry Andric StringRef s = arg->getValue(); 712e8d8bef9SDimitry Andric if (s == "ignore-all") { 713e8d8bef9SDimitry Andric diagRegular = false; 714e8d8bef9SDimitry Andric diagShlib = false; 715e8d8bef9SDimitry Andric } else if (s == "ignore-in-object-files") { 716e8d8bef9SDimitry Andric diagRegular = false; 717e8d8bef9SDimitry Andric diagShlib = true; 718e8d8bef9SDimitry Andric } else if (s == "ignore-in-shared-libs") { 719e8d8bef9SDimitry Andric diagRegular = true; 720e8d8bef9SDimitry Andric diagShlib = false; 721e8d8bef9SDimitry Andric } else if (s == "report-all") { 722e8d8bef9SDimitry Andric diagRegular = true; 723e8d8bef9SDimitry Andric diagShlib = true; 724e8d8bef9SDimitry Andric } else { 7250b57cec5SDimitry Andric error("unknown --unresolved-symbols value: " + s); 726e8d8bef9SDimitry Andric } 727e8d8bef9SDimitry Andric break; 7280b57cec5SDimitry Andric } 7290b57cec5SDimitry Andric case OPT_no_undefined: 730e8d8bef9SDimitry Andric diagRegular = true; 731e8d8bef9SDimitry Andric break; 7320b57cec5SDimitry Andric case OPT_z: 7330b57cec5SDimitry Andric if (StringRef(arg->getValue()) == "defs") 734e8d8bef9SDimitry Andric diagRegular = true; 735e8d8bef9SDimitry Andric else if (StringRef(arg->getValue()) == "undefs") 736e8d8bef9SDimitry Andric diagRegular = false; 737e8d8bef9SDimitry Andric break; 738e8d8bef9SDimitry Andric case OPT_allow_shlib_undefined: 739e8d8bef9SDimitry Andric diagShlib = false; 740e8d8bef9SDimitry Andric break; 741e8d8bef9SDimitry Andric case OPT_no_allow_shlib_undefined: 742e8d8bef9SDimitry Andric diagShlib = true; 743e8d8bef9SDimitry Andric break; 7440b57cec5SDimitry Andric } 7450b57cec5SDimitry Andric } 7460b57cec5SDimitry Andric 747e8d8bef9SDimitry Andric config->unresolvedSymbols = 748e8d8bef9SDimitry Andric diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore; 749e8d8bef9SDimitry Andric config->unresolvedSymbolsInShlib = 750e8d8bef9SDimitry Andric diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore; 7510b57cec5SDimitry Andric } 7520b57cec5SDimitry Andric 7530b57cec5SDimitry Andric static Target2Policy getTarget2(opt::InputArgList &args) { 7540b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_target2, "got-rel"); 7550b57cec5SDimitry Andric if (s == "rel") 7560b57cec5SDimitry Andric return Target2Policy::Rel; 7570b57cec5SDimitry Andric if (s == "abs") 7580b57cec5SDimitry Andric return Target2Policy::Abs; 7590b57cec5SDimitry Andric if (s == "got-rel") 7600b57cec5SDimitry Andric return Target2Policy::GotRel; 7610b57cec5SDimitry Andric error("unknown --target2 option: " + s); 7620b57cec5SDimitry Andric return Target2Policy::GotRel; 7630b57cec5SDimitry Andric } 7640b57cec5SDimitry Andric 7650b57cec5SDimitry Andric static bool isOutputFormatBinary(opt::InputArgList &args) { 7660b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_oformat, "elf"); 7670b57cec5SDimitry Andric if (s == "binary") 7680b57cec5SDimitry Andric return true; 76906c3fb27SDimitry Andric if (!s.starts_with("elf")) 7700b57cec5SDimitry Andric error("unknown --oformat value: " + s); 7710b57cec5SDimitry Andric return false; 7720b57cec5SDimitry Andric } 7730b57cec5SDimitry Andric 7740b57cec5SDimitry Andric static DiscardPolicy getDiscard(opt::InputArgList &args) { 7750b57cec5SDimitry Andric auto *arg = 7760b57cec5SDimitry Andric args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 7770b57cec5SDimitry Andric if (!arg) 7780b57cec5SDimitry Andric return DiscardPolicy::Default; 7790b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_discard_all) 7800b57cec5SDimitry Andric return DiscardPolicy::All; 7810b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_discard_locals) 7820b57cec5SDimitry Andric return DiscardPolicy::Locals; 7830b57cec5SDimitry Andric return DiscardPolicy::None; 7840b57cec5SDimitry Andric } 7850b57cec5SDimitry Andric 7860b57cec5SDimitry Andric static StringRef getDynamicLinker(opt::InputArgList &args) { 7870b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 78855e4f9d5SDimitry Andric if (!arg) 7890b57cec5SDimitry Andric return ""; 79055e4f9d5SDimitry Andric if (arg->getOption().getID() == OPT_no_dynamic_linker) { 79155e4f9d5SDimitry Andric // --no-dynamic-linker suppresses undefined weak symbols in .dynsym 79255e4f9d5SDimitry Andric config->noDynamicLinker = true; 79355e4f9d5SDimitry Andric return ""; 79455e4f9d5SDimitry Andric } 7950b57cec5SDimitry Andric return arg->getValue(); 7960b57cec5SDimitry Andric } 7970b57cec5SDimitry Andric 79881ad6265SDimitry Andric static int getMemtagMode(opt::InputArgList &args) { 79981ad6265SDimitry Andric StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode); 80006c3fb27SDimitry Andric if (memtagModeArg.empty()) { 80106c3fb27SDimitry Andric if (config->androidMemtagStack) 80206c3fb27SDimitry Andric warn("--android-memtag-mode is unspecified, leaving " 80306c3fb27SDimitry Andric "--android-memtag-stack a no-op"); 80406c3fb27SDimitry Andric else if (config->androidMemtagHeap) 80506c3fb27SDimitry Andric warn("--android-memtag-mode is unspecified, leaving " 80606c3fb27SDimitry Andric "--android-memtag-heap a no-op"); 80706c3fb27SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 80806c3fb27SDimitry Andric } 80906c3fb27SDimitry Andric 81006c3fb27SDimitry Andric if (memtagModeArg == "sync") 81181ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_SYNC; 81281ad6265SDimitry Andric if (memtagModeArg == "async") 81381ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_ASYNC; 81481ad6265SDimitry Andric if (memtagModeArg == "none") 81581ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 81681ad6265SDimitry Andric 81781ad6265SDimitry Andric error("unknown --android-memtag-mode value: \"" + memtagModeArg + 81881ad6265SDimitry Andric "\", should be one of {async, sync, none}"); 81981ad6265SDimitry Andric return ELF::NT_MEMTAG_LEVEL_NONE; 82081ad6265SDimitry Andric } 82181ad6265SDimitry Andric 8220b57cec5SDimitry Andric static ICFLevel getICF(opt::InputArgList &args) { 8230b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all); 8240b57cec5SDimitry Andric if (!arg || arg->getOption().getID() == OPT_icf_none) 8250b57cec5SDimitry Andric return ICFLevel::None; 8260b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_icf_safe) 8270b57cec5SDimitry Andric return ICFLevel::Safe; 8280b57cec5SDimitry Andric return ICFLevel::All; 8290b57cec5SDimitry Andric } 8300b57cec5SDimitry Andric 8310b57cec5SDimitry Andric static StripPolicy getStrip(opt::InputArgList &args) { 8320b57cec5SDimitry Andric if (args.hasArg(OPT_relocatable)) 8330b57cec5SDimitry Andric return StripPolicy::None; 8340b57cec5SDimitry Andric 8350b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug); 8360b57cec5SDimitry Andric if (!arg) 8370b57cec5SDimitry Andric return StripPolicy::None; 8380b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_strip_all) 8390b57cec5SDimitry Andric return StripPolicy::All; 8400b57cec5SDimitry Andric return StripPolicy::Debug; 8410b57cec5SDimitry Andric } 8420b57cec5SDimitry Andric 8430b57cec5SDimitry Andric static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args, 8440b57cec5SDimitry Andric const opt::Arg &arg) { 8450b57cec5SDimitry Andric uint64_t va = 0; 84606c3fb27SDimitry Andric if (s.starts_with("0x")) 8470b57cec5SDimitry Andric s = s.drop_front(2); 8480b57cec5SDimitry Andric if (!to_integer(s, va, 16)) 8490b57cec5SDimitry Andric error("invalid argument: " + arg.getAsString(args)); 8500b57cec5SDimitry Andric return va; 8510b57cec5SDimitry Andric } 8520b57cec5SDimitry Andric 8530b57cec5SDimitry Andric static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) { 8540b57cec5SDimitry Andric StringMap<uint64_t> ret; 8550b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section_start)) { 8560b57cec5SDimitry Andric StringRef name; 8570b57cec5SDimitry Andric StringRef addr; 8580b57cec5SDimitry Andric std::tie(name, addr) = StringRef(arg->getValue()).split('='); 8590b57cec5SDimitry Andric ret[name] = parseSectionAddress(addr, args, *arg); 8600b57cec5SDimitry Andric } 8610b57cec5SDimitry Andric 8620b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Ttext)) 8630b57cec5SDimitry Andric ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg); 8640b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Tdata)) 8650b57cec5SDimitry Andric ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg); 8660b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_Tbss)) 8670b57cec5SDimitry Andric ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg); 8680b57cec5SDimitry Andric return ret; 8690b57cec5SDimitry Andric } 8700b57cec5SDimitry Andric 8710b57cec5SDimitry Andric static SortSectionPolicy getSortSection(opt::InputArgList &args) { 8720b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_sort_section); 8730b57cec5SDimitry Andric if (s == "alignment") 8740b57cec5SDimitry Andric return SortSectionPolicy::Alignment; 8750b57cec5SDimitry Andric if (s == "name") 8760b57cec5SDimitry Andric return SortSectionPolicy::Name; 8770b57cec5SDimitry Andric if (!s.empty()) 8780b57cec5SDimitry Andric error("unknown --sort-section rule: " + s); 8790b57cec5SDimitry Andric return SortSectionPolicy::Default; 8800b57cec5SDimitry Andric } 8810b57cec5SDimitry Andric 8820b57cec5SDimitry Andric static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) { 8830b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_orphan_handling, "place"); 8840b57cec5SDimitry Andric if (s == "warn") 8850b57cec5SDimitry Andric return OrphanHandlingPolicy::Warn; 8860b57cec5SDimitry Andric if (s == "error") 8870b57cec5SDimitry Andric return OrphanHandlingPolicy::Error; 8880b57cec5SDimitry Andric if (s != "place") 8890b57cec5SDimitry Andric error("unknown --orphan-handling mode: " + s); 8900b57cec5SDimitry Andric return OrphanHandlingPolicy::Place; 8910b57cec5SDimitry Andric } 8920b57cec5SDimitry Andric 8930b57cec5SDimitry Andric // Parse --build-id or --build-id=<style>. We handle "tree" as a 8940b57cec5SDimitry Andric // synonym for "sha1" because all our hash functions including 895349cc55cSDimitry Andric // --build-id=sha1 are actually tree hashes for performance reasons. 896bdd1243dSDimitry Andric static std::pair<BuildIdKind, SmallVector<uint8_t, 0>> 8970b57cec5SDimitry Andric getBuildId(opt::InputArgList &args) { 898972a253aSDimitry Andric auto *arg = args.getLastArg(OPT_build_id); 8990b57cec5SDimitry Andric if (!arg) 9000b57cec5SDimitry Andric return {BuildIdKind::None, {}}; 9010b57cec5SDimitry Andric 9020b57cec5SDimitry Andric StringRef s = arg->getValue(); 9030b57cec5SDimitry Andric if (s == "fast") 9040b57cec5SDimitry Andric return {BuildIdKind::Fast, {}}; 9050b57cec5SDimitry Andric if (s == "md5") 9060b57cec5SDimitry Andric return {BuildIdKind::Md5, {}}; 9070b57cec5SDimitry Andric if (s == "sha1" || s == "tree") 9080b57cec5SDimitry Andric return {BuildIdKind::Sha1, {}}; 9090b57cec5SDimitry Andric if (s == "uuid") 9100b57cec5SDimitry Andric return {BuildIdKind::Uuid, {}}; 91106c3fb27SDimitry Andric if (s.starts_with("0x")) 9120b57cec5SDimitry Andric return {BuildIdKind::Hexstring, parseHex(s.substr(2))}; 9130b57cec5SDimitry Andric 9140b57cec5SDimitry Andric if (s != "none") 9150b57cec5SDimitry Andric error("unknown --build-id style: " + s); 9160b57cec5SDimitry Andric return {BuildIdKind::None, {}}; 9170b57cec5SDimitry Andric } 9180b57cec5SDimitry Andric 9190b57cec5SDimitry Andric static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) { 9200b57cec5SDimitry Andric StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none"); 9210b57cec5SDimitry Andric if (s == "android") 9220b57cec5SDimitry Andric return {true, false}; 9230b57cec5SDimitry Andric if (s == "relr") 9240b57cec5SDimitry Andric return {false, true}; 9250b57cec5SDimitry Andric if (s == "android+relr") 9260b57cec5SDimitry Andric return {true, true}; 9270b57cec5SDimitry Andric 9280b57cec5SDimitry Andric if (s != "none") 929349cc55cSDimitry Andric error("unknown --pack-dyn-relocs format: " + s); 9300b57cec5SDimitry Andric return {false, false}; 9310b57cec5SDimitry Andric } 9320b57cec5SDimitry Andric 9330b57cec5SDimitry Andric static void readCallGraph(MemoryBufferRef mb) { 9340b57cec5SDimitry Andric // Build a map from symbol name to section 9350b57cec5SDimitry Andric DenseMap<StringRef, Symbol *> map; 936bdd1243dSDimitry Andric for (ELFFileBase *file : ctx.objectFiles) 9370b57cec5SDimitry Andric for (Symbol *sym : file->getSymbols()) 9380b57cec5SDimitry Andric map[sym->getName()] = sym; 9390b57cec5SDimitry Andric 9400b57cec5SDimitry Andric auto findSection = [&](StringRef name) -> InputSectionBase * { 9410b57cec5SDimitry Andric Symbol *sym = map.lookup(name); 9420b57cec5SDimitry Andric if (!sym) { 9430b57cec5SDimitry Andric if (config->warnSymbolOrdering) 9440b57cec5SDimitry Andric warn(mb.getBufferIdentifier() + ": no such symbol: " + name); 9450b57cec5SDimitry Andric return nullptr; 9460b57cec5SDimitry Andric } 9470b57cec5SDimitry Andric maybeWarnUnorderableSymbol(sym); 9480b57cec5SDimitry Andric 9490b57cec5SDimitry Andric if (Defined *dr = dyn_cast_or_null<Defined>(sym)) 9500b57cec5SDimitry Andric return dyn_cast_or_null<InputSectionBase>(dr->section); 9510b57cec5SDimitry Andric return nullptr; 9520b57cec5SDimitry Andric }; 9530b57cec5SDimitry Andric 9540b57cec5SDimitry Andric for (StringRef line : args::getLines(mb)) { 9550b57cec5SDimitry Andric SmallVector<StringRef, 3> fields; 9560b57cec5SDimitry Andric line.split(fields, ' '); 9570b57cec5SDimitry Andric uint64_t count; 9580b57cec5SDimitry Andric 9590b57cec5SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 9600b57cec5SDimitry Andric error(mb.getBufferIdentifier() + ": parse error"); 9610b57cec5SDimitry Andric return; 9620b57cec5SDimitry Andric } 9630b57cec5SDimitry Andric 9640b57cec5SDimitry Andric if (InputSectionBase *from = findSection(fields[0])) 9650b57cec5SDimitry Andric if (InputSectionBase *to = findSection(fields[1])) 9660b57cec5SDimitry Andric config->callGraphProfile[std::make_pair(from, to)] += count; 9670b57cec5SDimitry Andric } 9680b57cec5SDimitry Andric } 9690b57cec5SDimitry Andric 970fe6060f1SDimitry Andric // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns 971fe6060f1SDimitry Andric // true and populates cgProfile and symbolIndices. 972fe6060f1SDimitry Andric template <class ELFT> 973fe6060f1SDimitry Andric static bool 974fe6060f1SDimitry Andric processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices, 975fe6060f1SDimitry Andric ArrayRef<typename ELFT::CGProfile> &cgProfile, 976fe6060f1SDimitry Andric ObjFile<ELFT> *inputObj) { 977fe6060f1SDimitry Andric if (inputObj->cgProfileSectionIndex == SHN_UNDEF) 978fe6060f1SDimitry Andric return false; 979fe6060f1SDimitry Andric 9800eae32dcSDimitry Andric ArrayRef<Elf_Shdr_Impl<ELFT>> objSections = 9810eae32dcSDimitry Andric inputObj->template getELFShdrs<ELFT>(); 9820eae32dcSDimitry Andric symbolIndices.clear(); 9830eae32dcSDimitry Andric const ELFFile<ELFT> &obj = inputObj->getObj(); 984fe6060f1SDimitry Andric cgProfile = 985fe6060f1SDimitry Andric check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>( 986fe6060f1SDimitry Andric objSections[inputObj->cgProfileSectionIndex])); 987fe6060f1SDimitry Andric 988fe6060f1SDimitry Andric for (size_t i = 0, e = objSections.size(); i < e; ++i) { 989fe6060f1SDimitry Andric const Elf_Shdr_Impl<ELFT> &sec = objSections[i]; 990fe6060f1SDimitry Andric if (sec.sh_info == inputObj->cgProfileSectionIndex) { 991fe6060f1SDimitry Andric if (sec.sh_type == SHT_RELA) { 992fe6060f1SDimitry Andric ArrayRef<typename ELFT::Rela> relas = 993fe6060f1SDimitry Andric CHECK(obj.relas(sec), "could not retrieve cg profile rela section"); 994fe6060f1SDimitry Andric for (const typename ELFT::Rela &rel : relas) 995fe6060f1SDimitry Andric symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 996fe6060f1SDimitry Andric break; 997fe6060f1SDimitry Andric } 998fe6060f1SDimitry Andric if (sec.sh_type == SHT_REL) { 999fe6060f1SDimitry Andric ArrayRef<typename ELFT::Rel> rels = 1000fe6060f1SDimitry Andric CHECK(obj.rels(sec), "could not retrieve cg profile rel section"); 1001fe6060f1SDimitry Andric for (const typename ELFT::Rel &rel : rels) 1002fe6060f1SDimitry Andric symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 1003fe6060f1SDimitry Andric break; 1004fe6060f1SDimitry Andric } 1005fe6060f1SDimitry Andric } 1006fe6060f1SDimitry Andric } 1007fe6060f1SDimitry Andric if (symbolIndices.empty()) 1008fe6060f1SDimitry Andric warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't"); 1009fe6060f1SDimitry Andric return !symbolIndices.empty(); 1010fe6060f1SDimitry Andric } 1011fe6060f1SDimitry Andric 10120b57cec5SDimitry Andric template <class ELFT> static void readCallGraphsFromObjectFiles() { 1013fe6060f1SDimitry Andric SmallVector<uint32_t, 32> symbolIndices; 1014fe6060f1SDimitry Andric ArrayRef<typename ELFT::CGProfile> cgProfile; 1015bdd1243dSDimitry Andric for (auto file : ctx.objectFiles) { 10160b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(file); 1017fe6060f1SDimitry Andric if (!processCallGraphRelocations(symbolIndices, cgProfile, obj)) 1018fe6060f1SDimitry Andric continue; 10190b57cec5SDimitry Andric 1020fe6060f1SDimitry Andric if (symbolIndices.size() != cgProfile.size() * 2) 1021fe6060f1SDimitry Andric fatal("number of relocations doesn't match Weights"); 1022fe6060f1SDimitry Andric 1023fe6060f1SDimitry Andric for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) { 1024fe6060f1SDimitry Andric const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i]; 1025fe6060f1SDimitry Andric uint32_t fromIndex = symbolIndices[i * 2]; 1026fe6060f1SDimitry Andric uint32_t toIndex = symbolIndices[i * 2 + 1]; 1027fe6060f1SDimitry Andric auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex)); 1028fe6060f1SDimitry Andric auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex)); 10290b57cec5SDimitry Andric if (!fromSym || !toSym) 10300b57cec5SDimitry Andric continue; 10310b57cec5SDimitry Andric 10320b57cec5SDimitry Andric auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section); 10330b57cec5SDimitry Andric auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section); 10340b57cec5SDimitry Andric if (from && to) 10350b57cec5SDimitry Andric config->callGraphProfile[{from, to}] += cgpe.cgp_weight; 10360b57cec5SDimitry Andric } 10370b57cec5SDimitry Andric } 10380b57cec5SDimitry Andric } 10390b57cec5SDimitry Andric 1040*5f757f3fSDimitry Andric template <class ELFT> 1041*5f757f3fSDimitry Andric static void ltoValidateAllVtablesHaveTypeInfos(opt::InputArgList &args) { 1042*5f757f3fSDimitry Andric DenseSet<StringRef> typeInfoSymbols; 1043*5f757f3fSDimitry Andric SmallSetVector<StringRef, 0> vtableSymbols; 1044*5f757f3fSDimitry Andric auto processVtableAndTypeInfoSymbols = [&](StringRef name) { 1045*5f757f3fSDimitry Andric if (name.consume_front("_ZTI")) 1046*5f757f3fSDimitry Andric typeInfoSymbols.insert(name); 1047*5f757f3fSDimitry Andric else if (name.consume_front("_ZTV")) 1048*5f757f3fSDimitry Andric vtableSymbols.insert(name); 1049*5f757f3fSDimitry Andric }; 1050*5f757f3fSDimitry Andric 1051*5f757f3fSDimitry Andric // Examine all native symbol tables. 1052*5f757f3fSDimitry Andric for (ELFFileBase *f : ctx.objectFiles) { 1053*5f757f3fSDimitry Andric using Elf_Sym = typename ELFT::Sym; 1054*5f757f3fSDimitry Andric for (const Elf_Sym &s : f->template getGlobalELFSyms<ELFT>()) { 1055*5f757f3fSDimitry Andric if (s.st_shndx != SHN_UNDEF) { 1056*5f757f3fSDimitry Andric StringRef name = check(s.getName(f->getStringTable())); 1057*5f757f3fSDimitry Andric processVtableAndTypeInfoSymbols(name); 1058*5f757f3fSDimitry Andric } 1059*5f757f3fSDimitry Andric } 1060*5f757f3fSDimitry Andric } 1061*5f757f3fSDimitry Andric 1062*5f757f3fSDimitry Andric for (SharedFile *f : ctx.sharedFiles) { 1063*5f757f3fSDimitry Andric using Elf_Sym = typename ELFT::Sym; 1064*5f757f3fSDimitry Andric for (const Elf_Sym &s : f->template getELFSyms<ELFT>()) { 1065*5f757f3fSDimitry Andric if (s.st_shndx != SHN_UNDEF) { 1066*5f757f3fSDimitry Andric StringRef name = check(s.getName(f->getStringTable())); 1067*5f757f3fSDimitry Andric processVtableAndTypeInfoSymbols(name); 1068*5f757f3fSDimitry Andric } 1069*5f757f3fSDimitry Andric } 1070*5f757f3fSDimitry Andric } 1071*5f757f3fSDimitry Andric 1072*5f757f3fSDimitry Andric SmallSetVector<StringRef, 0> vtableSymbolsWithNoRTTI; 1073*5f757f3fSDimitry Andric for (StringRef s : vtableSymbols) 1074*5f757f3fSDimitry Andric if (!typeInfoSymbols.count(s)) 1075*5f757f3fSDimitry Andric vtableSymbolsWithNoRTTI.insert(s); 1076*5f757f3fSDimitry Andric 1077*5f757f3fSDimitry Andric // Remove known safe symbols. 1078*5f757f3fSDimitry Andric for (auto *arg : args.filtered(OPT_lto_known_safe_vtables)) { 1079*5f757f3fSDimitry Andric StringRef knownSafeName = arg->getValue(); 1080*5f757f3fSDimitry Andric if (!knownSafeName.consume_front("_ZTV")) 1081*5f757f3fSDimitry Andric error("--lto-known-safe-vtables=: expected symbol to start with _ZTV, " 1082*5f757f3fSDimitry Andric "but got " + 1083*5f757f3fSDimitry Andric knownSafeName); 1084*5f757f3fSDimitry Andric vtableSymbolsWithNoRTTI.remove(knownSafeName); 1085*5f757f3fSDimitry Andric } 1086*5f757f3fSDimitry Andric 1087*5f757f3fSDimitry Andric ctx.ltoAllVtablesHaveTypeInfos = vtableSymbolsWithNoRTTI.empty(); 1088*5f757f3fSDimitry Andric // Check for unmatched RTTI symbols 1089*5f757f3fSDimitry Andric for (StringRef s : vtableSymbolsWithNoRTTI) { 1090*5f757f3fSDimitry Andric message( 1091*5f757f3fSDimitry Andric "--lto-validate-all-vtables-have-type-infos: RTTI missing for vtable " 1092*5f757f3fSDimitry Andric "_ZTV" + 1093*5f757f3fSDimitry Andric s + ", --lto-whole-program-visibility disabled"); 1094*5f757f3fSDimitry Andric } 1095*5f757f3fSDimitry Andric } 1096*5f757f3fSDimitry Andric 1097*5f757f3fSDimitry Andric static CGProfileSortKind getCGProfileSortKind(opt::InputArgList &args) { 1098*5f757f3fSDimitry Andric StringRef s = args.getLastArgValue(OPT_call_graph_profile_sort, "cdsort"); 1099*5f757f3fSDimitry Andric if (s == "hfsort") 1100*5f757f3fSDimitry Andric return CGProfileSortKind::Hfsort; 1101*5f757f3fSDimitry Andric if (s == "cdsort") 1102*5f757f3fSDimitry Andric return CGProfileSortKind::Cdsort; 1103*5f757f3fSDimitry Andric if (s != "none") 1104*5f757f3fSDimitry Andric error("unknown --call-graph-profile-sort= value: " + s); 1105*5f757f3fSDimitry Andric return CGProfileSortKind::None; 1106*5f757f3fSDimitry Andric } 1107*5f757f3fSDimitry Andric 110806c3fb27SDimitry Andric static DebugCompressionType getCompressionType(StringRef s, StringRef option) { 110906c3fb27SDimitry Andric DebugCompressionType type = StringSwitch<DebugCompressionType>(s) 111006c3fb27SDimitry Andric .Case("zlib", DebugCompressionType::Zlib) 111106c3fb27SDimitry Andric .Case("zstd", DebugCompressionType::Zstd) 111206c3fb27SDimitry Andric .Default(DebugCompressionType::None); 111306c3fb27SDimitry Andric if (type == DebugCompressionType::None) { 1114bdd1243dSDimitry Andric if (s != "none") 111506c3fb27SDimitry Andric error("unknown " + option + " value: " + s); 111606c3fb27SDimitry Andric } else if (const char *reason = compression::getReasonIfUnsupported( 111706c3fb27SDimitry Andric compression::formatFor(type))) { 111806c3fb27SDimitry Andric error(option + ": " + reason); 111906c3fb27SDimitry Andric } 112006c3fb27SDimitry Andric return type; 11210b57cec5SDimitry Andric } 11220b57cec5SDimitry Andric 112385868e8aSDimitry Andric static StringRef getAliasSpelling(opt::Arg *arg) { 112485868e8aSDimitry Andric if (const opt::Arg *alias = arg->getAlias()) 112585868e8aSDimitry Andric return alias->getSpelling(); 112685868e8aSDimitry Andric return arg->getSpelling(); 112785868e8aSDimitry Andric } 112885868e8aSDimitry Andric 11290b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 11300b57cec5SDimitry Andric unsigned id) { 11310b57cec5SDimitry Andric auto *arg = args.getLastArg(id); 11320b57cec5SDimitry Andric if (!arg) 11330b57cec5SDimitry Andric return {"", ""}; 11340b57cec5SDimitry Andric 11350b57cec5SDimitry Andric StringRef s = arg->getValue(); 11360b57cec5SDimitry Andric std::pair<StringRef, StringRef> ret = s.split(';'); 11370b57cec5SDimitry Andric if (ret.second.empty()) 113885868e8aSDimitry Andric error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s); 11390b57cec5SDimitry Andric return ret; 11400b57cec5SDimitry Andric } 11410b57cec5SDimitry Andric 114206c3fb27SDimitry Andric // Parse options of the form "old;new[;extra]". 114306c3fb27SDimitry Andric static std::tuple<StringRef, StringRef, StringRef> 114406c3fb27SDimitry Andric getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) { 114506c3fb27SDimitry Andric auto [oldDir, second] = getOldNewOptions(args, id); 114606c3fb27SDimitry Andric auto [newDir, extraDir] = second.split(';'); 114706c3fb27SDimitry Andric return {oldDir, newDir, extraDir}; 114806c3fb27SDimitry Andric } 114906c3fb27SDimitry Andric 11500b57cec5SDimitry Andric // Parse the symbol ordering file and warn for any duplicate entries. 1151bdd1243dSDimitry Andric static SmallVector<StringRef, 0> getSymbolOrderingFile(MemoryBufferRef mb) { 1152bdd1243dSDimitry Andric SetVector<StringRef, SmallVector<StringRef, 0>> names; 11530b57cec5SDimitry Andric for (StringRef s : args::getLines(mb)) 11540b57cec5SDimitry Andric if (!names.insert(s) && config->warnSymbolOrdering) 11550b57cec5SDimitry Andric warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s); 11560b57cec5SDimitry Andric 11570b57cec5SDimitry Andric return names.takeVector(); 11580b57cec5SDimitry Andric } 11590b57cec5SDimitry Andric 11605ffd83dbSDimitry Andric static bool getIsRela(opt::InputArgList &args) { 11615ffd83dbSDimitry Andric // If -z rel or -z rela is specified, use the last option. 11625ffd83dbSDimitry Andric for (auto *arg : args.filtered_reverse(OPT_z)) { 11635ffd83dbSDimitry Andric StringRef s(arg->getValue()); 11645ffd83dbSDimitry Andric if (s == "rel") 11655ffd83dbSDimitry Andric return false; 11665ffd83dbSDimitry Andric if (s == "rela") 11675ffd83dbSDimitry Andric return true; 11685ffd83dbSDimitry Andric } 11695ffd83dbSDimitry Andric 11705ffd83dbSDimitry Andric // Otherwise use the psABI defined relocation entry format. 11715ffd83dbSDimitry Andric uint16_t m = config->emachine; 117206c3fb27SDimitry Andric return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || 117306c3fb27SDimitry Andric m == EM_LOONGARCH || m == EM_PPC || m == EM_PPC64 || m == EM_RISCV || 117406c3fb27SDimitry Andric m == EM_X86_64; 11755ffd83dbSDimitry Andric } 11765ffd83dbSDimitry Andric 11770b57cec5SDimitry Andric static void parseClangOption(StringRef opt, const Twine &msg) { 11780b57cec5SDimitry Andric std::string err; 11790b57cec5SDimitry Andric raw_string_ostream os(err); 11800b57cec5SDimitry Andric 11810b57cec5SDimitry Andric const char *argv[] = {config->progName.data(), opt.data()}; 11820b57cec5SDimitry Andric if (cl::ParseCommandLineOptions(2, argv, "", &os)) 11830b57cec5SDimitry Andric return; 11840b57cec5SDimitry Andric os.flush(); 11850b57cec5SDimitry Andric error(msg + ": " + StringRef(err).trim()); 11860b57cec5SDimitry Andric } 11870b57cec5SDimitry Andric 11880eae32dcSDimitry Andric // Checks the parameter of the bti-report and cet-report options. 11890eae32dcSDimitry Andric static bool isValidReportString(StringRef arg) { 11900eae32dcSDimitry Andric return arg == "none" || arg == "warning" || arg == "error"; 11910eae32dcSDimitry Andric } 11920eae32dcSDimitry Andric 119306c3fb27SDimitry Andric // Process a remap pattern 'from-glob=to-file'. 119406c3fb27SDimitry Andric static bool remapInputs(StringRef line, const Twine &location) { 119506c3fb27SDimitry Andric SmallVector<StringRef, 0> fields; 119606c3fb27SDimitry Andric line.split(fields, '='); 119706c3fb27SDimitry Andric if (fields.size() != 2 || fields[1].empty()) { 119806c3fb27SDimitry Andric error(location + ": parse error, not 'from-glob=to-file'"); 119906c3fb27SDimitry Andric return true; 120006c3fb27SDimitry Andric } 120106c3fb27SDimitry Andric if (!hasWildcard(fields[0])) 120206c3fb27SDimitry Andric config->remapInputs[fields[0]] = fields[1]; 120306c3fb27SDimitry Andric else if (Expected<GlobPattern> pat = GlobPattern::create(fields[0])) 120406c3fb27SDimitry Andric config->remapInputsWildcards.emplace_back(std::move(*pat), fields[1]); 120506c3fb27SDimitry Andric else { 1206*5f757f3fSDimitry Andric error(location + ": " + toString(pat.takeError()) + ": " + fields[0]); 120706c3fb27SDimitry Andric return true; 120806c3fb27SDimitry Andric } 120906c3fb27SDimitry Andric return false; 121006c3fb27SDimitry Andric } 121106c3fb27SDimitry Andric 12120b57cec5SDimitry Andric // Initializes Config members by the command line options. 12130b57cec5SDimitry Andric static void readConfigs(opt::InputArgList &args) { 12140b57cec5SDimitry Andric errorHandler().verbose = args.hasArg(OPT_verbose); 12150b57cec5SDimitry Andric errorHandler().vsDiagnostics = 12160b57cec5SDimitry Andric args.hasArg(OPT_visual_studio_diagnostics_format, false); 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric config->allowMultipleDefinition = 12190b57cec5SDimitry Andric args.hasFlag(OPT_allow_multiple_definition, 12200b57cec5SDimitry Andric OPT_no_allow_multiple_definition, false) || 12210b57cec5SDimitry Andric hasZOption(args, "muldefs"); 122281ad6265SDimitry Andric config->androidMemtagHeap = 122381ad6265SDimitry Andric args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false); 122481ad6265SDimitry Andric config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack, 122581ad6265SDimitry Andric OPT_no_android_memtag_stack, false); 1226*5f757f3fSDimitry Andric config->fatLTOObjects = 1227*5f757f3fSDimitry Andric args.hasFlag(OPT_fat_lto_objects, OPT_no_fat_lto_objects, false); 122881ad6265SDimitry Andric config->androidMemtagMode = getMemtagMode(args); 12290b57cec5SDimitry Andric config->auxiliaryList = args::getStrings(args, OPT_auxiliary); 123006c3fb27SDimitry Andric config->armBe8 = args.hasArg(OPT_be8); 1231*5f757f3fSDimitry Andric if (opt::Arg *arg = args.getLastArg( 1232*5f757f3fSDimitry Andric OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions, 1233*5f757f3fSDimitry Andric OPT_Bsymbolic_functions, OPT_Bsymbolic_non_weak, OPT_Bsymbolic)) { 12346e75b2fbSDimitry Andric if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions)) 12356e75b2fbSDimitry Andric config->bsymbolic = BsymbolicKind::NonWeakFunctions; 12366e75b2fbSDimitry Andric else if (arg->getOption().matches(OPT_Bsymbolic_functions)) 12376e75b2fbSDimitry Andric config->bsymbolic = BsymbolicKind::Functions; 1238*5f757f3fSDimitry Andric else if (arg->getOption().matches(OPT_Bsymbolic_non_weak)) 1239*5f757f3fSDimitry Andric config->bsymbolic = BsymbolicKind::NonWeak; 1240fe6060f1SDimitry Andric else if (arg->getOption().matches(OPT_Bsymbolic)) 12416e75b2fbSDimitry Andric config->bsymbolic = BsymbolicKind::All; 1242fe6060f1SDimitry Andric } 1243*5f757f3fSDimitry Andric config->callGraphProfileSort = getCGProfileSortKind(args); 12440b57cec5SDimitry Andric config->checkSections = 12450b57cec5SDimitry Andric args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 12460b57cec5SDimitry Andric config->chroot = args.getLastArgValue(OPT_chroot); 124706c3fb27SDimitry Andric config->compressDebugSections = getCompressionType( 124806c3fb27SDimitry Andric args.getLastArgValue(OPT_compress_debug_sections, "none"), 124906c3fb27SDimitry Andric "--compress-debug-sections"); 1250fe6060f1SDimitry Andric config->cref = args.hasArg(OPT_cref); 12515ffd83dbSDimitry Andric config->optimizeBBJumps = 12525ffd83dbSDimitry Andric args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false); 12530b57cec5SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true); 1254e8d8bef9SDimitry Andric config->dependencyFile = args.getLastArgValue(OPT_dependency_file); 12550b57cec5SDimitry Andric config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true); 12560b57cec5SDimitry Andric config->disableVerify = args.hasArg(OPT_disable_verify); 12570b57cec5SDimitry Andric config->discard = getDiscard(args); 12580b57cec5SDimitry Andric config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq); 12590b57cec5SDimitry Andric config->dynamicLinker = getDynamicLinker(args); 12600b57cec5SDimitry Andric config->ehFrameHdr = 12610b57cec5SDimitry Andric args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 12620b57cec5SDimitry Andric config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false); 12630b57cec5SDimitry Andric config->emitRelocs = args.hasArg(OPT_emit_relocs); 12640b57cec5SDimitry Andric config->enableNewDtags = 12650b57cec5SDimitry Andric args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 12660b57cec5SDimitry Andric config->entry = args.getLastArgValue(OPT_entry); 1267e8d8bef9SDimitry Andric 1268e8d8bef9SDimitry Andric errorHandler().errorHandlingScript = 1269e8d8bef9SDimitry Andric args.getLastArgValue(OPT_error_handling_script); 1270e8d8bef9SDimitry Andric 12710b57cec5SDimitry Andric config->executeOnly = 12720b57cec5SDimitry Andric args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 12730b57cec5SDimitry Andric config->exportDynamic = 127481ad6265SDimitry Andric args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) || 127581ad6265SDimitry Andric args.hasArg(OPT_shared); 12760b57cec5SDimitry Andric config->filterList = args::getStrings(args, OPT_filter); 12770b57cec5SDimitry Andric config->fini = args.getLastArgValue(OPT_fini, "_fini"); 12785ffd83dbSDimitry Andric config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) && 12795ffd83dbSDimitry Andric !args.hasArg(OPT_relocatable); 128006c3fb27SDimitry Andric config->cmseImplib = args.hasArg(OPT_cmse_implib); 128106c3fb27SDimitry Andric config->cmseInputLib = args.getLastArgValue(OPT_in_implib); 128206c3fb27SDimitry Andric config->cmseOutputLib = args.getLastArgValue(OPT_out_implib); 12835ffd83dbSDimitry Andric config->fixCortexA8 = 12845ffd83dbSDimitry Andric args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable); 1285e8d8bef9SDimitry Andric config->fortranCommon = 128681ad6265SDimitry Andric args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false); 12870b57cec5SDimitry Andric config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 12880b57cec5SDimitry Andric config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 12890b57cec5SDimitry Andric config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 12900b57cec5SDimitry Andric config->icf = getICF(args); 12910b57cec5SDimitry Andric config->ignoreDataAddressEquality = 12920b57cec5SDimitry Andric args.hasArg(OPT_ignore_data_address_equality); 12930b57cec5SDimitry Andric config->ignoreFunctionAddressEquality = 12940b57cec5SDimitry Andric args.hasArg(OPT_ignore_function_address_equality); 12950b57cec5SDimitry Andric config->init = args.getLastArgValue(OPT_init, "_init"); 12960b57cec5SDimitry Andric config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline); 12970b57cec5SDimitry Andric config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 12980b57cec5SDimitry Andric config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 1299349cc55cSDimitry Andric config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1300349cc55cSDimitry Andric OPT_no_lto_pgo_warn_mismatch, true); 13010b57cec5SDimitry Andric config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager); 13025ffd83dbSDimitry Andric config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm); 13030b57cec5SDimitry Andric config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes); 13045ffd83dbSDimitry Andric config->ltoWholeProgramVisibility = 1305e8d8bef9SDimitry Andric args.hasFlag(OPT_lto_whole_program_visibility, 1306e8d8bef9SDimitry Andric OPT_no_lto_whole_program_visibility, false); 1307*5f757f3fSDimitry Andric config->ltoValidateAllVtablesHaveTypeInfos = 1308*5f757f3fSDimitry Andric args.hasFlag(OPT_lto_validate_all_vtables_have_type_infos, 1309*5f757f3fSDimitry Andric OPT_no_lto_validate_all_vtables_have_type_infos, false); 13100b57cec5SDimitry Andric config->ltoo = args::getInteger(args, OPT_lto_O, 2); 131106c3fb27SDimitry Andric if (config->ltoo > 3) 131206c3fb27SDimitry Andric error("invalid optimization level for LTO: " + Twine(config->ltoo)); 131306c3fb27SDimitry Andric unsigned ltoCgo = 131406c3fb27SDimitry Andric args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo)); 131506c3fb27SDimitry Andric if (auto level = CodeGenOpt::getLevel(ltoCgo)) 131606c3fb27SDimitry Andric config->ltoCgo = *level; 131706c3fb27SDimitry Andric else 131806c3fb27SDimitry Andric error("invalid codegen optimization level for LTO: " + Twine(ltoCgo)); 131985868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq); 13200b57cec5SDimitry Andric config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1); 13210b57cec5SDimitry Andric config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 13225ffd83dbSDimitry Andric config->ltoBasicBlockSections = 1323e8d8bef9SDimitry Andric args.getLastArgValue(OPT_lto_basic_block_sections); 13245ffd83dbSDimitry Andric config->ltoUniqueBasicBlockSectionNames = 1325e8d8bef9SDimitry Andric args.hasFlag(OPT_lto_unique_basic_block_section_names, 1326e8d8bef9SDimitry Andric OPT_no_lto_unique_basic_block_section_names, false); 13270b57cec5SDimitry Andric config->mapFile = args.getLastArgValue(OPT_Map); 13280b57cec5SDimitry Andric config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0); 13290b57cec5SDimitry Andric config->mergeArmExidx = 13300b57cec5SDimitry Andric args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 1331480093f4SDimitry Andric config->mmapOutputFile = 1332480093f4SDimitry Andric args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true); 13330b57cec5SDimitry Andric config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 13340b57cec5SDimitry Andric config->noinhibitExec = args.hasArg(OPT_noinhibit_exec); 13350b57cec5SDimitry Andric config->nostdlib = args.hasArg(OPT_nostdlib); 13360b57cec5SDimitry Andric config->oFormatBinary = isOutputFormatBinary(args); 13370b57cec5SDimitry Andric config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false); 13380b57cec5SDimitry Andric config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename); 133981ad6265SDimitry Andric config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file); 1340e8d8bef9SDimitry Andric 1341e8d8bef9SDimitry Andric // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 1342e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) { 1343e8d8bef9SDimitry Andric auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue()); 1344e8d8bef9SDimitry Andric if (!resultOrErr) 1345e8d8bef9SDimitry Andric error(arg->getSpelling() + ": invalid argument '" + arg->getValue() + 1346e8d8bef9SDimitry Andric "', only integer or 'auto' is supported"); 1347e8d8bef9SDimitry Andric else 1348e8d8bef9SDimitry Andric config->optRemarksHotnessThreshold = *resultOrErr; 1349e8d8bef9SDimitry Andric } 1350e8d8bef9SDimitry Andric 13510b57cec5SDimitry Andric config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes); 13520b57cec5SDimitry Andric config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness); 13530b57cec5SDimitry Andric config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format); 13540b57cec5SDimitry Andric config->optimize = args::getInteger(args, OPT_O, 1); 13550b57cec5SDimitry Andric config->orphanHandling = getOrphanHandling(args); 13560b57cec5SDimitry Andric config->outputFile = args.getLastArgValue(OPT_o); 135761cfbce3SDimitry Andric config->packageMetadata = args.getLastArgValue(OPT_package_metadata); 13580b57cec5SDimitry Andric config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false); 13590b57cec5SDimitry Andric config->printIcfSections = 13600b57cec5SDimitry Andric args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 13610b57cec5SDimitry Andric config->printGcSections = 13620b57cec5SDimitry Andric args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 136306c3fb27SDimitry Andric config->printMemoryUsage = args.hasArg(OPT_print_memory_usage); 13645ffd83dbSDimitry Andric config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats); 13650b57cec5SDimitry Andric config->printSymbolOrder = 13660b57cec5SDimitry Andric args.getLastArgValue(OPT_print_symbol_order); 1367349cc55cSDimitry Andric config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true); 136806c3fb27SDimitry Andric config->relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false); 13690b57cec5SDimitry Andric config->rpath = getRpath(args); 13700b57cec5SDimitry Andric config->relocatable = args.hasArg(OPT_relocatable); 1371753f127fSDimitry Andric 1372753f127fSDimitry Andric if (args.hasArg(OPT_save_temps)) { 1373753f127fSDimitry Andric // --save-temps implies saving all temps. 1374753f127fSDimitry Andric for (const char *s : saveTempsValues) 1375753f127fSDimitry Andric config->saveTempsArgs.insert(s); 1376753f127fSDimitry Andric } else { 1377753f127fSDimitry Andric for (auto *arg : args.filtered(OPT_save_temps_eq)) { 1378753f127fSDimitry Andric StringRef s = arg->getValue(); 1379753f127fSDimitry Andric if (llvm::is_contained(saveTempsValues, s)) 1380753f127fSDimitry Andric config->saveTempsArgs.insert(s); 1381753f127fSDimitry Andric else 1382753f127fSDimitry Andric error("unknown --save-temps value: " + s); 1383753f127fSDimitry Andric } 1384753f127fSDimitry Andric } 1385753f127fSDimitry Andric 13860b57cec5SDimitry Andric config->searchPaths = args::getStrings(args, OPT_library_path); 13870b57cec5SDimitry Andric config->sectionStartMap = getSectionStartMap(args); 13880b57cec5SDimitry Andric config->shared = args.hasArg(OPT_shared); 13895ffd83dbSDimitry Andric config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true); 13900b57cec5SDimitry Andric config->soName = args.getLastArgValue(OPT_soname); 13910b57cec5SDimitry Andric config->sortSection = getSortSection(args); 13920b57cec5SDimitry Andric config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384); 13930b57cec5SDimitry Andric config->strip = getStrip(args); 13940b57cec5SDimitry Andric config->sysroot = args.getLastArgValue(OPT_sysroot); 13950b57cec5SDimitry Andric config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 13960b57cec5SDimitry Andric config->target2 = getTarget2(args); 13970b57cec5SDimitry Andric config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir); 13980b57cec5SDimitry Andric config->thinLTOCachePolicy = CHECK( 13990b57cec5SDimitry Andric parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)), 14000b57cec5SDimitry Andric "--thinlto-cache-policy: invalid cache policy"); 140185868e8aSDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 140281ad6265SDimitry Andric config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) || 140381ad6265SDimitry Andric args.hasArg(OPT_thinlto_index_only) || 140481ad6265SDimitry Andric args.hasArg(OPT_thinlto_index_only_eq); 140585868e8aSDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 140685868e8aSDimitry Andric args.hasArg(OPT_thinlto_index_only_eq); 140785868e8aSDimitry Andric config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq); 14080b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 140985868e8aSDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq); 141006c3fb27SDimitry Andric std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew, 141106c3fb27SDimitry Andric config->thinLTOPrefixReplaceNativeObject) = 141206c3fb27SDimitry Andric getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace_eq); 141381ad6265SDimitry Andric if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) { 141481ad6265SDimitry Andric if (args.hasArg(OPT_thinlto_object_suffix_replace_eq)) 141581ad6265SDimitry Andric error("--thinlto-object-suffix-replace is not supported with " 141681ad6265SDimitry Andric "--thinlto-emit-index-files"); 141781ad6265SDimitry Andric else if (args.hasArg(OPT_thinlto_prefix_replace_eq)) 141881ad6265SDimitry Andric error("--thinlto-prefix-replace is not supported with " 141981ad6265SDimitry Andric "--thinlto-emit-index-files"); 142081ad6265SDimitry Andric } 142106c3fb27SDimitry Andric if (!config->thinLTOPrefixReplaceNativeObject.empty() && 142206c3fb27SDimitry Andric config->thinLTOIndexOnlyArg.empty()) { 142306c3fb27SDimitry Andric error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with " 142406c3fb27SDimitry Andric "--thinlto-index-only="); 142506c3fb27SDimitry Andric } 14265ffd83dbSDimitry Andric config->thinLTOModulesToCompile = 14275ffd83dbSDimitry Andric args::getStrings(args, OPT_thinlto_single_module_eq); 142881ad6265SDimitry Andric config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq); 14295ffd83dbSDimitry Andric config->timeTraceGranularity = 14305ffd83dbSDimitry Andric args::getInteger(args, OPT_time_trace_granularity, 500); 14310b57cec5SDimitry Andric config->trace = args.hasArg(OPT_trace); 14320b57cec5SDimitry Andric config->undefined = args::getStrings(args, OPT_undefined); 14330b57cec5SDimitry Andric config->undefinedVersion = 1434bdd1243dSDimitry Andric args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false); 14355ffd83dbSDimitry Andric config->unique = args.hasArg(OPT_unique); 14360b57cec5SDimitry Andric config->useAndroidRelrTags = args.hasFlag( 14370b57cec5SDimitry Andric OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 14380b57cec5SDimitry Andric config->warnBackrefs = 14390b57cec5SDimitry Andric args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 14400b57cec5SDimitry Andric config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 14410b57cec5SDimitry Andric config->warnSymbolOrdering = 14420b57cec5SDimitry Andric args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 1443349cc55cSDimitry Andric config->whyExtract = args.getLastArgValue(OPT_why_extract); 14440b57cec5SDimitry Andric config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true); 14450b57cec5SDimitry Andric config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true); 14465ffd83dbSDimitry Andric config->zForceBti = hasZOption(args, "force-bti"); 1447480093f4SDimitry Andric config->zForceIbt = hasZOption(args, "force-ibt"); 14480b57cec5SDimitry Andric config->zGlobal = hasZOption(args, "global"); 1449480093f4SDimitry Andric config->zGnustack = getZGnuStack(args); 14500b57cec5SDimitry Andric config->zHazardplt = hasZOption(args, "hazardplt"); 14510b57cec5SDimitry Andric config->zIfuncNoplt = hasZOption(args, "ifunc-noplt"); 14520b57cec5SDimitry Andric config->zInitfirst = hasZOption(args, "initfirst"); 14530b57cec5SDimitry Andric config->zInterpose = hasZOption(args, "interpose"); 14540b57cec5SDimitry Andric config->zKeepTextSectionPrefix = getZFlag( 14550b57cec5SDimitry Andric args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 14560b57cec5SDimitry Andric config->zNodefaultlib = hasZOption(args, "nodefaultlib"); 14570b57cec5SDimitry Andric config->zNodelete = hasZOption(args, "nodelete"); 14580b57cec5SDimitry Andric config->zNodlopen = hasZOption(args, "nodlopen"); 14590b57cec5SDimitry Andric config->zNow = getZFlag(args, "now", "lazy", false); 14600b57cec5SDimitry Andric config->zOrigin = hasZOption(args, "origin"); 14615ffd83dbSDimitry Andric config->zPacPlt = hasZOption(args, "pac-plt"); 14620b57cec5SDimitry Andric config->zRelro = getZFlag(args, "relro", "norelro", true); 14630b57cec5SDimitry Andric config->zRetpolineplt = hasZOption(args, "retpolineplt"); 14640b57cec5SDimitry Andric config->zRodynamic = hasZOption(args, "rodynamic"); 146585868e8aSDimitry Andric config->zSeparate = getZSeparate(args); 1466480093f4SDimitry Andric config->zShstk = hasZOption(args, "shstk"); 14670b57cec5SDimitry Andric config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0); 1468fe6060f1SDimitry Andric config->zStartStopGC = 1469fe6060f1SDimitry Andric getZFlag(args, "start-stop-gc", "nostart-stop-gc", true); 14705ffd83dbSDimitry Andric config->zStartStopVisibility = getZStartStopVisibility(args); 14710b57cec5SDimitry Andric config->zText = getZFlag(args, "text", "notext", true); 14720b57cec5SDimitry Andric config->zWxneeded = hasZOption(args, "wxneeded"); 1473e8d8bef9SDimitry Andric setUnresolvedSymbolPolicy(args); 14744824e7fdSDimitry Andric config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no"; 1475fe6060f1SDimitry Andric 1476fe6060f1SDimitry Andric if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) { 1477fe6060f1SDimitry Andric if (arg->getOption().matches(OPT_eb)) 1478fe6060f1SDimitry Andric config->optEB = true; 1479fe6060f1SDimitry Andric else 1480fe6060f1SDimitry Andric config->optEL = true; 1481fe6060f1SDimitry Andric } 1482fe6060f1SDimitry Andric 148306c3fb27SDimitry Andric for (opt::Arg *arg : args.filtered(OPT_remap_inputs)) { 148406c3fb27SDimitry Andric StringRef value(arg->getValue()); 148506c3fb27SDimitry Andric remapInputs(value, arg->getSpelling()); 148606c3fb27SDimitry Andric } 148706c3fb27SDimitry Andric for (opt::Arg *arg : args.filtered(OPT_remap_inputs_file)) { 148806c3fb27SDimitry Andric StringRef filename(arg->getValue()); 148906c3fb27SDimitry Andric std::optional<MemoryBufferRef> buffer = readFile(filename); 149006c3fb27SDimitry Andric if (!buffer) 149106c3fb27SDimitry Andric continue; 149206c3fb27SDimitry Andric // Parse 'from-glob=to-file' lines, ignoring #-led comments. 149306c3fb27SDimitry Andric for (auto [lineno, line] : llvm::enumerate(args::getLines(*buffer))) 149406c3fb27SDimitry Andric if (remapInputs(line, filename + ":" + Twine(lineno + 1))) 149506c3fb27SDimitry Andric break; 149606c3fb27SDimitry Andric } 149706c3fb27SDimitry Andric 1498fe6060f1SDimitry Andric for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) { 1499fe6060f1SDimitry Andric constexpr StringRef errPrefix = "--shuffle-sections=: "; 1500fe6060f1SDimitry Andric std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 1501fe6060f1SDimitry Andric if (kv.first.empty() || kv.second.empty()) { 1502fe6060f1SDimitry Andric error(errPrefix + "expected <section_glob>=<seed>, but got '" + 1503fe6060f1SDimitry Andric arg->getValue() + "'"); 1504fe6060f1SDimitry Andric continue; 1505fe6060f1SDimitry Andric } 1506fe6060f1SDimitry Andric // Signed so that <section_glob>=-1 is allowed. 1507fe6060f1SDimitry Andric int64_t v; 1508fe6060f1SDimitry Andric if (!to_integer(kv.second, v)) 1509fe6060f1SDimitry Andric error(errPrefix + "expected an integer, but got '" + kv.second + "'"); 1510fe6060f1SDimitry Andric else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1511fe6060f1SDimitry Andric config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v)); 1512fe6060f1SDimitry Andric else 1513*5f757f3fSDimitry Andric error(errPrefix + toString(pat.takeError()) + ": " + kv.first); 1514fe6060f1SDimitry Andric } 15150b57cec5SDimitry Andric 15160eae32dcSDimitry Andric auto reports = {std::make_pair("bti-report", &config->zBtiReport), 15170eae32dcSDimitry Andric std::make_pair("cet-report", &config->zCetReport)}; 15180eae32dcSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_z)) { 15190eae32dcSDimitry Andric std::pair<StringRef, StringRef> option = 15200eae32dcSDimitry Andric StringRef(arg->getValue()).split('='); 15210eae32dcSDimitry Andric for (auto reportArg : reports) { 15220eae32dcSDimitry Andric if (option.first != reportArg.first) 15230eae32dcSDimitry Andric continue; 15240eae32dcSDimitry Andric if (!isValidReportString(option.second)) { 15250eae32dcSDimitry Andric error(Twine("-z ") + reportArg.first + "= parameter " + option.second + 15260eae32dcSDimitry Andric " is not recognized"); 15270eae32dcSDimitry Andric continue; 15280eae32dcSDimitry Andric } 15290eae32dcSDimitry Andric *reportArg.second = option.second; 15300eae32dcSDimitry Andric } 15310eae32dcSDimitry Andric } 15320eae32dcSDimitry Andric 15335ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_z)) { 15345ffd83dbSDimitry Andric std::pair<StringRef, StringRef> option = 15355ffd83dbSDimitry Andric StringRef(arg->getValue()).split('='); 15365ffd83dbSDimitry Andric if (option.first != "dead-reloc-in-nonalloc") 15375ffd83dbSDimitry Andric continue; 15385ffd83dbSDimitry Andric constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: "; 15395ffd83dbSDimitry Andric std::pair<StringRef, StringRef> kv = option.second.split('='); 15405ffd83dbSDimitry Andric if (kv.first.empty() || kv.second.empty()) { 15415ffd83dbSDimitry Andric error(errPrefix + "expected <section_glob>=<value>"); 15425ffd83dbSDimitry Andric continue; 15435ffd83dbSDimitry Andric } 15445ffd83dbSDimitry Andric uint64_t v; 15455ffd83dbSDimitry Andric if (!to_integer(kv.second, v)) 15465ffd83dbSDimitry Andric error(errPrefix + "expected a non-negative integer, but got '" + 15475ffd83dbSDimitry Andric kv.second + "'"); 15485ffd83dbSDimitry Andric else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 15495ffd83dbSDimitry Andric config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v); 15505ffd83dbSDimitry Andric else 1551*5f757f3fSDimitry Andric error(errPrefix + toString(pat.takeError()) + ": " + kv.first); 15525ffd83dbSDimitry Andric } 15535ffd83dbSDimitry Andric 1554e8d8bef9SDimitry Andric cl::ResetAllOptionOccurrences(); 1555e8d8bef9SDimitry Andric 15560b57cec5SDimitry Andric // Parse LTO options. 15570b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq)) 155804eeddc0SDimitry Andric parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())), 15590b57cec5SDimitry Andric arg->getSpelling()); 15600b57cec5SDimitry Andric 15615ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus)) 15625ffd83dbSDimitry Andric parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling()); 15635ffd83dbSDimitry Andric 15645ffd83dbSDimitry Andric // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or 1565f3fd488fSDimitry Andric // relative path. Just ignore. If not ended with "lto-wrapper" (or 1566f3fd488fSDimitry Andric // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an 15675ffd83dbSDimitry Andric // unsupported LLVMgold.so option and error. 1568f3fd488fSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) { 1569f3fd488fSDimitry Andric StringRef v(arg->getValue()); 157006c3fb27SDimitry Andric if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe")) 15715ffd83dbSDimitry Andric error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() + 15725ffd83dbSDimitry Andric "'"); 1573f3fd488fSDimitry Andric } 15740b57cec5SDimitry Andric 157581ad6265SDimitry Andric config->passPlugins = args::getStrings(args, OPT_load_pass_plugins); 157681ad6265SDimitry Andric 15770b57cec5SDimitry Andric // Parse -mllvm options. 1578bdd1243dSDimitry Andric for (const auto *arg : args.filtered(OPT_mllvm)) { 15790b57cec5SDimitry Andric parseClangOption(arg->getValue(), arg->getSpelling()); 1580bdd1243dSDimitry Andric config->mllvmOpts.emplace_back(arg->getValue()); 1581bdd1243dSDimitry Andric } 15820b57cec5SDimitry Andric 158306c3fb27SDimitry Andric config->ltoKind = LtoKind::Default; 158406c3fb27SDimitry Andric if (auto *arg = args.getLastArg(OPT_lto)) { 158506c3fb27SDimitry Andric StringRef s = arg->getValue(); 158606c3fb27SDimitry Andric if (s == "thin") 158706c3fb27SDimitry Andric config->ltoKind = LtoKind::UnifiedThin; 158806c3fb27SDimitry Andric else if (s == "full") 158906c3fb27SDimitry Andric config->ltoKind = LtoKind::UnifiedRegular; 159006c3fb27SDimitry Andric else if (s == "default") 159106c3fb27SDimitry Andric config->ltoKind = LtoKind::Default; 159206c3fb27SDimitry Andric else 159306c3fb27SDimitry Andric error("unknown LTO mode: " + s); 159406c3fb27SDimitry Andric } 159506c3fb27SDimitry Andric 15965ffd83dbSDimitry Andric // --threads= takes a positive integer and provides the default value for 159706c3fb27SDimitry Andric // --thinlto-jobs=. If unspecified, cap the number of threads since 159806c3fb27SDimitry Andric // overhead outweighs optimization for used parallel algorithms for the 159906c3fb27SDimitry Andric // non-LTO parts. 16005ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 16015ffd83dbSDimitry Andric StringRef v(arg->getValue()); 16025ffd83dbSDimitry Andric unsigned threads = 0; 16035ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 16045ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 16055ffd83dbSDimitry Andric arg->getValue() + "'"); 16065ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 16075ffd83dbSDimitry Andric config->thinLTOJobs = v; 160806c3fb27SDimitry Andric } else if (parallel::strategy.compute_thread_count() > 16) { 160906c3fb27SDimitry Andric log("set maximum concurrency to 16, specify --threads= to change"); 161006c3fb27SDimitry Andric parallel::strategy = hardware_concurrency(16); 16115ffd83dbSDimitry Andric } 1612bdd1243dSDimitry Andric if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq)) 16135ffd83dbSDimitry Andric config->thinLTOJobs = arg->getValue(); 1614bdd1243dSDimitry Andric config->threadCount = parallel::strategy.compute_thread_count(); 16155ffd83dbSDimitry Andric 16160b57cec5SDimitry Andric if (config->ltoPartitions == 0) 16170b57cec5SDimitry Andric error("--lto-partitions: number of threads must be > 0"); 16185ffd83dbSDimitry Andric if (!get_threadpool_strategy(config->thinLTOJobs)) 16195ffd83dbSDimitry Andric error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 16200b57cec5SDimitry Andric 16210b57cec5SDimitry Andric if (config->splitStackAdjustSize < 0) 16220b57cec5SDimitry Andric error("--split-stack-adjust-size: size must be >= 0"); 16230b57cec5SDimitry Andric 1624480093f4SDimitry Andric // The text segment is traditionally the first segment, whose address equals 1625480093f4SDimitry Andric // the base address. However, lld places the R PT_LOAD first. -Ttext-segment 1626480093f4SDimitry Andric // is an old-fashioned option that does not play well with lld's layout. 1627480093f4SDimitry Andric // Suggest --image-base as a likely alternative. 1628480093f4SDimitry Andric if (args.hasArg(OPT_Ttext_segment)) 1629480093f4SDimitry Andric error("-Ttext-segment is not supported. Use --image-base if you " 1630480093f4SDimitry Andric "intend to set the base address"); 1631480093f4SDimitry Andric 16320b57cec5SDimitry Andric // Parse ELF{32,64}{LE,BE} and CPU type. 16330b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_m)) { 16340b57cec5SDimitry Andric StringRef s = arg->getValue(); 16350b57cec5SDimitry Andric std::tie(config->ekind, config->emachine, config->osabi) = 16360b57cec5SDimitry Andric parseEmulation(s); 16370b57cec5SDimitry Andric config->mipsN32Abi = 163806c3fb27SDimitry Andric (s.starts_with("elf32btsmipn32") || s.starts_with("elf32ltsmipn32")); 16390b57cec5SDimitry Andric config->emulation = s; 16400b57cec5SDimitry Andric } 16410b57cec5SDimitry Andric 1642349cc55cSDimitry Andric // Parse --hash-style={sysv,gnu,both}. 16430b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_hash_style)) { 16440b57cec5SDimitry Andric StringRef s = arg->getValue(); 16450b57cec5SDimitry Andric if (s == "sysv") 16460b57cec5SDimitry Andric config->sysvHash = true; 16470b57cec5SDimitry Andric else if (s == "gnu") 16480b57cec5SDimitry Andric config->gnuHash = true; 16490b57cec5SDimitry Andric else if (s == "both") 16500b57cec5SDimitry Andric config->sysvHash = config->gnuHash = true; 16510b57cec5SDimitry Andric else 1652349cc55cSDimitry Andric error("unknown --hash-style: " + s); 16530b57cec5SDimitry Andric } 16540b57cec5SDimitry Andric 16550b57cec5SDimitry Andric if (args.hasArg(OPT_print_map)) 16560b57cec5SDimitry Andric config->mapFile = "-"; 16570b57cec5SDimitry Andric 16580b57cec5SDimitry Andric // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 16590b57cec5SDimitry Andric // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 1660*5f757f3fSDimitry Andric // it. Also disable RELRO for -r. 1661*5f757f3fSDimitry Andric if (config->nmagic || config->omagic || config->relocatable) 16620b57cec5SDimitry Andric config->zRelro = false; 16630b57cec5SDimitry Andric 16640b57cec5SDimitry Andric std::tie(config->buildId, config->buildIdVector) = getBuildId(args); 16650b57cec5SDimitry Andric 166681ad6265SDimitry Andric if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) { 166781ad6265SDimitry Andric config->relrGlibc = true; 166881ad6265SDimitry Andric config->relrPackDynRelocs = true; 166981ad6265SDimitry Andric } else { 16700b57cec5SDimitry Andric std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) = 16710b57cec5SDimitry Andric getPackDynRelocs(args); 167281ad6265SDimitry Andric } 16730b57cec5SDimitry Andric 16740b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){ 16750b57cec5SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 16760b57cec5SDimitry Andric error("--symbol-ordering-file and --call-graph-order-file " 16770b57cec5SDimitry Andric "may not be used together"); 1678bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) { 16790b57cec5SDimitry Andric config->symbolOrderingFile = getSymbolOrderingFile(*buffer); 16800b57cec5SDimitry Andric // Also need to disable CallGraphProfileSort to prevent 16810b57cec5SDimitry Andric // LLD order symbols with CGProfile 1682*5f757f3fSDimitry Andric config->callGraphProfileSort = CGProfileSortKind::None; 16830b57cec5SDimitry Andric } 16840b57cec5SDimitry Andric } 16850b57cec5SDimitry Andric 168685868e8aSDimitry Andric assert(config->versionDefinitions.empty()); 168785868e8aSDimitry Andric config->versionDefinitions.push_back( 16886e75b2fbSDimitry Andric {"local", (uint16_t)VER_NDX_LOCAL, {}, {}}); 16896e75b2fbSDimitry Andric config->versionDefinitions.push_back( 16906e75b2fbSDimitry Andric {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}}); 169185868e8aSDimitry Andric 16920b57cec5SDimitry Andric // If --retain-symbol-file is used, we'll keep only the symbols listed in 16930b57cec5SDimitry Andric // the file and discard all others. 16940b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) { 16956e75b2fbSDimitry Andric config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back( 169685868e8aSDimitry Andric {"*", /*isExternCpp=*/false, /*hasWildcard=*/true}); 1697bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 16980b57cec5SDimitry Andric for (StringRef s : args::getLines(*buffer)) 16996e75b2fbSDimitry Andric config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back( 170085868e8aSDimitry Andric {s, /*isExternCpp=*/false, /*hasWildcard=*/false}); 17010b57cec5SDimitry Andric } 17020b57cec5SDimitry Andric 17035ffd83dbSDimitry Andric for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) { 17045ffd83dbSDimitry Andric StringRef pattern(arg->getValue()); 17055ffd83dbSDimitry Andric if (Expected<GlobPattern> pat = GlobPattern::create(pattern)) 17065ffd83dbSDimitry Andric config->warnBackrefsExclude.push_back(std::move(*pat)); 17075ffd83dbSDimitry Andric else 1708*5f757f3fSDimitry Andric error(arg->getSpelling() + ": " + toString(pat.takeError()) + ": " + 1709*5f757f3fSDimitry Andric pattern); 17105ffd83dbSDimitry Andric } 17115ffd83dbSDimitry Andric 1712349cc55cSDimitry Andric // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols 1713349cc55cSDimitry Andric // which should be exported. For -shared, references to matched non-local 1714349cc55cSDimitry Andric // STV_DEFAULT symbols are not bound to definitions within the shared object, 1715349cc55cSDimitry Andric // even if other options express a symbolic intention: -Bsymbolic, 17165ffd83dbSDimitry Andric // -Bsymbolic-functions (if STT_FUNC), --dynamic-list. 17170b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export_dynamic_symbol)) 17180b57cec5SDimitry Andric config->dynamicList.push_back( 17195ffd83dbSDimitry Andric {arg->getValue(), /*isExternCpp=*/false, 17205ffd83dbSDimitry Andric /*hasWildcard=*/hasWildcard(arg->getValue())}); 17210b57cec5SDimitry Andric 1722349cc55cSDimitry Andric // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol 1723349cc55cSDimitry Andric // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic 1724349cc55cSDimitry Andric // like semantics. 1725349cc55cSDimitry Andric config->symbolic = 1726349cc55cSDimitry Andric config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list); 1727349cc55cSDimitry Andric for (auto *arg : 1728349cc55cSDimitry Andric args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list)) 1729bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1730349cc55cSDimitry Andric readDynamicList(*buffer); 1731349cc55cSDimitry Andric 17320b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_version_script)) 1733bdd1243dSDimitry Andric if (std::optional<std::string> path = searchScript(arg->getValue())) { 1734bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(*path)) 17350b57cec5SDimitry Andric readVersionScript(*buffer); 17360b57cec5SDimitry Andric } else { 17370b57cec5SDimitry Andric error(Twine("cannot find version script ") + arg->getValue()); 17380b57cec5SDimitry Andric } 17390b57cec5SDimitry Andric } 17400b57cec5SDimitry Andric 17410b57cec5SDimitry Andric // Some Config members do not directly correspond to any particular 17420b57cec5SDimitry Andric // command line options, but computed based on other Config values. 17430b57cec5SDimitry Andric // This function initialize such members. See Config.h for the details 17440b57cec5SDimitry Andric // of these values. 17450b57cec5SDimitry Andric static void setConfigs(opt::InputArgList &args) { 17460b57cec5SDimitry Andric ELFKind k = config->ekind; 17470b57cec5SDimitry Andric uint16_t m = config->emachine; 17480b57cec5SDimitry Andric 17490b57cec5SDimitry Andric config->copyRelocs = (config->relocatable || config->emitRelocs); 17500b57cec5SDimitry Andric config->is64 = (k == ELF64LEKind || k == ELF64BEKind); 17510b57cec5SDimitry Andric config->isLE = (k == ELF32LEKind || k == ELF64LEKind); 17520b57cec5SDimitry Andric config->endianness = config->isLE ? endianness::little : endianness::big; 17530b57cec5SDimitry Andric config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS); 17540b57cec5SDimitry Andric config->isPic = config->pie || config->shared; 17550b57cec5SDimitry Andric config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic); 17560b57cec5SDimitry Andric config->wordsize = config->is64 ? 8 : 4; 17570b57cec5SDimitry Andric 17580b57cec5SDimitry Andric // ELF defines two different ways to store relocation addends as shown below: 17590b57cec5SDimitry Andric // 17605ffd83dbSDimitry Andric // Rel: Addends are stored to the location where relocations are applied. It 17615ffd83dbSDimitry Andric // cannot pack the full range of addend values for all relocation types, but 17625ffd83dbSDimitry Andric // this only affects relocation types that we don't support emitting as 17635ffd83dbSDimitry Andric // dynamic relocations (see getDynRel). 17640b57cec5SDimitry Andric // Rela: Addends are stored as part of relocation entry. 17650b57cec5SDimitry Andric // 17660b57cec5SDimitry Andric // In other words, Rela makes it easy to read addends at the price of extra 17675ffd83dbSDimitry Andric // 4 or 8 byte for each relocation entry. 17680b57cec5SDimitry Andric // 17695ffd83dbSDimitry Andric // We pick the format for dynamic relocations according to the psABI for each 17705ffd83dbSDimitry Andric // processor, but a contrary choice can be made if the dynamic loader 17715ffd83dbSDimitry Andric // supports. 17725ffd83dbSDimitry Andric config->isRela = getIsRela(args); 17730b57cec5SDimitry Andric 17740b57cec5SDimitry Andric // If the output uses REL relocations we must store the dynamic relocation 17750b57cec5SDimitry Andric // addends to the output sections. We also store addends for RELA relocations 17760b57cec5SDimitry Andric // if --apply-dynamic-relocs is used. 17770b57cec5SDimitry Andric // We default to not writing the addends when using RELA relocations since 17780b57cec5SDimitry Andric // any standard conforming tool can find it in r_addend. 17790b57cec5SDimitry Andric config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs, 17800b57cec5SDimitry Andric OPT_no_apply_dynamic_relocs, false) || 17810b57cec5SDimitry Andric !config->isRela; 1782fe6060f1SDimitry Andric // Validation of dynamic relocation addends is on by default for assertions 1783*5f757f3fSDimitry Andric // builds and disabled otherwise. This check is enabled when writeAddends is 1784*5f757f3fSDimitry Andric // true. 1785fe6060f1SDimitry Andric #ifndef NDEBUG 1786*5f757f3fSDimitry Andric bool checkDynamicRelocsDefault = true; 1787fe6060f1SDimitry Andric #else 1788fe6060f1SDimitry Andric bool checkDynamicRelocsDefault = false; 1789fe6060f1SDimitry Andric #endif 1790fe6060f1SDimitry Andric config->checkDynamicRelocs = 1791fe6060f1SDimitry Andric args.hasFlag(OPT_check_dynamic_relocations, 1792fe6060f1SDimitry Andric OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault); 17930b57cec5SDimitry Andric config->tocOptimize = 17940b57cec5SDimitry Andric args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64); 1795e8d8bef9SDimitry Andric config->pcRelOptimize = 1796e8d8bef9SDimitry Andric args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64); 17970b57cec5SDimitry Andric } 17980b57cec5SDimitry Andric 17990b57cec5SDimitry Andric static bool isFormatBinary(StringRef s) { 18000b57cec5SDimitry Andric if (s == "binary") 18010b57cec5SDimitry Andric return true; 18020b57cec5SDimitry Andric if (s == "elf" || s == "default") 18030b57cec5SDimitry Andric return false; 1804349cc55cSDimitry Andric error("unknown --format value: " + s + 18050b57cec5SDimitry Andric " (supported formats: elf, default, binary)"); 18060b57cec5SDimitry Andric return false; 18070b57cec5SDimitry Andric } 18080b57cec5SDimitry Andric 18090b57cec5SDimitry Andric void LinkerDriver::createFiles(opt::InputArgList &args) { 1810e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Load input files"); 18110b57cec5SDimitry Andric // For --{push,pop}-state. 18120b57cec5SDimitry Andric std::vector<std::tuple<bool, bool, bool>> stack; 18130b57cec5SDimitry Andric 18140b57cec5SDimitry Andric // Iterate over argv to process input files and positional arguments. 1815e8d8bef9SDimitry Andric InputFile::isInGroup = false; 181681ad6265SDimitry Andric bool hasInput = false; 18170b57cec5SDimitry Andric for (auto *arg : args) { 18180b57cec5SDimitry Andric switch (arg->getOption().getID()) { 18190b57cec5SDimitry Andric case OPT_library: 18200b57cec5SDimitry Andric addLibrary(arg->getValue()); 182181ad6265SDimitry Andric hasInput = true; 18220b57cec5SDimitry Andric break; 18230b57cec5SDimitry Andric case OPT_INPUT: 18240b57cec5SDimitry Andric addFile(arg->getValue(), /*withLOption=*/false); 182581ad6265SDimitry Andric hasInput = true; 18260b57cec5SDimitry Andric break; 18270b57cec5SDimitry Andric case OPT_defsym: { 18280b57cec5SDimitry Andric StringRef from; 18290b57cec5SDimitry Andric StringRef to; 18300b57cec5SDimitry Andric std::tie(from, to) = StringRef(arg->getValue()).split('='); 18310b57cec5SDimitry Andric if (from.empty() || to.empty()) 1832349cc55cSDimitry Andric error("--defsym: syntax error: " + StringRef(arg->getValue())); 18330b57cec5SDimitry Andric else 1834349cc55cSDimitry Andric readDefsym(from, MemoryBufferRef(to, "--defsym")); 18350b57cec5SDimitry Andric break; 18360b57cec5SDimitry Andric } 18370b57cec5SDimitry Andric case OPT_script: 1838bdd1243dSDimitry Andric if (std::optional<std::string> path = searchScript(arg->getValue())) { 1839bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> mb = readFile(*path)) 18400b57cec5SDimitry Andric readLinkerScript(*mb); 18410b57cec5SDimitry Andric break; 18420b57cec5SDimitry Andric } 18430b57cec5SDimitry Andric error(Twine("cannot find linker script ") + arg->getValue()); 18440b57cec5SDimitry Andric break; 18450b57cec5SDimitry Andric case OPT_as_needed: 18460b57cec5SDimitry Andric config->asNeeded = true; 18470b57cec5SDimitry Andric break; 18480b57cec5SDimitry Andric case OPT_format: 18490b57cec5SDimitry Andric config->formatBinary = isFormatBinary(arg->getValue()); 18500b57cec5SDimitry Andric break; 18510b57cec5SDimitry Andric case OPT_no_as_needed: 18520b57cec5SDimitry Andric config->asNeeded = false; 18530b57cec5SDimitry Andric break; 18540b57cec5SDimitry Andric case OPT_Bstatic: 18550b57cec5SDimitry Andric case OPT_omagic: 18560b57cec5SDimitry Andric case OPT_nmagic: 18570b57cec5SDimitry Andric config->isStatic = true; 18580b57cec5SDimitry Andric break; 18590b57cec5SDimitry Andric case OPT_Bdynamic: 18600b57cec5SDimitry Andric config->isStatic = false; 18610b57cec5SDimitry Andric break; 18620b57cec5SDimitry Andric case OPT_whole_archive: 18630b57cec5SDimitry Andric inWholeArchive = true; 18640b57cec5SDimitry Andric break; 18650b57cec5SDimitry Andric case OPT_no_whole_archive: 18660b57cec5SDimitry Andric inWholeArchive = false; 18670b57cec5SDimitry Andric break; 18680b57cec5SDimitry Andric case OPT_just_symbols: 1869bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) { 1870fcaf7f86SDimitry Andric files.push_back(createObjFile(*mb)); 18710b57cec5SDimitry Andric files.back()->justSymbols = true; 18720b57cec5SDimitry Andric } 18730b57cec5SDimitry Andric break; 187406c3fb27SDimitry Andric case OPT_in_implib: 187506c3fb27SDimitry Andric if (armCmseImpLib) 187606c3fb27SDimitry Andric error("multiple CMSE import libraries not supported"); 187706c3fb27SDimitry Andric else if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) 187806c3fb27SDimitry Andric armCmseImpLib = createObjFile(*mb); 187906c3fb27SDimitry Andric break; 18800b57cec5SDimitry Andric case OPT_start_group: 18810b57cec5SDimitry Andric if (InputFile::isInGroup) 18820b57cec5SDimitry Andric error("nested --start-group"); 18830b57cec5SDimitry Andric InputFile::isInGroup = true; 18840b57cec5SDimitry Andric break; 18850b57cec5SDimitry Andric case OPT_end_group: 18860b57cec5SDimitry Andric if (!InputFile::isInGroup) 18870b57cec5SDimitry Andric error("stray --end-group"); 18880b57cec5SDimitry Andric InputFile::isInGroup = false; 18890b57cec5SDimitry Andric ++InputFile::nextGroupId; 18900b57cec5SDimitry Andric break; 18910b57cec5SDimitry Andric case OPT_start_lib: 18920b57cec5SDimitry Andric if (inLib) 18930b57cec5SDimitry Andric error("nested --start-lib"); 18940b57cec5SDimitry Andric if (InputFile::isInGroup) 18950b57cec5SDimitry Andric error("may not nest --start-lib in --start-group"); 18960b57cec5SDimitry Andric inLib = true; 18970b57cec5SDimitry Andric InputFile::isInGroup = true; 18980b57cec5SDimitry Andric break; 18990b57cec5SDimitry Andric case OPT_end_lib: 19000b57cec5SDimitry Andric if (!inLib) 19010b57cec5SDimitry Andric error("stray --end-lib"); 19020b57cec5SDimitry Andric inLib = false; 19030b57cec5SDimitry Andric InputFile::isInGroup = false; 19040b57cec5SDimitry Andric ++InputFile::nextGroupId; 19050b57cec5SDimitry Andric break; 19060b57cec5SDimitry Andric case OPT_push_state: 19070b57cec5SDimitry Andric stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive); 19080b57cec5SDimitry Andric break; 19090b57cec5SDimitry Andric case OPT_pop_state: 19100b57cec5SDimitry Andric if (stack.empty()) { 19110b57cec5SDimitry Andric error("unbalanced --push-state/--pop-state"); 19120b57cec5SDimitry Andric break; 19130b57cec5SDimitry Andric } 19140b57cec5SDimitry Andric std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back(); 19150b57cec5SDimitry Andric stack.pop_back(); 19160b57cec5SDimitry Andric break; 19170b57cec5SDimitry Andric } 19180b57cec5SDimitry Andric } 19190b57cec5SDimitry Andric 192081ad6265SDimitry Andric if (files.empty() && !hasInput && errorCount() == 0) 19210b57cec5SDimitry Andric error("no input files"); 19220b57cec5SDimitry Andric } 19230b57cec5SDimitry Andric 19240b57cec5SDimitry Andric // If -m <machine_type> was not given, infer it from object files. 19250b57cec5SDimitry Andric void LinkerDriver::inferMachineType() { 19260b57cec5SDimitry Andric if (config->ekind != ELFNoneKind) 19270b57cec5SDimitry Andric return; 19280b57cec5SDimitry Andric 19290b57cec5SDimitry Andric for (InputFile *f : files) { 19300b57cec5SDimitry Andric if (f->ekind == ELFNoneKind) 19310b57cec5SDimitry Andric continue; 19320b57cec5SDimitry Andric config->ekind = f->ekind; 19330b57cec5SDimitry Andric config->emachine = f->emachine; 19340b57cec5SDimitry Andric config->osabi = f->osabi; 19350b57cec5SDimitry Andric config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f); 19360b57cec5SDimitry Andric return; 19370b57cec5SDimitry Andric } 19380b57cec5SDimitry Andric error("target emulation unknown: -m or at least one .o file required"); 19390b57cec5SDimitry Andric } 19400b57cec5SDimitry Andric 19410b57cec5SDimitry Andric // Parse -z max-page-size=<value>. The default value is defined by 19420b57cec5SDimitry Andric // each target. 19430b57cec5SDimitry Andric static uint64_t getMaxPageSize(opt::InputArgList &args) { 19440b57cec5SDimitry Andric uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size", 19450b57cec5SDimitry Andric target->defaultMaxPageSize); 1946972a253aSDimitry Andric if (!isPowerOf2_64(val)) { 19470b57cec5SDimitry Andric error("max-page-size: value isn't a power of 2"); 1948972a253aSDimitry Andric return target->defaultMaxPageSize; 1949972a253aSDimitry Andric } 19500b57cec5SDimitry Andric if (config->nmagic || config->omagic) { 19510b57cec5SDimitry Andric if (val != target->defaultMaxPageSize) 19520b57cec5SDimitry Andric warn("-z max-page-size set, but paging disabled by omagic or nmagic"); 19530b57cec5SDimitry Andric return 1; 19540b57cec5SDimitry Andric } 19550b57cec5SDimitry Andric return val; 19560b57cec5SDimitry Andric } 19570b57cec5SDimitry Andric 19580b57cec5SDimitry Andric // Parse -z common-page-size=<value>. The default value is defined by 19590b57cec5SDimitry Andric // each target. 19600b57cec5SDimitry Andric static uint64_t getCommonPageSize(opt::InputArgList &args) { 19610b57cec5SDimitry Andric uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size", 19620b57cec5SDimitry Andric target->defaultCommonPageSize); 1963972a253aSDimitry Andric if (!isPowerOf2_64(val)) { 19640b57cec5SDimitry Andric error("common-page-size: value isn't a power of 2"); 1965972a253aSDimitry Andric return target->defaultCommonPageSize; 1966972a253aSDimitry Andric } 19670b57cec5SDimitry Andric if (config->nmagic || config->omagic) { 19680b57cec5SDimitry Andric if (val != target->defaultCommonPageSize) 19690b57cec5SDimitry Andric warn("-z common-page-size set, but paging disabled by omagic or nmagic"); 19700b57cec5SDimitry Andric return 1; 19710b57cec5SDimitry Andric } 19720b57cec5SDimitry Andric // commonPageSize can't be larger than maxPageSize. 19730b57cec5SDimitry Andric if (val > config->maxPageSize) 19740b57cec5SDimitry Andric val = config->maxPageSize; 19750b57cec5SDimitry Andric return val; 19760b57cec5SDimitry Andric } 19770b57cec5SDimitry Andric 1978349cc55cSDimitry Andric // Parses --image-base option. 1979bdd1243dSDimitry Andric static std::optional<uint64_t> getImageBase(opt::InputArgList &args) { 19800b57cec5SDimitry Andric // Because we are using "Config->maxPageSize" here, this function has to be 19810b57cec5SDimitry Andric // called after the variable is initialized. 19820b57cec5SDimitry Andric auto *arg = args.getLastArg(OPT_image_base); 19830b57cec5SDimitry Andric if (!arg) 1984bdd1243dSDimitry Andric return std::nullopt; 19850b57cec5SDimitry Andric 19860b57cec5SDimitry Andric StringRef s = arg->getValue(); 19870b57cec5SDimitry Andric uint64_t v; 19880b57cec5SDimitry Andric if (!to_integer(s, v)) { 1989349cc55cSDimitry Andric error("--image-base: number expected, but got " + s); 19900b57cec5SDimitry Andric return 0; 19910b57cec5SDimitry Andric } 19920b57cec5SDimitry Andric if ((v % config->maxPageSize) != 0) 1993349cc55cSDimitry Andric warn("--image-base: address isn't multiple of page size: " + s); 19940b57cec5SDimitry Andric return v; 19950b57cec5SDimitry Andric } 19960b57cec5SDimitry Andric 19970b57cec5SDimitry Andric // Parses `--exclude-libs=lib,lib,...`. 19980b57cec5SDimitry Andric // The library names may be delimited by commas or colons. 19990b57cec5SDimitry Andric static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) { 20000b57cec5SDimitry Andric DenseSet<StringRef> ret; 20010b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_exclude_libs)) { 20020b57cec5SDimitry Andric StringRef s = arg->getValue(); 20030b57cec5SDimitry Andric for (;;) { 20040b57cec5SDimitry Andric size_t pos = s.find_first_of(",:"); 20050b57cec5SDimitry Andric if (pos == StringRef::npos) 20060b57cec5SDimitry Andric break; 20070b57cec5SDimitry Andric ret.insert(s.substr(0, pos)); 20080b57cec5SDimitry Andric s = s.substr(pos + 1); 20090b57cec5SDimitry Andric } 20100b57cec5SDimitry Andric ret.insert(s); 20110b57cec5SDimitry Andric } 20120b57cec5SDimitry Andric return ret; 20130b57cec5SDimitry Andric } 20140b57cec5SDimitry Andric 2015349cc55cSDimitry Andric // Handles the --exclude-libs option. If a static library file is specified 2016349cc55cSDimitry Andric // by the --exclude-libs option, all public symbols from the archive become 20170b57cec5SDimitry Andric // private unless otherwise specified by version scripts or something. 20180b57cec5SDimitry Andric // A special library name "ALL" means all archive files. 20190b57cec5SDimitry Andric // 20200b57cec5SDimitry Andric // This is not a popular option, but some programs such as bionic libc use it. 20210b57cec5SDimitry Andric static void excludeLibs(opt::InputArgList &args) { 20220b57cec5SDimitry Andric DenseSet<StringRef> libs = getExcludeLibs(args); 20230b57cec5SDimitry Andric bool all = libs.count("ALL"); 20240b57cec5SDimitry Andric 20250b57cec5SDimitry Andric auto visit = [&](InputFile *file) { 202681ad6265SDimitry Andric if (file->archiveName.empty() || 202781ad6265SDimitry Andric !(all || libs.count(path::filename(file->archiveName)))) 202881ad6265SDimitry Andric return; 202981ad6265SDimitry Andric ArrayRef<Symbol *> symbols = file->getSymbols(); 203081ad6265SDimitry Andric if (isa<ELFFileBase>(file)) 203181ad6265SDimitry Andric symbols = cast<ELFFileBase>(file)->getGlobalSymbols(); 203281ad6265SDimitry Andric for (Symbol *sym : symbols) 203381ad6265SDimitry Andric if (!sym->isUndefined() && sym->file == file) 20340b57cec5SDimitry Andric sym->versionId = VER_NDX_LOCAL; 20350b57cec5SDimitry Andric }; 20360b57cec5SDimitry Andric 2037bdd1243dSDimitry Andric for (ELFFileBase *file : ctx.objectFiles) 20380b57cec5SDimitry Andric visit(file); 20390b57cec5SDimitry Andric 2040bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.bitcodeFiles) 20410b57cec5SDimitry Andric visit(file); 20420b57cec5SDimitry Andric } 20430b57cec5SDimitry Andric 20445ffd83dbSDimitry Andric // Force Sym to be entered in the output. 2045349cc55cSDimitry Andric static void handleUndefined(Symbol *sym, const char *option) { 20460b57cec5SDimitry Andric // Since a symbol may not be used inside the program, LTO may 20470b57cec5SDimitry Andric // eliminate it. Mark the symbol as "used" to prevent it. 20480b57cec5SDimitry Andric sym->isUsedInRegularObj = true; 20490b57cec5SDimitry Andric 2050349cc55cSDimitry Andric if (!sym->isLazy()) 2051349cc55cSDimitry Andric return; 20524824e7fdSDimitry Andric sym->extract(); 2053349cc55cSDimitry Andric if (!config->whyExtract.empty()) 2054bdd1243dSDimitry Andric ctx.whyExtractRecords.emplace_back(option, sym->file, *sym); 20550b57cec5SDimitry Andric } 20560b57cec5SDimitry Andric 2057480093f4SDimitry Andric // As an extension to GNU linkers, lld supports a variant of `-u` 20580b57cec5SDimitry Andric // which accepts wildcard patterns. All symbols that match a given 20590b57cec5SDimitry Andric // pattern are handled as if they were given by `-u`. 20600b57cec5SDimitry Andric static void handleUndefinedGlob(StringRef arg) { 20610b57cec5SDimitry Andric Expected<GlobPattern> pat = GlobPattern::create(arg); 20620b57cec5SDimitry Andric if (!pat) { 2063*5f757f3fSDimitry Andric error("--undefined-glob: " + toString(pat.takeError()) + ": " + arg); 20640b57cec5SDimitry Andric return; 20650b57cec5SDimitry Andric } 20660b57cec5SDimitry Andric 20674824e7fdSDimitry Andric // Calling sym->extract() in the loop is not safe because it may add new 20684824e7fdSDimitry Andric // symbols to the symbol table, invalidating the current iterator. 20691fd87a68SDimitry Andric SmallVector<Symbol *, 0> syms; 2070bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols()) 207104eeddc0SDimitry Andric if (!sym->isPlaceholder() && pat->match(sym->getName())) 20720b57cec5SDimitry Andric syms.push_back(sym); 20730b57cec5SDimitry Andric 20740b57cec5SDimitry Andric for (Symbol *sym : syms) 2075349cc55cSDimitry Andric handleUndefined(sym, "--undefined-glob"); 20760b57cec5SDimitry Andric } 20770b57cec5SDimitry Andric 20780b57cec5SDimitry Andric static void handleLibcall(StringRef name) { 2079bdd1243dSDimitry Andric Symbol *sym = symtab.find(name); 20800b57cec5SDimitry Andric if (!sym || !sym->isLazy()) 20810b57cec5SDimitry Andric return; 20820b57cec5SDimitry Andric 20830b57cec5SDimitry Andric MemoryBufferRef mb; 208481ad6265SDimitry Andric mb = cast<LazyObject>(sym)->file->mb; 20850b57cec5SDimitry Andric 20860b57cec5SDimitry Andric if (isBitcode(mb)) 20874824e7fdSDimitry Andric sym->extract(); 20880b57cec5SDimitry Andric } 20890b57cec5SDimitry Andric 209081ad6265SDimitry Andric static void writeArchiveStats() { 209181ad6265SDimitry Andric if (config->printArchiveStats.empty()) 209281ad6265SDimitry Andric return; 209381ad6265SDimitry Andric 209481ad6265SDimitry Andric std::error_code ec; 209506c3fb27SDimitry Andric raw_fd_ostream os = ctx.openAuxiliaryFile(config->printArchiveStats, ec); 209681ad6265SDimitry Andric if (ec) { 209781ad6265SDimitry Andric error("--print-archive-stats=: cannot open " + config->printArchiveStats + 209881ad6265SDimitry Andric ": " + ec.message()); 209981ad6265SDimitry Andric return; 210081ad6265SDimitry Andric } 210181ad6265SDimitry Andric 210281ad6265SDimitry Andric os << "members\textracted\tarchive\n"; 210381ad6265SDimitry Andric 210481ad6265SDimitry Andric SmallVector<StringRef, 0> archives; 210581ad6265SDimitry Andric DenseMap<CachedHashStringRef, unsigned> all, extracted; 2106bdd1243dSDimitry Andric for (ELFFileBase *file : ctx.objectFiles) 210781ad6265SDimitry Andric if (file->archiveName.size()) 210881ad6265SDimitry Andric ++extracted[CachedHashStringRef(file->archiveName)]; 2109bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.bitcodeFiles) 211081ad6265SDimitry Andric if (file->archiveName.size()) 211181ad6265SDimitry Andric ++extracted[CachedHashStringRef(file->archiveName)]; 2112bdd1243dSDimitry Andric for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) { 211381ad6265SDimitry Andric unsigned &v = extracted[CachedHashString(f.first)]; 211481ad6265SDimitry Andric os << f.second << '\t' << v << '\t' << f.first << '\n'; 211581ad6265SDimitry Andric // If the archive occurs multiple times, other instances have a count of 0. 211681ad6265SDimitry Andric v = 0; 211781ad6265SDimitry Andric } 211881ad6265SDimitry Andric } 211981ad6265SDimitry Andric 212081ad6265SDimitry Andric static void writeWhyExtract() { 212181ad6265SDimitry Andric if (config->whyExtract.empty()) 212281ad6265SDimitry Andric return; 212381ad6265SDimitry Andric 212481ad6265SDimitry Andric std::error_code ec; 212506c3fb27SDimitry Andric raw_fd_ostream os = ctx.openAuxiliaryFile(config->whyExtract, ec); 212681ad6265SDimitry Andric if (ec) { 212781ad6265SDimitry Andric error("cannot open --why-extract= file " + config->whyExtract + ": " + 212881ad6265SDimitry Andric ec.message()); 212981ad6265SDimitry Andric return; 213081ad6265SDimitry Andric } 213181ad6265SDimitry Andric 213281ad6265SDimitry Andric os << "reference\textracted\tsymbol\n"; 2133bdd1243dSDimitry Andric for (auto &entry : ctx.whyExtractRecords) { 213481ad6265SDimitry Andric os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t' 213581ad6265SDimitry Andric << toString(std::get<2>(entry)) << '\n'; 213681ad6265SDimitry Andric } 213781ad6265SDimitry Andric } 213881ad6265SDimitry Andric 213981ad6265SDimitry Andric static void reportBackrefs() { 2140bdd1243dSDimitry Andric for (auto &ref : ctx.backwardReferences) { 214181ad6265SDimitry Andric const Symbol &sym = *ref.first; 214281ad6265SDimitry Andric std::string to = toString(ref.second.second); 214381ad6265SDimitry Andric // Some libraries have known problems and can cause noise. Filter them out 214481ad6265SDimitry Andric // with --warn-backrefs-exclude=. The value may look like (for --start-lib) 214581ad6265SDimitry Andric // *.o or (archive member) *.a(*.o). 214681ad6265SDimitry Andric bool exclude = false; 214781ad6265SDimitry Andric for (const llvm::GlobPattern &pat : config->warnBackrefsExclude) 214881ad6265SDimitry Andric if (pat.match(to)) { 214981ad6265SDimitry Andric exclude = true; 215081ad6265SDimitry Andric break; 215181ad6265SDimitry Andric } 215281ad6265SDimitry Andric if (!exclude) 215381ad6265SDimitry Andric warn("backward reference detected: " + sym.getName() + " in " + 215481ad6265SDimitry Andric toString(ref.second.first) + " refers to " + to); 215581ad6265SDimitry Andric } 215681ad6265SDimitry Andric } 215781ad6265SDimitry Andric 2158e8d8bef9SDimitry Andric // Handle --dependency-file=<path>. If that option is given, lld creates a 2159e8d8bef9SDimitry Andric // file at a given path with the following contents: 2160e8d8bef9SDimitry Andric // 2161e8d8bef9SDimitry Andric // <output-file>: <input-file> ... 2162e8d8bef9SDimitry Andric // 2163e8d8bef9SDimitry Andric // <input-file>: 2164e8d8bef9SDimitry Andric // 2165e8d8bef9SDimitry Andric // where <output-file> is a pathname of an output file and <input-file> 2166e8d8bef9SDimitry Andric // ... is a list of pathnames of all input files. `make` command can read a 2167e8d8bef9SDimitry Andric // file in the above format and interpret it as a dependency info. We write 2168e8d8bef9SDimitry Andric // phony targets for every <input-file> to avoid an error when that file is 2169e8d8bef9SDimitry Andric // removed. 2170e8d8bef9SDimitry Andric // 2171e8d8bef9SDimitry Andric // This option is useful if you want to make your final executable to depend 2172e8d8bef9SDimitry Andric // on all input files including system libraries. Here is why. 2173e8d8bef9SDimitry Andric // 2174e8d8bef9SDimitry Andric // When you write a Makefile, you usually write it so that the final 2175e8d8bef9SDimitry Andric // executable depends on all user-generated object files. Normally, you 2176e8d8bef9SDimitry Andric // don't make your executable to depend on system libraries (such as libc) 2177e8d8bef9SDimitry Andric // because you don't know the exact paths of libraries, even though system 2178e8d8bef9SDimitry Andric // libraries that are linked to your executable statically are technically a 2179e8d8bef9SDimitry Andric // part of your program. By using --dependency-file option, you can make 2180e8d8bef9SDimitry Andric // lld to dump dependency info so that you can maintain exact dependencies 2181e8d8bef9SDimitry Andric // easily. 2182e8d8bef9SDimitry Andric static void writeDependencyFile() { 2183e8d8bef9SDimitry Andric std::error_code ec; 218406c3fb27SDimitry Andric raw_fd_ostream os = ctx.openAuxiliaryFile(config->dependencyFile, ec); 2185e8d8bef9SDimitry Andric if (ec) { 2186e8d8bef9SDimitry Andric error("cannot open " + config->dependencyFile + ": " + ec.message()); 2187e8d8bef9SDimitry Andric return; 2188e8d8bef9SDimitry Andric } 2189e8d8bef9SDimitry Andric 2190e8d8bef9SDimitry Andric // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja: 2191e8d8bef9SDimitry Andric // * A space is escaped by a backslash which itself must be escaped. 2192e8d8bef9SDimitry Andric // * A hash sign is escaped by a single backslash. 2193e8d8bef9SDimitry Andric // * $ is escapes as $$. 2194e8d8bef9SDimitry Andric auto printFilename = [](raw_fd_ostream &os, StringRef filename) { 2195e8d8bef9SDimitry Andric llvm::SmallString<256> nativePath; 2196e8d8bef9SDimitry Andric llvm::sys::path::native(filename.str(), nativePath); 2197e8d8bef9SDimitry Andric llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true); 2198e8d8bef9SDimitry Andric for (unsigned i = 0, e = nativePath.size(); i != e; ++i) { 2199e8d8bef9SDimitry Andric if (nativePath[i] == '#') { 2200e8d8bef9SDimitry Andric os << '\\'; 2201e8d8bef9SDimitry Andric } else if (nativePath[i] == ' ') { 2202e8d8bef9SDimitry Andric os << '\\'; 2203e8d8bef9SDimitry Andric unsigned j = i; 2204e8d8bef9SDimitry Andric while (j > 0 && nativePath[--j] == '\\') 2205e8d8bef9SDimitry Andric os << '\\'; 2206e8d8bef9SDimitry Andric } else if (nativePath[i] == '$') { 2207e8d8bef9SDimitry Andric os << '$'; 2208e8d8bef9SDimitry Andric } 2209e8d8bef9SDimitry Andric os << nativePath[i]; 2210e8d8bef9SDimitry Andric } 2211e8d8bef9SDimitry Andric }; 2212e8d8bef9SDimitry Andric 2213e8d8bef9SDimitry Andric os << config->outputFile << ":"; 2214e8d8bef9SDimitry Andric for (StringRef path : config->dependencyFiles) { 2215e8d8bef9SDimitry Andric os << " \\\n "; 2216e8d8bef9SDimitry Andric printFilename(os, path); 2217e8d8bef9SDimitry Andric } 2218e8d8bef9SDimitry Andric os << "\n"; 2219e8d8bef9SDimitry Andric 2220e8d8bef9SDimitry Andric for (StringRef path : config->dependencyFiles) { 2221e8d8bef9SDimitry Andric os << "\n"; 2222e8d8bef9SDimitry Andric printFilename(os, path); 2223e8d8bef9SDimitry Andric os << ":\n"; 2224e8d8bef9SDimitry Andric } 2225e8d8bef9SDimitry Andric } 2226e8d8bef9SDimitry Andric 22270b57cec5SDimitry Andric // Replaces common symbols with defined symbols reside in .bss sections. 22280b57cec5SDimitry Andric // This function is called after all symbol names are resolved. As a 22290b57cec5SDimitry Andric // result, the passes after the symbol resolution won't see any 22300b57cec5SDimitry Andric // symbols of type CommonSymbol. 22310b57cec5SDimitry Andric static void replaceCommonSymbols() { 2232e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Replace common symbols"); 2233bdd1243dSDimitry Andric for (ELFFileBase *file : ctx.objectFiles) { 22340eae32dcSDimitry Andric if (!file->hasCommonSyms) 22350eae32dcSDimitry Andric continue; 22360eae32dcSDimitry Andric for (Symbol *sym : file->getGlobalSymbols()) { 22370b57cec5SDimitry Andric auto *s = dyn_cast<CommonSymbol>(sym); 22380b57cec5SDimitry Andric if (!s) 2239480093f4SDimitry Andric continue; 22400b57cec5SDimitry Andric 22410b57cec5SDimitry Andric auto *bss = make<BssSection>("COMMON", s->size, s->alignment); 22420b57cec5SDimitry Andric bss->file = s->file; 2243bdd1243dSDimitry Andric ctx.inputSections.push_back(bss); 2244bdd1243dSDimitry Andric Defined(s->file, StringRef(), s->binding, s->stOther, s->type, 2245bdd1243dSDimitry Andric /*value=*/0, s->size, bss) 2246bdd1243dSDimitry Andric .overwrite(*s); 2247480093f4SDimitry Andric } 22480b57cec5SDimitry Andric } 22490eae32dcSDimitry Andric } 22500b57cec5SDimitry Andric 22510b57cec5SDimitry Andric // The section referred to by `s` is considered address-significant. Set the 22520b57cec5SDimitry Andric // keepUnique flag on the section if appropriate. 22530b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 22540b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 22550b57cec5SDimitry Andric if (d->section) 22560b57cec5SDimitry Andric // We don't need to keep text sections unique under --icf=all even if they 22570b57cec5SDimitry Andric // are address-significant. 22580b57cec5SDimitry Andric if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR)) 22590b57cec5SDimitry Andric d->section->keepUnique = true; 22600b57cec5SDimitry Andric } 22610b57cec5SDimitry Andric 22620b57cec5SDimitry Andric // Record sections that define symbols mentioned in --keep-unique <symbol> 22630b57cec5SDimitry Andric // and symbols referred to by address-significance tables. These sections are 22640b57cec5SDimitry Andric // ineligible for ICF. 22650b57cec5SDimitry Andric template <class ELFT> 22660b57cec5SDimitry Andric static void findKeepUniqueSections(opt::InputArgList &args) { 22670b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_keep_unique)) { 22680b57cec5SDimitry Andric StringRef name = arg->getValue(); 2269bdd1243dSDimitry Andric auto *d = dyn_cast_or_null<Defined>(symtab.find(name)); 22700b57cec5SDimitry Andric if (!d || !d->section) { 22710b57cec5SDimitry Andric warn("could not find symbol " + name + " to keep unique"); 22720b57cec5SDimitry Andric continue; 22730b57cec5SDimitry Andric } 22740b57cec5SDimitry Andric d->section->keepUnique = true; 22750b57cec5SDimitry Andric } 22760b57cec5SDimitry Andric 22770b57cec5SDimitry Andric // --icf=all --ignore-data-address-equality means that we can ignore 22780b57cec5SDimitry Andric // the dynsym and address-significance tables entirely. 22790b57cec5SDimitry Andric if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality) 22800b57cec5SDimitry Andric return; 22810b57cec5SDimitry Andric 22820b57cec5SDimitry Andric // Symbols in the dynsym could be address-significant in other executables 22830b57cec5SDimitry Andric // or DSOs, so we conservatively mark them as address-significant. 2284bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols()) 22850b57cec5SDimitry Andric if (sym->includeInDynsym()) 22860b57cec5SDimitry Andric markAddrsig(sym); 22870b57cec5SDimitry Andric 22880b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 22890b57cec5SDimitry Andric // referenced symbol as address-significant. 2290bdd1243dSDimitry Andric for (InputFile *f : ctx.objectFiles) { 22910b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(f); 22920b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 22930b57cec5SDimitry Andric if (obj->addrsigSec) { 22940b57cec5SDimitry Andric ArrayRef<uint8_t> contents = 2295e8d8bef9SDimitry Andric check(obj->getObj().getSectionContents(*obj->addrsigSec)); 22960b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 22970b57cec5SDimitry Andric while (cur != contents.end()) { 22980b57cec5SDimitry Andric unsigned size; 2299*5f757f3fSDimitry Andric const char *err = nullptr; 23000b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 23010b57cec5SDimitry Andric if (err) 23020b57cec5SDimitry Andric fatal(toString(f) + ": could not decode addrsig section: " + err); 23030b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 23040b57cec5SDimitry Andric cur += size; 23050b57cec5SDimitry Andric } 23060b57cec5SDimitry Andric } else { 23070b57cec5SDimitry Andric // If an object file does not have an address-significance table, 23080b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 23090b57cec5SDimitry Andric for (Symbol *s : syms) 23100b57cec5SDimitry Andric markAddrsig(s); 23110b57cec5SDimitry Andric } 23120b57cec5SDimitry Andric } 23130b57cec5SDimitry Andric } 23140b57cec5SDimitry Andric 23150b57cec5SDimitry Andric // This function reads a symbol partition specification section. These sections 23160b57cec5SDimitry Andric // are used to control which partition a symbol is allocated to. See 23170b57cec5SDimitry Andric // https://lld.llvm.org/Partitions.html for more details on partitions. 23180b57cec5SDimitry Andric template <typename ELFT> 23190b57cec5SDimitry Andric static void readSymbolPartitionSection(InputSectionBase *s) { 23200b57cec5SDimitry Andric // Read the relocation that refers to the partition's entry point symbol. 23210b57cec5SDimitry Andric Symbol *sym; 2322349cc55cSDimitry Andric const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>(); 2323349cc55cSDimitry Andric if (rels.areRelocsRel()) 2324349cc55cSDimitry Andric sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]); 23250b57cec5SDimitry Andric else 2326349cc55cSDimitry Andric sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]); 23270b57cec5SDimitry Andric if (!isa<Defined>(sym) || !sym->includeInDynsym()) 23280b57cec5SDimitry Andric return; 23290b57cec5SDimitry Andric 2330bdd1243dSDimitry Andric StringRef partName = reinterpret_cast<const char *>(s->content().data()); 23310b57cec5SDimitry Andric for (Partition &part : partitions) { 23320b57cec5SDimitry Andric if (part.name == partName) { 23330b57cec5SDimitry Andric sym->partition = part.getNumber(); 23340b57cec5SDimitry Andric return; 23350b57cec5SDimitry Andric } 23360b57cec5SDimitry Andric } 23370b57cec5SDimitry Andric 23380b57cec5SDimitry Andric // Forbid partitions from being used on incompatible targets, and forbid them 23390b57cec5SDimitry Andric // from being used together with various linker features that assume a single 23400b57cec5SDimitry Andric // set of output sections. 23410b57cec5SDimitry Andric if (script->hasSectionsCommand) 23420b57cec5SDimitry Andric error(toString(s->file) + 23430b57cec5SDimitry Andric ": partitions cannot be used with the SECTIONS command"); 23440b57cec5SDimitry Andric if (script->hasPhdrsCommands()) 23450b57cec5SDimitry Andric error(toString(s->file) + 23460b57cec5SDimitry Andric ": partitions cannot be used with the PHDRS command"); 23470b57cec5SDimitry Andric if (!config->sectionStartMap.empty()) 23480b57cec5SDimitry Andric error(toString(s->file) + ": partitions cannot be used with " 23490b57cec5SDimitry Andric "--section-start, -Ttext, -Tdata or -Tbss"); 23500b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 23510b57cec5SDimitry Andric error(toString(s->file) + ": partitions cannot be used on this target"); 23520b57cec5SDimitry Andric 23530b57cec5SDimitry Andric // Impose a limit of no more than 254 partitions. This limit comes from the 23540b57cec5SDimitry Andric // sizes of the Partition fields in InputSectionBase and Symbol, as well as 23550b57cec5SDimitry Andric // the amount of space devoted to the partition number in RankFlags. 23560b57cec5SDimitry Andric if (partitions.size() == 254) 23570b57cec5SDimitry Andric fatal("may not have more than 254 partitions"); 23580b57cec5SDimitry Andric 23590b57cec5SDimitry Andric partitions.emplace_back(); 23600b57cec5SDimitry Andric Partition &newPart = partitions.back(); 23610b57cec5SDimitry Andric newPart.name = partName; 23620b57cec5SDimitry Andric sym->partition = newPart.getNumber(); 23630b57cec5SDimitry Andric } 23640b57cec5SDimitry Andric 2365fe6060f1SDimitry Andric static Symbol *addUnusedUndefined(StringRef name, 2366fe6060f1SDimitry Andric uint8_t binding = STB_GLOBAL) { 2367bdd1243dSDimitry Andric return symtab.addSymbol(Undefined{nullptr, name, binding, STV_DEFAULT, 0}); 23685ffd83dbSDimitry Andric } 23695ffd83dbSDimitry Andric 237004eeddc0SDimitry Andric static void markBuffersAsDontNeed(bool skipLinkedOutput) { 237104eeddc0SDimitry Andric // With --thinlto-index-only, all buffers are nearly unused from now on 237204eeddc0SDimitry Andric // (except symbol/section names used by infrequent passes). Mark input file 237304eeddc0SDimitry Andric // buffers as MADV_DONTNEED so that these pages can be reused by the expensive 237404eeddc0SDimitry Andric // thin link, saving memory. 237504eeddc0SDimitry Andric if (skipLinkedOutput) { 2376bdd1243dSDimitry Andric for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers)) 237704eeddc0SDimitry Andric mb.dontNeedIfMmap(); 237804eeddc0SDimitry Andric return; 237904eeddc0SDimitry Andric } 238004eeddc0SDimitry Andric 238104eeddc0SDimitry Andric // Otherwise, just mark MemoryBuffers backing BitcodeFiles. 238204eeddc0SDimitry Andric DenseSet<const char *> bufs; 2383bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.bitcodeFiles) 238404eeddc0SDimitry Andric bufs.insert(file->mb.getBufferStart()); 2385bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.lazyBitcodeFiles) 238604eeddc0SDimitry Andric bufs.insert(file->mb.getBufferStart()); 2387bdd1243dSDimitry Andric for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers)) 238804eeddc0SDimitry Andric if (bufs.count(mb.getBufferStart())) 238904eeddc0SDimitry Andric mb.dontNeedIfMmap(); 239004eeddc0SDimitry Andric } 239104eeddc0SDimitry Andric 23920b57cec5SDimitry Andric // This function is where all the optimizations of link-time 23930b57cec5SDimitry Andric // optimization takes place. When LTO is in use, some input files are 23940b57cec5SDimitry Andric // not in native object file format but in the LLVM bitcode format. 23950b57cec5SDimitry Andric // This function compiles bitcode files into a few big native files 23960b57cec5SDimitry Andric // using LLVM functions and replaces bitcode symbols with the results. 23970b57cec5SDimitry Andric // Because all bitcode files that the program consists of are passed to 23980b57cec5SDimitry Andric // the compiler at once, it can do a whole-program optimization. 239904eeddc0SDimitry Andric template <class ELFT> 240004eeddc0SDimitry Andric void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) { 24015ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("LTO"); 24020b57cec5SDimitry Andric // Compile bitcode files and replace bitcode symbols. 24030b57cec5SDimitry Andric lto.reset(new BitcodeCompiler); 2404bdd1243dSDimitry Andric for (BitcodeFile *file : ctx.bitcodeFiles) 24050b57cec5SDimitry Andric lto->add(*file); 24060b57cec5SDimitry Andric 2407bdd1243dSDimitry Andric if (!ctx.bitcodeFiles.empty()) 240804eeddc0SDimitry Andric markBuffersAsDontNeed(skipLinkedOutput); 240904eeddc0SDimitry Andric 24100b57cec5SDimitry Andric for (InputFile *file : lto->compile()) { 24110b57cec5SDimitry Andric auto *obj = cast<ObjFile<ELFT>>(file); 24120b57cec5SDimitry Andric obj->parse(/*ignoreComdats=*/true); 24135ffd83dbSDimitry Andric 24145ffd83dbSDimitry Andric // Parse '@' in symbol names for non-relocatable output. 24155ffd83dbSDimitry Andric if (!config->relocatable) 24160b57cec5SDimitry Andric for (Symbol *sym : obj->getGlobalSymbols()) 241704eeddc0SDimitry Andric if (sym->hasVersionSuffix) 24180b57cec5SDimitry Andric sym->parseSymbolVersion(); 2419bdd1243dSDimitry Andric ctx.objectFiles.push_back(obj); 24200b57cec5SDimitry Andric } 24210b57cec5SDimitry Andric } 24220b57cec5SDimitry Andric 24230b57cec5SDimitry Andric // The --wrap option is a feature to rename symbols so that you can write 2424349cc55cSDimitry Andric // wrappers for existing functions. If you pass `--wrap=foo`, all 2425e8d8bef9SDimitry Andric // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are 2426e8d8bef9SDimitry Andric // expected to write `__wrap_foo` function as a wrapper). The original 2427e8d8bef9SDimitry Andric // symbol becomes accessible as `__real_foo`, so you can call that from your 24280b57cec5SDimitry Andric // wrapper. 24290b57cec5SDimitry Andric // 2430349cc55cSDimitry Andric // This data structure is instantiated for each --wrap option. 24310b57cec5SDimitry Andric struct WrappedSymbol { 24320b57cec5SDimitry Andric Symbol *sym; 24330b57cec5SDimitry Andric Symbol *real; 24340b57cec5SDimitry Andric Symbol *wrap; 24350b57cec5SDimitry Andric }; 24360b57cec5SDimitry Andric 2437349cc55cSDimitry Andric // Handles --wrap option. 24380b57cec5SDimitry Andric // 24390b57cec5SDimitry Andric // This function instantiates wrapper symbols. At this point, they seem 24400b57cec5SDimitry Andric // like they are not being used at all, so we explicitly set some flags so 24410b57cec5SDimitry Andric // that LTO won't eliminate them. 24420b57cec5SDimitry Andric static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) { 24430b57cec5SDimitry Andric std::vector<WrappedSymbol> v; 24440b57cec5SDimitry Andric DenseSet<StringRef> seen; 24450b57cec5SDimitry Andric 24460b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wrap)) { 24470b57cec5SDimitry Andric StringRef name = arg->getValue(); 24480b57cec5SDimitry Andric if (!seen.insert(name).second) 24490b57cec5SDimitry Andric continue; 24500b57cec5SDimitry Andric 2451bdd1243dSDimitry Andric Symbol *sym = symtab.find(name); 24520b57cec5SDimitry Andric if (!sym) 24530b57cec5SDimitry Andric continue; 24540b57cec5SDimitry Andric 2455fe6060f1SDimitry Andric Symbol *wrap = 245604eeddc0SDimitry Andric addUnusedUndefined(saver().save("__wrap_" + name), sym->binding); 2457bdd1243dSDimitry Andric 2458bdd1243dSDimitry Andric // If __real_ is referenced, pull in the symbol if it is lazy. Do this after 2459bdd1243dSDimitry Andric // processing __wrap_ as that may have referenced __real_. 2460bdd1243dSDimitry Andric StringRef realName = saver().save("__real_" + name); 2461bdd1243dSDimitry Andric if (symtab.find(realName)) 2462bdd1243dSDimitry Andric addUnusedUndefined(name, sym->binding); 2463bdd1243dSDimitry Andric 2464bdd1243dSDimitry Andric Symbol *real = addUnusedUndefined(realName); 24650b57cec5SDimitry Andric v.push_back({sym, real, wrap}); 24660b57cec5SDimitry Andric 24670b57cec5SDimitry Andric // We want to tell LTO not to inline symbols to be overwritten 24680b57cec5SDimitry Andric // because LTO doesn't know the final symbol contents after renaming. 246981ad6265SDimitry Andric real->scriptDefined = true; 247081ad6265SDimitry Andric sym->scriptDefined = true; 24710b57cec5SDimitry Andric 247281ad6265SDimitry Andric // If a symbol is referenced in any object file, bitcode file or shared 247381ad6265SDimitry Andric // object, mark its redirection target (foo for __real_foo and __wrap_foo 247481ad6265SDimitry Andric // for foo) as referenced after redirection, which will be used to tell LTO 247581ad6265SDimitry Andric // to not eliminate the redirection target. If the object file defining the 247681ad6265SDimitry Andric // symbol also references it, we cannot easily distinguish the case from 247781ad6265SDimitry Andric // cases where the symbol is not referenced. Retain the redirection target 247881ad6265SDimitry Andric // in this case because we choose to wrap symbol references regardless of 247981ad6265SDimitry Andric // whether the symbol is defined 2480e8d8bef9SDimitry Andric // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358). 248181ad6265SDimitry Andric if (real->referenced || real->isDefined()) 248281ad6265SDimitry Andric sym->referencedAfterWrap = true; 2483e8d8bef9SDimitry Andric if (sym->referenced || sym->isDefined()) 248481ad6265SDimitry Andric wrap->referencedAfterWrap = true; 24850b57cec5SDimitry Andric } 24860b57cec5SDimitry Andric return v; 24870b57cec5SDimitry Andric } 24880b57cec5SDimitry Andric 2489bdd1243dSDimitry Andric static void combineVersionedSymbol(Symbol &sym, 2490bdd1243dSDimitry Andric DenseMap<Symbol *, Symbol *> &map) { 2491bdd1243dSDimitry Andric const char *suffix1 = sym.getVersionSuffix(); 2492bdd1243dSDimitry Andric if (suffix1[0] != '@' || suffix1[1] == '@') 2493bdd1243dSDimitry Andric return; 2494bdd1243dSDimitry Andric 2495bdd1243dSDimitry Andric // Check the existing symbol foo. We have two special cases to handle: 2496bdd1243dSDimitry Andric // 2497bdd1243dSDimitry Andric // * There is a definition of foo@v1 and foo@@v1. 2498bdd1243dSDimitry Andric // * There is a definition of foo@v1 and foo. 2499bdd1243dSDimitry Andric Defined *sym2 = dyn_cast_or_null<Defined>(symtab.find(sym.getName())); 2500bdd1243dSDimitry Andric if (!sym2) 2501bdd1243dSDimitry Andric return; 2502bdd1243dSDimitry Andric const char *suffix2 = sym2->getVersionSuffix(); 2503bdd1243dSDimitry Andric if (suffix2[0] == '@' && suffix2[1] == '@' && 2504bdd1243dSDimitry Andric strcmp(suffix1 + 1, suffix2 + 2) == 0) { 2505bdd1243dSDimitry Andric // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1. 2506bdd1243dSDimitry Andric map.try_emplace(&sym, sym2); 2507bdd1243dSDimitry Andric // If both foo@v1 and foo@@v1 are defined and non-weak, report a 2508bdd1243dSDimitry Andric // duplicate definition error. 2509bdd1243dSDimitry Andric if (sym.isDefined()) { 2510bdd1243dSDimitry Andric sym2->checkDuplicate(cast<Defined>(sym)); 2511bdd1243dSDimitry Andric sym2->resolve(cast<Defined>(sym)); 2512bdd1243dSDimitry Andric } else if (sym.isUndefined()) { 2513bdd1243dSDimitry Andric sym2->resolve(cast<Undefined>(sym)); 2514bdd1243dSDimitry Andric } else { 2515bdd1243dSDimitry Andric sym2->resolve(cast<SharedSymbol>(sym)); 2516bdd1243dSDimitry Andric } 2517bdd1243dSDimitry Andric // Eliminate foo@v1 from the symbol table. 2518bdd1243dSDimitry Andric sym.symbolKind = Symbol::PlaceholderKind; 2519bdd1243dSDimitry Andric sym.isUsedInRegularObj = false; 2520bdd1243dSDimitry Andric } else if (auto *sym1 = dyn_cast<Defined>(&sym)) { 2521bdd1243dSDimitry Andric if (sym2->versionId > VER_NDX_GLOBAL 2522bdd1243dSDimitry Andric ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1 2523bdd1243dSDimitry Andric : sym1->section == sym2->section && sym1->value == sym2->value) { 2524bdd1243dSDimitry Andric // Due to an assembler design flaw, if foo is defined, .symver foo, 2525bdd1243dSDimitry Andric // foo@v1 defines both foo and foo@v1. Unless foo is bound to a 2526bdd1243dSDimitry Andric // different version, GNU ld makes foo@v1 canonical and eliminates 2527bdd1243dSDimitry Andric // foo. Emulate its behavior, otherwise we would have foo or foo@@v1 2528bdd1243dSDimitry Andric // beside foo@v1. foo@v1 and foo combining does not apply if they are 2529bdd1243dSDimitry Andric // not defined in the same place. 2530bdd1243dSDimitry Andric map.try_emplace(sym2, &sym); 2531bdd1243dSDimitry Andric sym2->symbolKind = Symbol::PlaceholderKind; 2532bdd1243dSDimitry Andric sym2->isUsedInRegularObj = false; 2533bdd1243dSDimitry Andric } 2534bdd1243dSDimitry Andric } 2535bdd1243dSDimitry Andric } 2536bdd1243dSDimitry Andric 2537349cc55cSDimitry Andric // Do renaming for --wrap and foo@v1 by updating pointers to symbols. 25380b57cec5SDimitry Andric // 25390b57cec5SDimitry Andric // When this function is executed, only InputFiles and symbol table 25400b57cec5SDimitry Andric // contain pointers to symbol objects. We visit them to replace pointers, 25410b57cec5SDimitry Andric // so that wrapped symbols are swapped as instructed by the command line. 2542e8d8bef9SDimitry Andric static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) { 2543e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Redirect symbols"); 25440b57cec5SDimitry Andric DenseMap<Symbol *, Symbol *> map; 25450b57cec5SDimitry Andric for (const WrappedSymbol &w : wrapped) { 25460b57cec5SDimitry Andric map[w.sym] = w.wrap; 25470b57cec5SDimitry Andric map[w.real] = w.sym; 25480b57cec5SDimitry Andric } 2549e8d8bef9SDimitry Andric 2550bdd1243dSDimitry Andric // If there are version definitions (versionDefinitions.size() > 2), enumerate 2551bdd1243dSDimitry Andric // symbols with a non-default version (foo@v1) and check whether it should be 2552bdd1243dSDimitry Andric // combined with foo or foo@@v1. 2553bdd1243dSDimitry Andric if (config->versionDefinitions.size() > 2) 2554bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols()) 2555bdd1243dSDimitry Andric if (sym->hasVersionSuffix) 2556bdd1243dSDimitry Andric combineVersionedSymbol(*sym, map); 2557e8d8bef9SDimitry Andric 2558e8d8bef9SDimitry Andric if (map.empty()) 2559e8d8bef9SDimitry Andric return; 25600b57cec5SDimitry Andric 25610b57cec5SDimitry Andric // Update pointers in input files. 2562bdd1243dSDimitry Andric parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) { 25630eae32dcSDimitry Andric for (Symbol *&sym : file->getMutableGlobalSymbols()) 25640eae32dcSDimitry Andric if (Symbol *s = map.lookup(sym)) 25650eae32dcSDimitry Andric sym = s; 25660b57cec5SDimitry Andric }); 25670b57cec5SDimitry Andric 25680b57cec5SDimitry Andric // Update pointers in the symbol table. 25690b57cec5SDimitry Andric for (const WrappedSymbol &w : wrapped) 2570bdd1243dSDimitry Andric symtab.wrap(w.sym, w.real, w.wrap); 25710b57cec5SDimitry Andric } 25720b57cec5SDimitry Andric 25730eae32dcSDimitry Andric static void checkAndReportMissingFeature(StringRef config, uint32_t features, 25740eae32dcSDimitry Andric uint32_t mask, const Twine &report) { 25750eae32dcSDimitry Andric if (!(features & mask)) { 25760eae32dcSDimitry Andric if (config == "error") 25770eae32dcSDimitry Andric error(report); 25780eae32dcSDimitry Andric else if (config == "warning") 25790eae32dcSDimitry Andric warn(report); 25800eae32dcSDimitry Andric } 25810eae32dcSDimitry Andric } 25820eae32dcSDimitry Andric 2583bdd1243dSDimitry Andric // To enable CET (x86's hardware-assisted control flow enforcement), each 25840b57cec5SDimitry Andric // source file must be compiled with -fcf-protection. Object files compiled 25850b57cec5SDimitry Andric // with the flag contain feature flags indicating that they are compatible 25860b57cec5SDimitry Andric // with CET. We enable the feature only when all object files are compatible 25870b57cec5SDimitry Andric // with CET. 25880b57cec5SDimitry Andric // 25890b57cec5SDimitry Andric // This is also the case with AARCH64's BTI and PAC which use the similar 25900b57cec5SDimitry Andric // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism. 25911fd87a68SDimitry Andric static uint32_t getAndFeatures() { 25920b57cec5SDimitry Andric if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 25930b57cec5SDimitry Andric config->emachine != EM_AARCH64) 25940b57cec5SDimitry Andric return 0; 25950b57cec5SDimitry Andric 25960b57cec5SDimitry Andric uint32_t ret = -1; 2597bdd1243dSDimitry Andric for (ELFFileBase *f : ctx.objectFiles) { 25981fd87a68SDimitry Andric uint32_t features = f->andFeatures; 25990eae32dcSDimitry Andric 26000eae32dcSDimitry Andric checkAndReportMissingFeature( 26010eae32dcSDimitry Andric config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI, 26020eae32dcSDimitry Andric toString(f) + ": -z bti-report: file does not have " 26030eae32dcSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 26040eae32dcSDimitry Andric 26050eae32dcSDimitry Andric checkAndReportMissingFeature( 26060eae32dcSDimitry Andric config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT, 26070eae32dcSDimitry Andric toString(f) + ": -z cet-report: file does not have " 26080eae32dcSDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 26090eae32dcSDimitry Andric 26100eae32dcSDimitry Andric checkAndReportMissingFeature( 26110eae32dcSDimitry Andric config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK, 26120eae32dcSDimitry Andric toString(f) + ": -z cet-report: file does not have " 26130eae32dcSDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_SHSTK property"); 26140eae32dcSDimitry Andric 26155ffd83dbSDimitry Andric if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) { 26160eae32dcSDimitry Andric features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI; 26170eae32dcSDimitry Andric if (config->zBtiReport == "none") 26185ffd83dbSDimitry Andric warn(toString(f) + ": -z force-bti: file does not have " 26195ffd83dbSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 2620480093f4SDimitry Andric } else if (config->zForceIbt && 2621480093f4SDimitry Andric !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) { 26220eae32dcSDimitry Andric if (config->zCetReport == "none") 2623480093f4SDimitry Andric warn(toString(f) + ": -z force-ibt: file does not have " 2624480093f4SDimitry Andric "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 2625480093f4SDimitry Andric features |= GNU_PROPERTY_X86_FEATURE_1_IBT; 2626480093f4SDimitry Andric } 26275ffd83dbSDimitry Andric if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) { 26285ffd83dbSDimitry Andric warn(toString(f) + ": -z pac-plt: file does not have " 26295ffd83dbSDimitry Andric "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property"); 26305ffd83dbSDimitry Andric features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC; 26315ffd83dbSDimitry Andric } 26320b57cec5SDimitry Andric ret &= features; 26330b57cec5SDimitry Andric } 26340b57cec5SDimitry Andric 2635480093f4SDimitry Andric // Force enable Shadow Stack. 2636480093f4SDimitry Andric if (config->zShstk) 2637480093f4SDimitry Andric ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK; 26380b57cec5SDimitry Andric 26390b57cec5SDimitry Andric return ret; 26400b57cec5SDimitry Andric } 26410b57cec5SDimitry Andric 2642bdd1243dSDimitry Andric static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) { 2643bdd1243dSDimitry Andric switch (file->ekind) { 264481ad6265SDimitry Andric case ELF32LEKind: 2645bdd1243dSDimitry Andric cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 264681ad6265SDimitry Andric break; 264781ad6265SDimitry Andric case ELF32BEKind: 2648bdd1243dSDimitry Andric cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 264981ad6265SDimitry Andric break; 265081ad6265SDimitry Andric case ELF64LEKind: 2651bdd1243dSDimitry Andric cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 265281ad6265SDimitry Andric break; 265381ad6265SDimitry Andric case ELF64BEKind: 2654bdd1243dSDimitry Andric cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 265581ad6265SDimitry Andric break; 265681ad6265SDimitry Andric default: 265781ad6265SDimitry Andric llvm_unreachable(""); 265881ad6265SDimitry Andric } 265981ad6265SDimitry Andric } 266081ad6265SDimitry Andric 266181ad6265SDimitry Andric static void postParseObjectFile(ELFFileBase *file) { 2662bdd1243dSDimitry Andric switch (file->ekind) { 266381ad6265SDimitry Andric case ELF32LEKind: 266481ad6265SDimitry Andric cast<ObjFile<ELF32LE>>(file)->postParse(); 266581ad6265SDimitry Andric break; 266681ad6265SDimitry Andric case ELF32BEKind: 266781ad6265SDimitry Andric cast<ObjFile<ELF32BE>>(file)->postParse(); 266881ad6265SDimitry Andric break; 266981ad6265SDimitry Andric case ELF64LEKind: 267081ad6265SDimitry Andric cast<ObjFile<ELF64LE>>(file)->postParse(); 267181ad6265SDimitry Andric break; 267281ad6265SDimitry Andric case ELF64BEKind: 267381ad6265SDimitry Andric cast<ObjFile<ELF64BE>>(file)->postParse(); 267481ad6265SDimitry Andric break; 267581ad6265SDimitry Andric default: 267681ad6265SDimitry Andric llvm_unreachable(""); 267781ad6265SDimitry Andric } 267881ad6265SDimitry Andric } 267981ad6265SDimitry Andric 26800b57cec5SDimitry Andric // Do actual linking. Note that when this function is called, 26810b57cec5SDimitry Andric // all linker scripts have already been parsed. 26821fd87a68SDimitry Andric void LinkerDriver::link(opt::InputArgList &args) { 26835ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link")); 2684349cc55cSDimitry Andric // If a --hash-style option was not given, set to a default value, 26850b57cec5SDimitry Andric // which varies depending on the target. 26860b57cec5SDimitry Andric if (!args.hasArg(OPT_hash_style)) { 26870b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 26880b57cec5SDimitry Andric config->sysvHash = true; 26890b57cec5SDimitry Andric else 26900b57cec5SDimitry Andric config->sysvHash = config->gnuHash = true; 26910b57cec5SDimitry Andric } 26920b57cec5SDimitry Andric 26930b57cec5SDimitry Andric // Default output filename is "a.out" by the Unix tradition. 26940b57cec5SDimitry Andric if (config->outputFile.empty()) 26950b57cec5SDimitry Andric config->outputFile = "a.out"; 26960b57cec5SDimitry Andric 26970b57cec5SDimitry Andric // Fail early if the output file or map file is not writable. If a user has a 26980b57cec5SDimitry Andric // long link, e.g. due to a large LTO link, they do not wish to run it and 26990b57cec5SDimitry Andric // find that it failed because there was a mistake in their command-line. 2700e8d8bef9SDimitry Andric { 2701e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Create output files"); 27020b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) 2703e8d8bef9SDimitry Andric error("cannot open output file " + config->outputFile + ": " + 2704e8d8bef9SDimitry Andric e.message()); 27050b57cec5SDimitry Andric if (auto e = tryCreateFile(config->mapFile)) 27060b57cec5SDimitry Andric error("cannot open map file " + config->mapFile + ": " + e.message()); 2707349cc55cSDimitry Andric if (auto e = tryCreateFile(config->whyExtract)) 2708349cc55cSDimitry Andric error("cannot open --why-extract= file " + config->whyExtract + ": " + 2709349cc55cSDimitry Andric e.message()); 2710e8d8bef9SDimitry Andric } 27110b57cec5SDimitry Andric if (errorCount()) 27120b57cec5SDimitry Andric return; 27130b57cec5SDimitry Andric 27140b57cec5SDimitry Andric // Use default entry point name if no name was given via the command 27150b57cec5SDimitry Andric // line nor linker scripts. For some reason, MIPS entry point name is 27160b57cec5SDimitry Andric // different from others. 27170b57cec5SDimitry Andric config->warnMissingEntry = 27180b57cec5SDimitry Andric (!config->entry.empty() || (!config->shared && !config->relocatable)); 27190b57cec5SDimitry Andric if (config->entry.empty() && !config->relocatable) 27200b57cec5SDimitry Andric config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start"; 27210b57cec5SDimitry Andric 27220b57cec5SDimitry Andric // Handle --trace-symbol. 27230b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_trace_symbol)) 2724bdd1243dSDimitry Andric symtab.insert(arg->getValue())->traced = true; 27250b57cec5SDimitry Andric 27265ffd83dbSDimitry Andric // Handle -u/--undefined before input files. If both a.a and b.so define foo, 27274824e7fdSDimitry Andric // -u foo a.a b.so will extract a.a. 27285ffd83dbSDimitry Andric for (StringRef name : config->undefined) 2729e8d8bef9SDimitry Andric addUnusedUndefined(name)->referenced = true; 27305ffd83dbSDimitry Andric 27310b57cec5SDimitry Andric // Add all files to the symbol table. This will add almost all 27320b57cec5SDimitry Andric // symbols that we need to the symbol table. This process might 27330b57cec5SDimitry Andric // add files to the link, via autolinking, these files are always 27340b57cec5SDimitry Andric // appended to the Files vector. 27355ffd83dbSDimitry Andric { 27365ffd83dbSDimitry Andric llvm::TimeTraceScope timeScope("Parse input files"); 2737e8d8bef9SDimitry Andric for (size_t i = 0; i < files.size(); ++i) { 2738e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName()); 27390b57cec5SDimitry Andric parseFile(files[i]); 27405ffd83dbSDimitry Andric } 274106c3fb27SDimitry Andric if (armCmseImpLib) 274206c3fb27SDimitry Andric parseArmCMSEImportLib(*armCmseImpLib); 2743e8d8bef9SDimitry Andric } 27440b57cec5SDimitry Andric 27450b57cec5SDimitry Andric // Now that we have every file, we can decide if we will need a 27460b57cec5SDimitry Andric // dynamic symbol table. 27470b57cec5SDimitry Andric // We need one if we were asked to export dynamic symbols or if we are 27480b57cec5SDimitry Andric // producing a shared library. 27490b57cec5SDimitry Andric // We also need one if any shared libraries are used and for pie executables 27500b57cec5SDimitry Andric // (probably because the dynamic linker needs it). 27510b57cec5SDimitry Andric config->hasDynSymTab = 2752bdd1243dSDimitry Andric !ctx.sharedFiles.empty() || config->isPic || config->exportDynamic; 27530b57cec5SDimitry Andric 27540b57cec5SDimitry Andric // Some symbols (such as __ehdr_start) are defined lazily only when there 27550b57cec5SDimitry Andric // are undefined symbols for them, so we add these to trigger that logic. 275681ad6265SDimitry Andric for (StringRef name : script->referencedSymbols) { 275781ad6265SDimitry Andric Symbol *sym = addUnusedUndefined(name); 275881ad6265SDimitry Andric sym->isUsedInRegularObj = true; 275981ad6265SDimitry Andric sym->referenced = true; 276081ad6265SDimitry Andric } 27610b57cec5SDimitry Andric 27625ffd83dbSDimitry Andric // Prevent LTO from removing any definition referenced by -u. 27635ffd83dbSDimitry Andric for (StringRef name : config->undefined) 2764bdd1243dSDimitry Andric if (Defined *sym = dyn_cast_or_null<Defined>(symtab.find(name))) 27655ffd83dbSDimitry Andric sym->isUsedInRegularObj = true; 27660b57cec5SDimitry Andric 27670b57cec5SDimitry Andric // If an entry symbol is in a static archive, pull out that file now. 2768bdd1243dSDimitry Andric if (Symbol *sym = symtab.find(config->entry)) 2769349cc55cSDimitry Andric handleUndefined(sym, "--entry"); 27700b57cec5SDimitry Andric 27710b57cec5SDimitry Andric // Handle the `--undefined-glob <pattern>` options. 27720b57cec5SDimitry Andric for (StringRef pat : args::getStrings(args, OPT_undefined_glob)) 27730b57cec5SDimitry Andric handleUndefinedGlob(pat); 27740b57cec5SDimitry Andric 2775480093f4SDimitry Andric // Mark -init and -fini symbols so that the LTO doesn't eliminate them. 2776bdd1243dSDimitry Andric if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->init))) 2777480093f4SDimitry Andric sym->isUsedInRegularObj = true; 2778bdd1243dSDimitry Andric if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->fini))) 2779480093f4SDimitry Andric sym->isUsedInRegularObj = true; 2780480093f4SDimitry Andric 27810b57cec5SDimitry Andric // If any of our inputs are bitcode files, the LTO code generator may create 27820b57cec5SDimitry Andric // references to certain library functions that might not be explicit in the 27830b57cec5SDimitry Andric // bitcode file's symbol table. If any of those library functions are defined 27840b57cec5SDimitry Andric // in a bitcode file in an archive member, we need to arrange to use LTO to 27850b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 27860b57cec5SDimitry Andric // 27870b57cec5SDimitry Andric // However, adding all libcall symbols to the link can have undesired 27880b57cec5SDimitry Andric // consequences. For example, the libgcc implementation of 27890b57cec5SDimitry Andric // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 27900b57cec5SDimitry Andric // that aborts the program if the Linux kernel does not support 64-bit 27910b57cec5SDimitry Andric // atomics, which would prevent the program from running even if it does not 27920b57cec5SDimitry Andric // use 64-bit atomics. 27930b57cec5SDimitry Andric // 27940b57cec5SDimitry Andric // Therefore, we only add libcall symbols to the link before LTO if we have 27950b57cec5SDimitry Andric // to, i.e. if the symbol's definition is in bitcode. Any other required 27960b57cec5SDimitry Andric // libcall symbols will be added to the link after LTO when we add the LTO 27970b57cec5SDimitry Andric // object file to the link. 2798bdd1243dSDimitry Andric if (!ctx.bitcodeFiles.empty()) 279985868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 28000b57cec5SDimitry Andric handleLibcall(s); 28010b57cec5SDimitry Andric 280281ad6265SDimitry Andric // Archive members defining __wrap symbols may be extracted. 280381ad6265SDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 280481ad6265SDimitry Andric 280581ad6265SDimitry Andric // No more lazy bitcode can be extracted at this point. Do post parse work 280681ad6265SDimitry Andric // like checking duplicate symbols. 2807bdd1243dSDimitry Andric parallelForEach(ctx.objectFiles, [](ELFFileBase *file) { 2808bdd1243dSDimitry Andric initSectionsAndLocalSyms(file, /*ignoreComdats=*/false); 2809bdd1243dSDimitry Andric }); 2810bdd1243dSDimitry Andric parallelForEach(ctx.objectFiles, postParseObjectFile); 2811bdd1243dSDimitry Andric parallelForEach(ctx.bitcodeFiles, 281281ad6265SDimitry Andric [](BitcodeFile *file) { file->postParse(); }); 2813bdd1243dSDimitry Andric for (auto &it : ctx.nonPrevailingSyms) { 281481ad6265SDimitry Andric Symbol &sym = *it.first; 2815bdd1243dSDimitry Andric Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type, 2816bdd1243dSDimitry Andric it.second) 2817bdd1243dSDimitry Andric .overwrite(sym); 281881ad6265SDimitry Andric cast<Undefined>(sym).nonPrevailing = true; 281981ad6265SDimitry Andric } 2820bdd1243dSDimitry Andric ctx.nonPrevailingSyms.clear(); 2821bdd1243dSDimitry Andric for (const DuplicateSymbol &d : ctx.duplicates) 282281ad6265SDimitry Andric reportDuplicate(*d.sym, d.file, d.section, d.value); 2823bdd1243dSDimitry Andric ctx.duplicates.clear(); 282481ad6265SDimitry Andric 28250b57cec5SDimitry Andric // Return if there were name resolution errors. 28260b57cec5SDimitry Andric if (errorCount()) 28270b57cec5SDimitry Andric return; 28280b57cec5SDimitry Andric 28290b57cec5SDimitry Andric // We want to declare linker script's symbols early, 28300b57cec5SDimitry Andric // so that we can version them. 28310b57cec5SDimitry Andric // They also might be exported if referenced by DSOs. 28320b57cec5SDimitry Andric script->declareSymbols(); 28330b57cec5SDimitry Andric 2834e8d8bef9SDimitry Andric // Handle --exclude-libs. This is before scanVersionScript() due to a 2835e8d8bef9SDimitry Andric // workaround for Android ndk: for a defined versioned symbol in an archive 2836e8d8bef9SDimitry Andric // without a version node in the version script, Android does not expect a 2837e8d8bef9SDimitry Andric // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295). 2838e8d8bef9SDimitry Andric // GNU ld errors in this case. 28390b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_libs)) 28400b57cec5SDimitry Andric excludeLibs(args); 28410b57cec5SDimitry Andric 28420b57cec5SDimitry Andric // Create elfHeader early. We need a dummy section in 28430b57cec5SDimitry Andric // addReservedSymbols to mark the created symbols as not absolute. 28440b57cec5SDimitry Andric Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC); 28450b57cec5SDimitry Andric 28460b57cec5SDimitry Andric // We need to create some reserved symbols such as _end. Create them. 28470b57cec5SDimitry Andric if (!config->relocatable) 28480b57cec5SDimitry Andric addReservedSymbols(); 28490b57cec5SDimitry Andric 28500b57cec5SDimitry Andric // Apply version scripts. 28510b57cec5SDimitry Andric // 28520b57cec5SDimitry Andric // For a relocatable output, version scripts don't make sense, and 28530b57cec5SDimitry Andric // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 28540b57cec5SDimitry Andric // name "foo@ver1") rather do harm, so we don't call this if -r is given. 2855e8d8bef9SDimitry Andric if (!config->relocatable) { 2856e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Process symbol versions"); 2857bdd1243dSDimitry Andric symtab.scanVersionScript(); 2858e8d8bef9SDimitry Andric } 28590b57cec5SDimitry Andric 286004eeddc0SDimitry Andric // Skip the normal linked output if some LTO options are specified. 286104eeddc0SDimitry Andric // 286204eeddc0SDimitry Andric // For --thinlto-index-only, index file creation is performed in 286304eeddc0SDimitry Andric // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and 286404eeddc0SDimitry Andric // --plugin-opt=emit-asm create output files in bitcode or assembly code, 286504eeddc0SDimitry Andric // respectively. When only certain thinLTO modules are specified for 286604eeddc0SDimitry Andric // compilation, the intermediate object file are the expected output. 286704eeddc0SDimitry Andric const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM || 286804eeddc0SDimitry Andric config->ltoEmitAsm || 286904eeddc0SDimitry Andric !config->thinLTOModulesToCompile.empty(); 287004eeddc0SDimitry Andric 2871*5f757f3fSDimitry Andric // Handle --lto-validate-all-vtables-have-type-infos. 2872*5f757f3fSDimitry Andric if (config->ltoValidateAllVtablesHaveTypeInfos) 2873*5f757f3fSDimitry Andric invokeELFT(ltoValidateAllVtablesHaveTypeInfos, args); 2874*5f757f3fSDimitry Andric 28750b57cec5SDimitry Andric // Do link-time optimization if given files are LLVM bitcode files. 28760b57cec5SDimitry Andric // This compiles bitcode files into real object files. 28770b57cec5SDimitry Andric // 28780b57cec5SDimitry Andric // With this the symbol table should be complete. After this, no new names 28790b57cec5SDimitry Andric // except a few linker-synthesized ones will be added to the symbol table. 2880bdd1243dSDimitry Andric const size_t numObjsBeforeLTO = ctx.objectFiles.size(); 28811fd87a68SDimitry Andric invokeELFT(compileBitcodeFiles, skipLinkedOutput); 288204eeddc0SDimitry Andric 288381ad6265SDimitry Andric // Symbol resolution finished. Report backward reference problems, 288481ad6265SDimitry Andric // --print-archive-stats=, and --why-extract=. 288504eeddc0SDimitry Andric reportBackrefs(); 288681ad6265SDimitry Andric writeArchiveStats(); 288781ad6265SDimitry Andric writeWhyExtract(); 288804eeddc0SDimitry Andric if (errorCount()) 288904eeddc0SDimitry Andric return; 289004eeddc0SDimitry Andric 289104eeddc0SDimitry Andric // Bail out if normal linked output is skipped due to LTO. 289204eeddc0SDimitry Andric if (skipLinkedOutput) 289304eeddc0SDimitry Andric return; 28945ffd83dbSDimitry Andric 289581ad6265SDimitry Andric // compileBitcodeFiles may have produced lto.tmp object files. After this, no 289681ad6265SDimitry Andric // more file will be added. 2897bdd1243dSDimitry Andric auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO); 2898bdd1243dSDimitry Andric parallelForEach(newObjectFiles, [](ELFFileBase *file) { 2899bdd1243dSDimitry Andric initSectionsAndLocalSyms(file, /*ignoreComdats=*/true); 2900bdd1243dSDimitry Andric }); 290181ad6265SDimitry Andric parallelForEach(newObjectFiles, postParseObjectFile); 2902bdd1243dSDimitry Andric for (const DuplicateSymbol &d : ctx.duplicates) 290381ad6265SDimitry Andric reportDuplicate(*d.sym, d.file, d.section, d.value); 290481ad6265SDimitry Andric 2905e8d8bef9SDimitry Andric // Handle --exclude-libs again because lto.tmp may reference additional 2906e8d8bef9SDimitry Andric // libcalls symbols defined in an excluded archive. This may override 2907e8d8bef9SDimitry Andric // versionId set by scanVersionScript(). 2908e8d8bef9SDimitry Andric if (args.hasArg(OPT_exclude_libs)) 2909e8d8bef9SDimitry Andric excludeLibs(args); 2910e8d8bef9SDimitry Andric 291106c3fb27SDimitry Andric // Record [__acle_se_<sym>, <sym>] pairs for later processing. 291206c3fb27SDimitry Andric processArmCmseSymbols(); 291306c3fb27SDimitry Andric 2914349cc55cSDimitry Andric // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1. 2915e8d8bef9SDimitry Andric redirectSymbols(wrapped); 29160b57cec5SDimitry Andric 291704eeddc0SDimitry Andric // Replace common symbols with regular symbols. 291804eeddc0SDimitry Andric replaceCommonSymbols(); 291904eeddc0SDimitry Andric 2920e8d8bef9SDimitry Andric { 2921e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Aggregate sections"); 29220b57cec5SDimitry Andric // Now that we have a complete list of input files. 29230b57cec5SDimitry Andric // Beyond this point, no new files are added. 29240b57cec5SDimitry Andric // Aggregate all input sections into one place. 2925bdd1243dSDimitry Andric for (InputFile *f : ctx.objectFiles) { 2926bdd1243dSDimitry Andric for (InputSectionBase *s : f->getSections()) { 2927bdd1243dSDimitry Andric if (!s || s == &InputSection::discarded) 2928bdd1243dSDimitry Andric continue; 2929bdd1243dSDimitry Andric if (LLVM_UNLIKELY(isa<EhInputSection>(s))) 2930bdd1243dSDimitry Andric ctx.ehInputSections.push_back(cast<EhInputSection>(s)); 2931bdd1243dSDimitry Andric else 2932bdd1243dSDimitry Andric ctx.inputSections.push_back(s); 2933bdd1243dSDimitry Andric } 2934bdd1243dSDimitry Andric } 2935bdd1243dSDimitry Andric for (BinaryFile *f : ctx.binaryFiles) 29360b57cec5SDimitry Andric for (InputSectionBase *s : f->getSections()) 2937bdd1243dSDimitry Andric ctx.inputSections.push_back(cast<InputSection>(s)); 2938e8d8bef9SDimitry Andric } 29390b57cec5SDimitry Andric 2940e8d8bef9SDimitry Andric { 2941e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Strip sections"); 2942bdd1243dSDimitry Andric if (ctx.hasSympart.load(std::memory_order_relaxed)) { 2943bdd1243dSDimitry Andric llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) { 294481ad6265SDimitry Andric if (s->type != SHT_LLVM_SYMPART) 294581ad6265SDimitry Andric return false; 29461fd87a68SDimitry Andric invokeELFT(readSymbolPartitionSection, s); 29470b57cec5SDimitry Andric return true; 294881ad6265SDimitry Andric }); 29490b57cec5SDimitry Andric } 29500b57cec5SDimitry Andric // We do not want to emit debug sections if --strip-all 2951349cc55cSDimitry Andric // or --strip-debug are given. 295281ad6265SDimitry Andric if (config->strip != StripPolicy::None) { 2953bdd1243dSDimitry Andric llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) { 2954d65cd7a5SDimitry Andric if (isDebugSection(*s)) 2955d65cd7a5SDimitry Andric return true; 2956d65cd7a5SDimitry Andric if (auto *isec = dyn_cast<InputSection>(s)) 2957d65cd7a5SDimitry Andric if (InputSectionBase *rel = isec->getRelocatedSection()) 2958d65cd7a5SDimitry Andric if (isDebugSection(*rel)) 2959d65cd7a5SDimitry Andric return true; 2960d65cd7a5SDimitry Andric 2961d65cd7a5SDimitry Andric return false; 29620b57cec5SDimitry Andric }); 2963e8d8bef9SDimitry Andric } 296481ad6265SDimitry Andric } 2965e8d8bef9SDimitry Andric 2966e8d8bef9SDimitry Andric // Since we now have a complete set of input files, we can create 2967e8d8bef9SDimitry Andric // a .d file to record build dependencies. 2968e8d8bef9SDimitry Andric if (!config->dependencyFile.empty()) 2969e8d8bef9SDimitry Andric writeDependencyFile(); 29700b57cec5SDimitry Andric 29710b57cec5SDimitry Andric // Now that the number of partitions is fixed, save a pointer to the main 29720b57cec5SDimitry Andric // partition. 29730b57cec5SDimitry Andric mainPart = &partitions[0]; 29740b57cec5SDimitry Andric 29750b57cec5SDimitry Andric // Read .note.gnu.property sections from input object files which 29760b57cec5SDimitry Andric // contain a hint to tweak linker's and loader's behaviors. 29771fd87a68SDimitry Andric config->andFeatures = getAndFeatures(); 29780b57cec5SDimitry Andric 29790b57cec5SDimitry Andric // The Target instance handles target-specific stuff, such as applying 29800b57cec5SDimitry Andric // relocations or writing a PLT section. It also contains target-dependent 29810b57cec5SDimitry Andric // values such as a default image base address. 29820b57cec5SDimitry Andric target = getTarget(); 29830b57cec5SDimitry Andric 29840b57cec5SDimitry Andric config->eflags = target->calcEFlags(); 29850b57cec5SDimitry Andric // maxPageSize (sometimes called abi page size) is the maximum page size that 29860b57cec5SDimitry Andric // the output can be run on. For example if the OS can use 4k or 64k page 29870b57cec5SDimitry Andric // sizes then maxPageSize must be 64k for the output to be useable on both. 29880b57cec5SDimitry Andric // All important alignment decisions must use this value. 29890b57cec5SDimitry Andric config->maxPageSize = getMaxPageSize(args); 29900b57cec5SDimitry Andric // commonPageSize is the most common page size that the output will be run on. 29910b57cec5SDimitry Andric // For example if an OS can use 4k or 64k page sizes and 4k is more common 29920b57cec5SDimitry Andric // than 64k then commonPageSize is set to 4k. commonPageSize can be used for 29930b57cec5SDimitry Andric // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 29940b57cec5SDimitry Andric // is limited to writing trap instructions on the last executable segment. 29950b57cec5SDimitry Andric config->commonPageSize = getCommonPageSize(args); 29960b57cec5SDimitry Andric 29970b57cec5SDimitry Andric config->imageBase = getImageBase(args); 29980b57cec5SDimitry Andric 299985868e8aSDimitry Andric // This adds a .comment section containing a version string. 30000b57cec5SDimitry Andric if (!config->relocatable) 3001bdd1243dSDimitry Andric ctx.inputSections.push_back(createCommentSection()); 30020b57cec5SDimitry Andric 300385868e8aSDimitry Andric // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection. 300406c3fb27SDimitry Andric invokeELFT(splitSections,); 300585868e8aSDimitry Andric 300685868e8aSDimitry Andric // Garbage collection and removal of shared symbols from unused shared objects. 300706c3fb27SDimitry Andric invokeELFT(markLive,); 300885868e8aSDimitry Andric 300985868e8aSDimitry Andric // Make copies of any input sections that need to be copied into each 301085868e8aSDimitry Andric // partition. 301185868e8aSDimitry Andric copySectionsIntoPartitions(); 301285868e8aSDimitry Andric 3013*5f757f3fSDimitry Andric if (canHaveMemtagGlobals()) { 3014*5f757f3fSDimitry Andric llvm::TimeTraceScope timeScope("Process memory tagged symbols"); 3015*5f757f3fSDimitry Andric createTaggedSymbols(ctx.objectFiles); 3016*5f757f3fSDimitry Andric } 3017*5f757f3fSDimitry Andric 301885868e8aSDimitry Andric // Create synthesized sections such as .got and .plt. This is called before 301985868e8aSDimitry Andric // processSectionCommands() so that they can be placed by SECTIONS commands. 302006c3fb27SDimitry Andric invokeELFT(createSyntheticSections,); 302185868e8aSDimitry Andric 302285868e8aSDimitry Andric // Some input sections that are used for exception handling need to be moved 302385868e8aSDimitry Andric // into synthetic sections. Do that now so that they aren't assigned to 302485868e8aSDimitry Andric // output sections in the usual way. 302585868e8aSDimitry Andric if (!config->relocatable) 302685868e8aSDimitry Andric combineEhSections(); 302785868e8aSDimitry Andric 3028bdd1243dSDimitry Andric // Merge .riscv.attributes sections. 3029bdd1243dSDimitry Andric if (config->emachine == EM_RISCV) 3030bdd1243dSDimitry Andric mergeRISCVAttributesSections(); 3031bdd1243dSDimitry Andric 3032e8d8bef9SDimitry Andric { 3033e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Assign sections"); 3034e8d8bef9SDimitry Andric 303585868e8aSDimitry Andric // Create output sections described by SECTIONS commands. 303685868e8aSDimitry Andric script->processSectionCommands(); 303785868e8aSDimitry Andric 3038e8d8bef9SDimitry Andric // Linker scripts control how input sections are assigned to output 3039e8d8bef9SDimitry Andric // sections. Input sections that were not handled by scripts are called 3040e8d8bef9SDimitry Andric // "orphans", and they are assigned to output sections by the default rule. 3041e8d8bef9SDimitry Andric // Process that. 304285868e8aSDimitry Andric script->addOrphanSections(); 3043e8d8bef9SDimitry Andric } 3044e8d8bef9SDimitry Andric 3045e8d8bef9SDimitry Andric { 3046e8d8bef9SDimitry Andric llvm::TimeTraceScope timeScope("Merge/finalize input sections"); 304785868e8aSDimitry Andric 304885868e8aSDimitry Andric // Migrate InputSectionDescription::sectionBases to sections. This includes 304985868e8aSDimitry Andric // merging MergeInputSections into a single MergeSyntheticSection. From this 305085868e8aSDimitry Andric // point onwards InputSectionDescription::sections should be used instead of 305185868e8aSDimitry Andric // sectionBases. 30524824e7fdSDimitry Andric for (SectionCommand *cmd : script->sectionCommands) 305381ad6265SDimitry Andric if (auto *osd = dyn_cast<OutputDesc>(cmd)) 305481ad6265SDimitry Andric osd->osec.finalizeInputSections(); 3055e8d8bef9SDimitry Andric } 305685868e8aSDimitry Andric 305785868e8aSDimitry Andric // Two input sections with different output sections should not be folded. 305885868e8aSDimitry Andric // ICF runs after processSectionCommands() so that we know the output sections. 30590b57cec5SDimitry Andric if (config->icf != ICFLevel::None) { 30601fd87a68SDimitry Andric invokeELFT(findKeepUniqueSections, args); 306106c3fb27SDimitry Andric invokeELFT(doIcf,); 30620b57cec5SDimitry Andric } 30630b57cec5SDimitry Andric 30640b57cec5SDimitry Andric // Read the callgraph now that we know what was gced or icfed 3065*5f757f3fSDimitry Andric if (config->callGraphProfileSort != CGProfileSortKind::None) { 30660b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) 3067bdd1243dSDimitry Andric if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 30680b57cec5SDimitry Andric readCallGraph(*buffer); 306906c3fb27SDimitry Andric invokeELFT(readCallGraphsFromObjectFiles,); 30700b57cec5SDimitry Andric } 30710b57cec5SDimitry Andric 30720b57cec5SDimitry Andric // Write the result to the file. 307306c3fb27SDimitry Andric invokeELFT(writeResult,); 30740b57cec5SDimitry Andric } 3075