Path: blob/main/contrib/llvm-project/lld/ELF/Driver.cpp
34878 views
//===- Driver.cpp ---------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// The driver drives the entire linking process. It is responsible for9// parsing command line options and doing whatever it is instructed to do.10//11// One notable thing in the LLD's driver when compared to other linkers is12// that the LLD's driver is agnostic on the host operating system.13// Other linkers usually have implicit default values (such as a dynamic14// linker path or library paths) for each host OS.15//16// I don't think implicit default values are useful because they are17// usually explicitly specified by the compiler ctx.driver. They can even18// be harmful when you are doing cross-linking. Therefore, in LLD, we19// simply trust the compiler driver to pass all required options and20// don't try to make effort on our side.21//22//===----------------------------------------------------------------------===//2324#include "Driver.h"25#include "Config.h"26#include "ICF.h"27#include "InputFiles.h"28#include "InputSection.h"29#include "LTO.h"30#include "LinkerScript.h"31#include "MarkLive.h"32#include "OutputSections.h"33#include "ScriptParser.h"34#include "SymbolTable.h"35#include "Symbols.h"36#include "SyntheticSections.h"37#include "Target.h"38#include "Writer.h"39#include "lld/Common/Args.h"40#include "lld/Common/CommonLinkerContext.h"41#include "lld/Common/Driver.h"42#include "lld/Common/ErrorHandler.h"43#include "lld/Common/Filesystem.h"44#include "lld/Common/Memory.h"45#include "lld/Common/Strings.h"46#include "lld/Common/TargetOptionsCommandFlags.h"47#include "lld/Common/Version.h"48#include "llvm/ADT/STLExtras.h"49#include "llvm/ADT/SetVector.h"50#include "llvm/ADT/StringExtras.h"51#include "llvm/ADT/StringSwitch.h"52#include "llvm/Config/llvm-config.h"53#include "llvm/LTO/LTO.h"54#include "llvm/Object/Archive.h"55#include "llvm/Object/IRObjectFile.h"56#include "llvm/Remarks/HotnessThresholdParser.h"57#include "llvm/Support/CommandLine.h"58#include "llvm/Support/Compression.h"59#include "llvm/Support/FileSystem.h"60#include "llvm/Support/GlobPattern.h"61#include "llvm/Support/LEB128.h"62#include "llvm/Support/Parallel.h"63#include "llvm/Support/Path.h"64#include "llvm/Support/TarWriter.h"65#include "llvm/Support/TargetSelect.h"66#include "llvm/Support/TimeProfiler.h"67#include "llvm/Support/raw_ostream.h"68#include <cstdlib>69#include <tuple>70#include <utility>7172using namespace llvm;73using namespace llvm::ELF;74using namespace llvm::object;75using namespace llvm::sys;76using namespace llvm::support;77using namespace lld;78using namespace lld::elf;7980ConfigWrapper elf::config;81Ctx elf::ctx;8283static void setConfigs(opt::InputArgList &args);84static void readConfigs(opt::InputArgList &args);8586void elf::errorOrWarn(const Twine &msg) {87if (config->noinhibitExec)88warn(msg);89else90error(msg);91}9293void Ctx::reset() {94driver = LinkerDriver();95memoryBuffers.clear();96objectFiles.clear();97sharedFiles.clear();98binaryFiles.clear();99bitcodeFiles.clear();100lazyBitcodeFiles.clear();101inputSections.clear();102ehInputSections.clear();103duplicates.clear();104nonPrevailingSyms.clear();105whyExtractRecords.clear();106backwardReferences.clear();107auxiliaryFiles.clear();108internalFile = nullptr;109hasSympart.store(false, std::memory_order_relaxed);110hasTlsIe.store(false, std::memory_order_relaxed);111needsTlsLd.store(false, std::memory_order_relaxed);112scriptSymOrderCounter = 1;113scriptSymOrder.clear();114ltoAllVtablesHaveTypeInfos = false;115}116117llvm::raw_fd_ostream Ctx::openAuxiliaryFile(llvm::StringRef filename,118std::error_code &ec) {119using namespace llvm::sys::fs;120OpenFlags flags =121auxiliaryFiles.insert(filename).second ? OF_None : OF_Append;122return {filename, ec, flags};123}124125namespace lld {126namespace elf {127bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,128llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {129// This driver-specific context will be freed later by unsafeLldMain().130auto *ctx = new CommonLinkerContext;131132ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);133ctx->e.cleanupCallback = []() {134elf::ctx.reset();135symtab = SymbolTable();136137outputSections.clear();138symAux.clear();139140tar = nullptr;141in.reset();142143partitions.clear();144partitions.emplace_back();145146SharedFile::vernauxNum = 0;147};148ctx->e.logName = args::getFilenameWithoutExe(args[0]);149ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use "150"--error-limit=0 to see all errors)";151152config = ConfigWrapper();153script = ScriptWrapper();154155symAux.emplace_back();156157partitions.clear();158partitions.emplace_back();159160config->progName = args[0];161162elf::ctx.driver.linkerMain(args);163164return errorCount() == 0;165}166} // namespace elf167} // namespace lld168169// Parses a linker -m option.170static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {171uint8_t osabi = 0;172StringRef s = emul;173if (s.ends_with("_fbsd")) {174s = s.drop_back(5);175osabi = ELFOSABI_FREEBSD;176}177178std::pair<ELFKind, uint16_t> ret =179StringSwitch<std::pair<ELFKind, uint16_t>>(s)180.Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})181.Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})182.Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})183.Cases("armelfb", "armelfb_linux_eabi", {ELF32BEKind, EM_ARM})184.Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})185.Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})186.Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})187.Case("elf32lriscv", {ELF32LEKind, EM_RISCV})188.Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})189.Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})190.Case("elf32loongarch", {ELF32LEKind, EM_LOONGARCH})191.Case("elf64btsmip", {ELF64BEKind, EM_MIPS})192.Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})193.Case("elf64lriscv", {ELF64LEKind, EM_RISCV})194.Case("elf64ppc", {ELF64BEKind, EM_PPC64})195.Case("elf64lppc", {ELF64LEKind, EM_PPC64})196.Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})197.Case("elf_i386", {ELF32LEKind, EM_386})198.Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})199.Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})200.Case("msp430elf", {ELF32LEKind, EM_MSP430})201.Case("elf64_amdgpu", {ELF64LEKind, EM_AMDGPU})202.Case("elf64loongarch", {ELF64LEKind, EM_LOONGARCH})203.Case("elf64_s390", {ELF64BEKind, EM_S390})204.Case("hexagonelf", {ELF32LEKind, EM_HEXAGON})205.Default({ELFNoneKind, EM_NONE});206207if (ret.first == ELFNoneKind)208error("unknown emulation: " + emul);209if (ret.second == EM_MSP430)210osabi = ELFOSABI_STANDALONE;211else if (ret.second == EM_AMDGPU)212osabi = ELFOSABI_AMDGPU_HSA;213return std::make_tuple(ret.first, ret.second, osabi);214}215216// Returns slices of MB by parsing MB as an archive file.217// Each slice consists of a member file in the archive.218std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(219MemoryBufferRef mb) {220std::unique_ptr<Archive> file =221CHECK(Archive::create(mb),222mb.getBufferIdentifier() + ": failed to parse archive");223224std::vector<std::pair<MemoryBufferRef, uint64_t>> v;225Error err = Error::success();226bool addToTar = file->isThin() && tar;227for (const Archive::Child &c : file->children(err)) {228MemoryBufferRef mbref =229CHECK(c.getMemoryBufferRef(),230mb.getBufferIdentifier() +231": could not get the buffer for a child of the archive");232if (addToTar)233tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());234v.push_back(std::make_pair(mbref, c.getChildOffset()));235}236if (err)237fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +238toString(std::move(err)));239240// Take ownership of memory buffers created for members of thin archives.241std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers();242std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers));243244return v;245}246247static bool isBitcode(MemoryBufferRef mb) {248return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode;249}250251bool LinkerDriver::tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName,252uint64_t offsetInArchive, bool lazy) {253if (!config->fatLTOObjects)254return false;255Expected<MemoryBufferRef> fatLTOData =256IRObjectFile::findBitcodeInMemBuffer(mb);257if (errorToBool(fatLTOData.takeError()))258return false;259files.push_back(260make<BitcodeFile>(*fatLTOData, archiveName, offsetInArchive, lazy));261return true;262}263264// Opens a file and create a file object. Path has to be resolved already.265void LinkerDriver::addFile(StringRef path, bool withLOption) {266using namespace sys::fs;267268std::optional<MemoryBufferRef> buffer = readFile(path);269if (!buffer)270return;271MemoryBufferRef mbref = *buffer;272273if (config->formatBinary) {274files.push_back(make<BinaryFile>(mbref));275return;276}277278switch (identify_magic(mbref.getBuffer())) {279case file_magic::unknown:280readLinkerScript(mbref);281return;282case file_magic::archive: {283auto members = getArchiveMembers(mbref);284if (inWholeArchive) {285for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {286if (isBitcode(p.first))287files.push_back(make<BitcodeFile>(p.first, path, p.second, false));288else if (!tryAddFatLTOFile(p.first, path, p.second, false))289files.push_back(createObjFile(p.first, path));290}291return;292}293294archiveFiles.emplace_back(path, members.size());295296// Handle archives and --start-lib/--end-lib using the same code path. This297// scans all the ELF relocatable object files and bitcode files in the298// archive rather than just the index file, with the benefit that the299// symbols are only loaded once. For many projects archives see high300// utilization rates and it is a net performance win. --start-lib scans301// symbols in the same order that llvm-ar adds them to the index, so in the302// common case the semantics are identical. If the archive symbol table was303// created in a different order, or is incomplete, this strategy has304// different semantics. Such output differences are considered user error.305//306// All files within the archive get the same group ID to allow mutual307// references for --warn-backrefs.308bool saved = InputFile::isInGroup;309InputFile::isInGroup = true;310for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {311auto magic = identify_magic(p.first.getBuffer());312if (magic == file_magic::elf_relocatable) {313if (!tryAddFatLTOFile(p.first, path, p.second, true))314files.push_back(createObjFile(p.first, path, true));315} else if (magic == file_magic::bitcode)316files.push_back(make<BitcodeFile>(p.first, path, p.second, true));317else318warn(path + ": archive member '" + p.first.getBufferIdentifier() +319"' is neither ET_REL nor LLVM bitcode");320}321InputFile::isInGroup = saved;322if (!saved)323++InputFile::nextGroupId;324return;325}326case file_magic::elf_shared_object: {327if (config->isStatic) {328error("attempted static link of dynamic object " + path);329return;330}331332// Shared objects are identified by soname. soname is (if specified)333// DT_SONAME and falls back to filename. If a file was specified by -lfoo,334// the directory part is ignored. Note that path may be a temporary and335// cannot be stored into SharedFile::soName.336path = mbref.getBufferIdentifier();337auto *f =338make<SharedFile>(mbref, withLOption ? path::filename(path) : path);339f->init();340files.push_back(f);341return;342}343case file_magic::bitcode:344files.push_back(make<BitcodeFile>(mbref, "", 0, inLib));345break;346case file_magic::elf_relocatable:347if (!tryAddFatLTOFile(mbref, "", 0, inLib))348files.push_back(createObjFile(mbref, "", inLib));349break;350default:351error(path + ": unknown file type");352}353}354355// Add a given library by searching it from input search paths.356void LinkerDriver::addLibrary(StringRef name) {357if (std::optional<std::string> path = searchLibrary(name))358addFile(saver().save(*path), /*withLOption=*/true);359else360error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});361}362363// This function is called on startup. We need this for LTO since364// LTO calls LLVM functions to compile bitcode files to native code.365// Technically this can be delayed until we read bitcode files, but366// we don't bother to do lazily because the initialization is fast.367static void initLLVM() {368InitializeAllTargets();369InitializeAllTargetMCs();370InitializeAllAsmPrinters();371InitializeAllAsmParsers();372}373374// Some command line options or some combinations of them are not allowed.375// This function checks for such errors.376static void checkOptions() {377// The MIPS ABI as of 2016 does not support the GNU-style symbol lookup378// table which is a relatively new feature.379if (config->emachine == EM_MIPS && config->gnuHash)380error("the .gnu.hash section is not compatible with the MIPS target");381382if (config->emachine == EM_ARM) {383if (!config->cmseImplib) {384if (!config->cmseInputLib.empty())385error("--in-implib may not be used without --cmse-implib");386if (!config->cmseOutputLib.empty())387error("--out-implib may not be used without --cmse-implib");388}389} else {390if (config->cmseImplib)391error("--cmse-implib is only supported on ARM targets");392if (!config->cmseInputLib.empty())393error("--in-implib is only supported on ARM targets");394if (!config->cmseOutputLib.empty())395error("--out-implib is only supported on ARM targets");396}397398if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)399error("--fix-cortex-a53-843419 is only supported on AArch64 targets");400401if (config->fixCortexA8 && config->emachine != EM_ARM)402error("--fix-cortex-a8 is only supported on ARM targets");403404if (config->armBe8 && config->emachine != EM_ARM)405error("--be8 is only supported on ARM targets");406407if (config->fixCortexA8 && !config->isLE)408error("--fix-cortex-a8 is not supported on big endian targets");409410if (config->tocOptimize && config->emachine != EM_PPC64)411error("--toc-optimize is only supported on PowerPC64 targets");412413if (config->pcRelOptimize && config->emachine != EM_PPC64)414error("--pcrel-optimize is only supported on PowerPC64 targets");415416if (config->relaxGP && config->emachine != EM_RISCV)417error("--relax-gp is only supported on RISC-V targets");418419if (config->pie && config->shared)420error("-shared and -pie may not be used together");421422if (!config->shared && !config->filterList.empty())423error("-F may not be used without -shared");424425if (!config->shared && !config->auxiliaryList.empty())426error("-f may not be used without -shared");427428if (config->strip == StripPolicy::All && config->emitRelocs)429error("--strip-all and --emit-relocs may not be used together");430431if (config->zText && config->zIfuncNoplt)432error("-z text and -z ifunc-noplt may not be used together");433434if (config->relocatable) {435if (config->shared)436error("-r and -shared may not be used together");437if (config->gdbIndex)438error("-r and --gdb-index may not be used together");439if (config->icf != ICFLevel::None)440error("-r and --icf may not be used together");441if (config->pie)442error("-r and -pie may not be used together");443if (config->exportDynamic)444error("-r and --export-dynamic may not be used together");445if (config->debugNames)446error("-r and --debug-names may not be used together");447}448449if (config->executeOnly) {450if (config->emachine != EM_AARCH64)451error("--execute-only is only supported on AArch64 targets");452453if (config->singleRoRx && !script->hasSectionsCommand)454error("--execute-only and --no-rosegment cannot be used together");455}456457if (config->zRetpolineplt && config->zForceIbt)458error("-z force-ibt may not be used with -z retpolineplt");459460if (config->emachine != EM_AARCH64) {461if (config->zPacPlt)462error("-z pac-plt only supported on AArch64");463if (config->zForceBti)464error("-z force-bti only supported on AArch64");465if (config->zBtiReport != "none")466error("-z bti-report only supported on AArch64");467if (config->zPauthReport != "none")468error("-z pauth-report only supported on AArch64");469if (config->zGcsReport != "none")470error("-z gcs-report only supported on AArch64");471if (config->zGcs != GcsPolicy::Implicit)472error("-z gcs only supported on AArch64");473}474475if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&476config->zCetReport != "none")477error("-z cet-report only supported on X86 and X86_64");478}479480static const char *getReproduceOption(opt::InputArgList &args) {481if (auto *arg = args.getLastArg(OPT_reproduce))482return arg->getValue();483return getenv("LLD_REPRODUCE");484}485486static bool hasZOption(opt::InputArgList &args, StringRef key) {487bool ret = false;488for (auto *arg : args.filtered(OPT_z))489if (key == arg->getValue()) {490ret = true;491arg->claim();492}493return ret;494}495496static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,497bool defaultValue) {498for (auto *arg : args.filtered(OPT_z)) {499StringRef v = arg->getValue();500if (k1 == v)501defaultValue = true;502else if (k2 == v)503defaultValue = false;504else505continue;506arg->claim();507}508return defaultValue;509}510511static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {512auto ret = SeparateSegmentKind::None;513for (auto *arg : args.filtered(OPT_z)) {514StringRef v = arg->getValue();515if (v == "noseparate-code")516ret = SeparateSegmentKind::None;517else if (v == "separate-code")518ret = SeparateSegmentKind::Code;519else if (v == "separate-loadable-segments")520ret = SeparateSegmentKind::Loadable;521else522continue;523arg->claim();524}525return ret;526}527528static GnuStackKind getZGnuStack(opt::InputArgList &args) {529auto ret = GnuStackKind::NoExec;530for (auto *arg : args.filtered(OPT_z)) {531StringRef v = arg->getValue();532if (v == "execstack")533ret = GnuStackKind::Exec;534else if (v == "noexecstack")535ret = GnuStackKind::NoExec;536else if (v == "nognustack")537ret = GnuStackKind::None;538else539continue;540arg->claim();541}542return ret;543}544545static uint8_t getZStartStopVisibility(opt::InputArgList &args) {546uint8_t ret = STV_PROTECTED;547for (auto *arg : args.filtered(OPT_z)) {548std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');549if (kv.first == "start-stop-visibility") {550arg->claim();551if (kv.second == "default")552ret = STV_DEFAULT;553else if (kv.second == "internal")554ret = STV_INTERNAL;555else if (kv.second == "hidden")556ret = STV_HIDDEN;557else if (kv.second == "protected")558ret = STV_PROTECTED;559else560error("unknown -z start-stop-visibility= value: " +561StringRef(kv.second));562}563}564return ret;565}566567static GcsPolicy getZGcs(opt::InputArgList &args) {568GcsPolicy ret = GcsPolicy::Implicit;569for (auto *arg : args.filtered(OPT_z)) {570std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');571if (kv.first == "gcs") {572arg->claim();573if (kv.second == "implicit")574ret = GcsPolicy::Implicit;575else if (kv.second == "never")576ret = GcsPolicy::Never;577else if (kv.second == "always")578ret = GcsPolicy::Always;579else580error("unknown -z gcs= value: " + kv.second);581}582}583return ret;584}585586// Report a warning for an unknown -z option.587static void checkZOptions(opt::InputArgList &args) {588// This function is called before getTarget(), when certain options are not589// initialized yet. Claim them here.590args::getZOptionValue(args, OPT_z, "max-page-size", 0);591args::getZOptionValue(args, OPT_z, "common-page-size", 0);592getZFlag(args, "rel", "rela", false);593for (auto *arg : args.filtered(OPT_z))594if (!arg->isClaimed())595warn("unknown -z value: " + StringRef(arg->getValue()));596}597598constexpr const char *saveTempsValues[] = {599"resolution", "preopt", "promote", "internalize", "import",600"opt", "precodegen", "prelink", "combinedindex"};601602void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {603ELFOptTable parser;604opt::InputArgList args = parser.parse(argsArr.slice(1));605606// Interpret these flags early because error()/warn() depend on them.607errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);608errorHandler().fatalWarnings =609args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) &&610!args.hasArg(OPT_no_warnings);611errorHandler().suppressWarnings = args.hasArg(OPT_no_warnings);612613// Handle -help614if (args.hasArg(OPT_help)) {615printHelp();616return;617}618619// Handle -v or -version.620//621// A note about "compatible with GNU linkers" message: this is a hack for622// scripts generated by GNU Libtool up to 2021-10 to recognize LLD as623// a GNU compatible linker. See624// <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.625//626// This is somewhat ugly hack, but in reality, we had no choice other627// than doing this. Considering the very long release cycle of Libtool,628// it is not easy to improve it to recognize LLD as a GNU compatible629// linker in a timely manner. Even if we can make it, there are still a630// lot of "configure" scripts out there that are generated by old version631// of Libtool. We cannot convince every software developer to migrate to632// the latest version and re-generate scripts. So we have this hack.633if (args.hasArg(OPT_v) || args.hasArg(OPT_version))634message(getLLDVersion() + " (compatible with GNU linkers)");635636if (const char *path = getReproduceOption(args)) {637// Note that --reproduce is a debug option so you can ignore it638// if you are trying to understand the whole picture of the code.639Expected<std::unique_ptr<TarWriter>> errOrWriter =640TarWriter::create(path, path::stem(path));641if (errOrWriter) {642tar = std::move(*errOrWriter);643tar->append("response.txt", createResponseFile(args));644tar->append("version.txt", getLLDVersion() + "\n");645StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);646if (!ltoSampleProfile.empty())647readFile(ltoSampleProfile);648} else {649error("--reproduce: " + toString(errOrWriter.takeError()));650}651}652653readConfigs(args);654checkZOptions(args);655656// The behavior of -v or --version is a bit strange, but this is657// needed for compatibility with GNU linkers.658if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))659return;660if (args.hasArg(OPT_version))661return;662663// Initialize time trace profiler.664if (config->timeTraceEnabled)665timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);666667{668llvm::TimeTraceScope timeScope("ExecuteLinker");669670initLLVM();671createFiles(args);672if (errorCount())673return;674675inferMachineType();676setConfigs(args);677checkOptions();678if (errorCount())679return;680681invokeELFT(link, args);682}683684if (config->timeTraceEnabled) {685checkError(timeTraceProfilerWrite(686args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));687timeTraceProfilerCleanup();688}689}690691static std::string getRpath(opt::InputArgList &args) {692SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath);693return llvm::join(v.begin(), v.end(), ":");694}695696// Determines what we should do if there are remaining unresolved697// symbols after the name resolution.698static void setUnresolvedSymbolPolicy(opt::InputArgList &args) {699UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,700OPT_warn_unresolved_symbols, true)701? UnresolvedPolicy::ReportError702: UnresolvedPolicy::Warn;703// -shared implies --unresolved-symbols=ignore-all because missing704// symbols are likely to be resolved at runtime.705bool diagRegular = !config->shared, diagShlib = !config->shared;706707for (const opt::Arg *arg : args) {708switch (arg->getOption().getID()) {709case OPT_unresolved_symbols: {710StringRef s = arg->getValue();711if (s == "ignore-all") {712diagRegular = false;713diagShlib = false;714} else if (s == "ignore-in-object-files") {715diagRegular = false;716diagShlib = true;717} else if (s == "ignore-in-shared-libs") {718diagRegular = true;719diagShlib = false;720} else if (s == "report-all") {721diagRegular = true;722diagShlib = true;723} else {724error("unknown --unresolved-symbols value: " + s);725}726break;727}728case OPT_no_undefined:729diagRegular = true;730break;731case OPT_z:732if (StringRef(arg->getValue()) == "defs")733diagRegular = true;734else if (StringRef(arg->getValue()) == "undefs")735diagRegular = false;736else737break;738arg->claim();739break;740case OPT_allow_shlib_undefined:741diagShlib = false;742break;743case OPT_no_allow_shlib_undefined:744diagShlib = true;745break;746}747}748749config->unresolvedSymbols =750diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;751config->unresolvedSymbolsInShlib =752diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;753}754755static Target2Policy getTarget2(opt::InputArgList &args) {756StringRef s = args.getLastArgValue(OPT_target2, "got-rel");757if (s == "rel")758return Target2Policy::Rel;759if (s == "abs")760return Target2Policy::Abs;761if (s == "got-rel")762return Target2Policy::GotRel;763error("unknown --target2 option: " + s);764return Target2Policy::GotRel;765}766767static bool isOutputFormatBinary(opt::InputArgList &args) {768StringRef s = args.getLastArgValue(OPT_oformat, "elf");769if (s == "binary")770return true;771if (!s.starts_with("elf"))772error("unknown --oformat value: " + s);773return false;774}775776static DiscardPolicy getDiscard(opt::InputArgList &args) {777auto *arg =778args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);779if (!arg)780return DiscardPolicy::Default;781if (arg->getOption().getID() == OPT_discard_all)782return DiscardPolicy::All;783if (arg->getOption().getID() == OPT_discard_locals)784return DiscardPolicy::Locals;785return DiscardPolicy::None;786}787788static StringRef getDynamicLinker(opt::InputArgList &args) {789auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);790if (!arg)791return "";792if (arg->getOption().getID() == OPT_no_dynamic_linker) {793// --no-dynamic-linker suppresses undefined weak symbols in .dynsym794config->noDynamicLinker = true;795return "";796}797return arg->getValue();798}799800static int getMemtagMode(opt::InputArgList &args) {801StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode);802if (memtagModeArg.empty()) {803if (config->androidMemtagStack)804warn("--android-memtag-mode is unspecified, leaving "805"--android-memtag-stack a no-op");806else if (config->androidMemtagHeap)807warn("--android-memtag-mode is unspecified, leaving "808"--android-memtag-heap a no-op");809return ELF::NT_MEMTAG_LEVEL_NONE;810}811812if (memtagModeArg == "sync")813return ELF::NT_MEMTAG_LEVEL_SYNC;814if (memtagModeArg == "async")815return ELF::NT_MEMTAG_LEVEL_ASYNC;816if (memtagModeArg == "none")817return ELF::NT_MEMTAG_LEVEL_NONE;818819error("unknown --android-memtag-mode value: \"" + memtagModeArg +820"\", should be one of {async, sync, none}");821return ELF::NT_MEMTAG_LEVEL_NONE;822}823824static ICFLevel getICF(opt::InputArgList &args) {825auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);826if (!arg || arg->getOption().getID() == OPT_icf_none)827return ICFLevel::None;828if (arg->getOption().getID() == OPT_icf_safe)829return ICFLevel::Safe;830return ICFLevel::All;831}832833static StripPolicy getStrip(opt::InputArgList &args) {834if (args.hasArg(OPT_relocatable))835return StripPolicy::None;836837auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);838if (!arg)839return StripPolicy::None;840if (arg->getOption().getID() == OPT_strip_all)841return StripPolicy::All;842return StripPolicy::Debug;843}844845static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,846const opt::Arg &arg) {847uint64_t va = 0;848if (s.starts_with("0x"))849s = s.drop_front(2);850if (!to_integer(s, va, 16))851error("invalid argument: " + arg.getAsString(args));852return va;853}854855static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {856StringMap<uint64_t> ret;857for (auto *arg : args.filtered(OPT_section_start)) {858StringRef name;859StringRef addr;860std::tie(name, addr) = StringRef(arg->getValue()).split('=');861ret[name] = parseSectionAddress(addr, args, *arg);862}863864if (auto *arg = args.getLastArg(OPT_Ttext))865ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);866if (auto *arg = args.getLastArg(OPT_Tdata))867ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);868if (auto *arg = args.getLastArg(OPT_Tbss))869ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);870return ret;871}872873static SortSectionPolicy getSortSection(opt::InputArgList &args) {874StringRef s = args.getLastArgValue(OPT_sort_section);875if (s == "alignment")876return SortSectionPolicy::Alignment;877if (s == "name")878return SortSectionPolicy::Name;879if (!s.empty())880error("unknown --sort-section rule: " + s);881return SortSectionPolicy::Default;882}883884static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {885StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");886if (s == "warn")887return OrphanHandlingPolicy::Warn;888if (s == "error")889return OrphanHandlingPolicy::Error;890if (s != "place")891error("unknown --orphan-handling mode: " + s);892return OrphanHandlingPolicy::Place;893}894895// Parse --build-id or --build-id=<style>. We handle "tree" as a896// synonym for "sha1" because all our hash functions including897// --build-id=sha1 are actually tree hashes for performance reasons.898static std::pair<BuildIdKind, SmallVector<uint8_t, 0>>899getBuildId(opt::InputArgList &args) {900auto *arg = args.getLastArg(OPT_build_id);901if (!arg)902return {BuildIdKind::None, {}};903904StringRef s = arg->getValue();905if (s == "fast")906return {BuildIdKind::Fast, {}};907if (s == "md5")908return {BuildIdKind::Md5, {}};909if (s == "sha1" || s == "tree")910return {BuildIdKind::Sha1, {}};911if (s == "uuid")912return {BuildIdKind::Uuid, {}};913if (s.starts_with("0x"))914return {BuildIdKind::Hexstring, parseHex(s.substr(2))};915916if (s != "none")917error("unknown --build-id style: " + s);918return {BuildIdKind::None, {}};919}920921static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {922StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");923if (s == "android")924return {true, false};925if (s == "relr")926return {false, true};927if (s == "android+relr")928return {true, true};929930if (s != "none")931error("unknown --pack-dyn-relocs format: " + s);932return {false, false};933}934935static void readCallGraph(MemoryBufferRef mb) {936// Build a map from symbol name to section937DenseMap<StringRef, Symbol *> map;938for (ELFFileBase *file : ctx.objectFiles)939for (Symbol *sym : file->getSymbols())940map[sym->getName()] = sym;941942auto findSection = [&](StringRef name) -> InputSectionBase * {943Symbol *sym = map.lookup(name);944if (!sym) {945if (config->warnSymbolOrdering)946warn(mb.getBufferIdentifier() + ": no such symbol: " + name);947return nullptr;948}949maybeWarnUnorderableSymbol(sym);950951if (Defined *dr = dyn_cast_or_null<Defined>(sym))952return dyn_cast_or_null<InputSectionBase>(dr->section);953return nullptr;954};955956for (StringRef line : args::getLines(mb)) {957SmallVector<StringRef, 3> fields;958line.split(fields, ' ');959uint64_t count;960961if (fields.size() != 3 || !to_integer(fields[2], count)) {962error(mb.getBufferIdentifier() + ": parse error");963return;964}965966if (InputSectionBase *from = findSection(fields[0]))967if (InputSectionBase *to = findSection(fields[1]))968config->callGraphProfile[std::make_pair(from, to)] += count;969}970}971972// If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns973// true and populates cgProfile and symbolIndices.974template <class ELFT>975static bool976processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices,977ArrayRef<typename ELFT::CGProfile> &cgProfile,978ObjFile<ELFT> *inputObj) {979if (inputObj->cgProfileSectionIndex == SHN_UNDEF)980return false;981982ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =983inputObj->template getELFShdrs<ELFT>();984symbolIndices.clear();985const ELFFile<ELFT> &obj = inputObj->getObj();986cgProfile =987check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(988objSections[inputObj->cgProfileSectionIndex]));989990for (size_t i = 0, e = objSections.size(); i < e; ++i) {991const Elf_Shdr_Impl<ELFT> &sec = objSections[i];992if (sec.sh_info == inputObj->cgProfileSectionIndex) {993if (sec.sh_type == SHT_CREL) {994auto crels =995CHECK(obj.crels(sec), "could not retrieve cg profile rela section");996for (const auto &rel : crels.first)997symbolIndices.push_back(rel.getSymbol(false));998for (const auto &rel : crels.second)999symbolIndices.push_back(rel.getSymbol(false));1000break;1001}1002if (sec.sh_type == SHT_RELA) {1003ArrayRef<typename ELFT::Rela> relas =1004CHECK(obj.relas(sec), "could not retrieve cg profile rela section");1005for (const typename ELFT::Rela &rel : relas)1006symbolIndices.push_back(rel.getSymbol(config->isMips64EL));1007break;1008}1009if (sec.sh_type == SHT_REL) {1010ArrayRef<typename ELFT::Rel> rels =1011CHECK(obj.rels(sec), "could not retrieve cg profile rel section");1012for (const typename ELFT::Rel &rel : rels)1013symbolIndices.push_back(rel.getSymbol(config->isMips64EL));1014break;1015}1016}1017}1018if (symbolIndices.empty())1019warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");1020return !symbolIndices.empty();1021}10221023template <class ELFT> static void readCallGraphsFromObjectFiles() {1024SmallVector<uint32_t, 32> symbolIndices;1025ArrayRef<typename ELFT::CGProfile> cgProfile;1026for (auto file : ctx.objectFiles) {1027auto *obj = cast<ObjFile<ELFT>>(file);1028if (!processCallGraphRelocations(symbolIndices, cgProfile, obj))1029continue;10301031if (symbolIndices.size() != cgProfile.size() * 2)1032fatal("number of relocations doesn't match Weights");10331034for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {1035const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];1036uint32_t fromIndex = symbolIndices[i * 2];1037uint32_t toIndex = symbolIndices[i * 2 + 1];1038auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));1039auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));1040if (!fromSym || !toSym)1041continue;10421043auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);1044auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);1045if (from && to)1046config->callGraphProfile[{from, to}] += cgpe.cgp_weight;1047}1048}1049}10501051template <class ELFT>1052static void ltoValidateAllVtablesHaveTypeInfos(opt::InputArgList &args) {1053DenseSet<StringRef> typeInfoSymbols;1054SmallSetVector<StringRef, 0> vtableSymbols;1055auto processVtableAndTypeInfoSymbols = [&](StringRef name) {1056if (name.consume_front("_ZTI"))1057typeInfoSymbols.insert(name);1058else if (name.consume_front("_ZTV"))1059vtableSymbols.insert(name);1060};10611062// Examine all native symbol tables.1063for (ELFFileBase *f : ctx.objectFiles) {1064using Elf_Sym = typename ELFT::Sym;1065for (const Elf_Sym &s : f->template getGlobalELFSyms<ELFT>()) {1066if (s.st_shndx != SHN_UNDEF) {1067StringRef name = check(s.getName(f->getStringTable()));1068processVtableAndTypeInfoSymbols(name);1069}1070}1071}10721073for (SharedFile *f : ctx.sharedFiles) {1074using Elf_Sym = typename ELFT::Sym;1075for (const Elf_Sym &s : f->template getELFSyms<ELFT>()) {1076if (s.st_shndx != SHN_UNDEF) {1077StringRef name = check(s.getName(f->getStringTable()));1078processVtableAndTypeInfoSymbols(name);1079}1080}1081}10821083SmallSetVector<StringRef, 0> vtableSymbolsWithNoRTTI;1084for (StringRef s : vtableSymbols)1085if (!typeInfoSymbols.count(s))1086vtableSymbolsWithNoRTTI.insert(s);10871088// Remove known safe symbols.1089for (auto *arg : args.filtered(OPT_lto_known_safe_vtables)) {1090StringRef knownSafeName = arg->getValue();1091if (!knownSafeName.consume_front("_ZTV"))1092error("--lto-known-safe-vtables=: expected symbol to start with _ZTV, "1093"but got " +1094knownSafeName);1095Expected<GlobPattern> pat = GlobPattern::create(knownSafeName);1096if (!pat)1097error("--lto-known-safe-vtables=: " + toString(pat.takeError()));1098vtableSymbolsWithNoRTTI.remove_if(1099[&](StringRef s) { return pat->match(s); });1100}11011102ctx.ltoAllVtablesHaveTypeInfos = vtableSymbolsWithNoRTTI.empty();1103// Check for unmatched RTTI symbols1104for (StringRef s : vtableSymbolsWithNoRTTI) {1105message(1106"--lto-validate-all-vtables-have-type-infos: RTTI missing for vtable "1107"_ZTV" +1108s + ", --lto-whole-program-visibility disabled");1109}1110}11111112static CGProfileSortKind getCGProfileSortKind(opt::InputArgList &args) {1113StringRef s = args.getLastArgValue(OPT_call_graph_profile_sort, "cdsort");1114if (s == "hfsort")1115return CGProfileSortKind::Hfsort;1116if (s == "cdsort")1117return CGProfileSortKind::Cdsort;1118if (s != "none")1119error("unknown --call-graph-profile-sort= value: " + s);1120return CGProfileSortKind::None;1121}11221123static DebugCompressionType getCompressionType(StringRef s, StringRef option) {1124DebugCompressionType type = StringSwitch<DebugCompressionType>(s)1125.Case("zlib", DebugCompressionType::Zlib)1126.Case("zstd", DebugCompressionType::Zstd)1127.Default(DebugCompressionType::None);1128if (type == DebugCompressionType::None) {1129if (s != "none")1130error("unknown " + option + " value: " + s);1131} else if (const char *reason = compression::getReasonIfUnsupported(1132compression::formatFor(type))) {1133error(option + ": " + reason);1134}1135return type;1136}11371138static StringRef getAliasSpelling(opt::Arg *arg) {1139if (const opt::Arg *alias = arg->getAlias())1140return alias->getSpelling();1141return arg->getSpelling();1142}11431144static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,1145unsigned id) {1146auto *arg = args.getLastArg(id);1147if (!arg)1148return {"", ""};11491150StringRef s = arg->getValue();1151std::pair<StringRef, StringRef> ret = s.split(';');1152if (ret.second.empty())1153error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);1154return ret;1155}11561157// Parse options of the form "old;new[;extra]".1158static std::tuple<StringRef, StringRef, StringRef>1159getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {1160auto [oldDir, second] = getOldNewOptions(args, id);1161auto [newDir, extraDir] = second.split(';');1162return {oldDir, newDir, extraDir};1163}11641165// Parse the symbol ordering file and warn for any duplicate entries.1166static SmallVector<StringRef, 0> getSymbolOrderingFile(MemoryBufferRef mb) {1167SetVector<StringRef, SmallVector<StringRef, 0>> names;1168for (StringRef s : args::getLines(mb))1169if (!names.insert(s) && config->warnSymbolOrdering)1170warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);11711172return names.takeVector();1173}11741175static bool getIsRela(opt::InputArgList &args) {1176// The psABI specifies the default relocation entry format.1177bool rela = is_contained({EM_AARCH64, EM_AMDGPU, EM_HEXAGON, EM_LOONGARCH,1178EM_PPC, EM_PPC64, EM_RISCV, EM_S390, EM_X86_64},1179config->emachine);1180// If -z rel or -z rela is specified, use the last option.1181for (auto *arg : args.filtered(OPT_z)) {1182StringRef s(arg->getValue());1183if (s == "rel")1184rela = false;1185else if (s == "rela")1186rela = true;1187else1188continue;1189arg->claim();1190}1191return rela;1192}11931194static void parseClangOption(StringRef opt, const Twine &msg) {1195std::string err;1196raw_string_ostream os(err);11971198const char *argv[] = {config->progName.data(), opt.data()};1199if (cl::ParseCommandLineOptions(2, argv, "", &os))1200return;1201os.flush();1202error(msg + ": " + StringRef(err).trim());1203}12041205// Checks the parameter of the bti-report and cet-report options.1206static bool isValidReportString(StringRef arg) {1207return arg == "none" || arg == "warning" || arg == "error";1208}12091210// Process a remap pattern 'from-glob=to-file'.1211static bool remapInputs(StringRef line, const Twine &location) {1212SmallVector<StringRef, 0> fields;1213line.split(fields, '=');1214if (fields.size() != 2 || fields[1].empty()) {1215error(location + ": parse error, not 'from-glob=to-file'");1216return true;1217}1218if (!hasWildcard(fields[0]))1219config->remapInputs[fields[0]] = fields[1];1220else if (Expected<GlobPattern> pat = GlobPattern::create(fields[0]))1221config->remapInputsWildcards.emplace_back(std::move(*pat), fields[1]);1222else {1223error(location + ": " + toString(pat.takeError()) + ": " + fields[0]);1224return true;1225}1226return false;1227}12281229// Initializes Config members by the command line options.1230static void readConfigs(opt::InputArgList &args) {1231errorHandler().verbose = args.hasArg(OPT_verbose);1232errorHandler().vsDiagnostics =1233args.hasArg(OPT_visual_studio_diagnostics_format, false);12341235config->allowMultipleDefinition =1236hasZOption(args, "muldefs") ||1237args.hasFlag(OPT_allow_multiple_definition,1238OPT_no_allow_multiple_definition, false);1239config->androidMemtagHeap =1240args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false);1241config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack,1242OPT_no_android_memtag_stack, false);1243config->fatLTOObjects =1244args.hasFlag(OPT_fat_lto_objects, OPT_no_fat_lto_objects, false);1245config->androidMemtagMode = getMemtagMode(args);1246config->auxiliaryList = args::getStrings(args, OPT_auxiliary);1247config->armBe8 = args.hasArg(OPT_be8);1248if (opt::Arg *arg = args.getLastArg(1249OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,1250OPT_Bsymbolic_functions, OPT_Bsymbolic_non_weak, OPT_Bsymbolic)) {1251if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))1252config->bsymbolic = BsymbolicKind::NonWeakFunctions;1253else if (arg->getOption().matches(OPT_Bsymbolic_functions))1254config->bsymbolic = BsymbolicKind::Functions;1255else if (arg->getOption().matches(OPT_Bsymbolic_non_weak))1256config->bsymbolic = BsymbolicKind::NonWeak;1257else if (arg->getOption().matches(OPT_Bsymbolic))1258config->bsymbolic = BsymbolicKind::All;1259}1260config->callGraphProfileSort = getCGProfileSortKind(args);1261config->checkSections =1262args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);1263config->chroot = args.getLastArgValue(OPT_chroot);1264if (auto *arg = args.getLastArg(OPT_compress_debug_sections)) {1265config->compressDebugSections =1266getCompressionType(arg->getValue(), "--compress-debug-sections");1267}1268config->cref = args.hasArg(OPT_cref);1269config->optimizeBBJumps =1270args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);1271config->debugNames = args.hasFlag(OPT_debug_names, OPT_no_debug_names, false);1272config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);1273config->dependencyFile = args.getLastArgValue(OPT_dependency_file);1274config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);1275config->disableVerify = args.hasArg(OPT_disable_verify);1276config->discard = getDiscard(args);1277config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);1278config->dynamicLinker = getDynamicLinker(args);1279config->ehFrameHdr =1280args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);1281config->emitLLVM = args.hasArg(OPT_lto_emit_llvm);1282config->emitRelocs = args.hasArg(OPT_emit_relocs);1283config->enableNewDtags =1284args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);1285config->enableNonContiguousRegions =1286args.hasArg(OPT_enable_non_contiguous_regions);1287config->entry = args.getLastArgValue(OPT_entry);12881289errorHandler().errorHandlingScript =1290args.getLastArgValue(OPT_error_handling_script);12911292config->executeOnly =1293args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);1294config->exportDynamic =1295args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) ||1296args.hasArg(OPT_shared);1297config->filterList = args::getStrings(args, OPT_filter);1298config->fini = args.getLastArgValue(OPT_fini, "_fini");1299config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&1300!args.hasArg(OPT_relocatable);1301config->cmseImplib = args.hasArg(OPT_cmse_implib);1302config->cmseInputLib = args.getLastArgValue(OPT_in_implib);1303config->cmseOutputLib = args.getLastArgValue(OPT_out_implib);1304config->fixCortexA8 =1305args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);1306config->fortranCommon =1307args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false);1308config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);1309config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);1310config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);1311config->icf = getICF(args);1312config->ignoreDataAddressEquality =1313args.hasArg(OPT_ignore_data_address_equality);1314config->ignoreFunctionAddressEquality =1315args.hasArg(OPT_ignore_function_address_equality);1316config->init = args.getLastArgValue(OPT_init, "_init");1317config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);1318config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);1319config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);1320config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,1321OPT_no_lto_pgo_warn_mismatch, true);1322config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);1323config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);1324config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);1325config->ltoWholeProgramVisibility =1326args.hasFlag(OPT_lto_whole_program_visibility,1327OPT_no_lto_whole_program_visibility, false);1328config->ltoValidateAllVtablesHaveTypeInfos =1329args.hasFlag(OPT_lto_validate_all_vtables_have_type_infos,1330OPT_no_lto_validate_all_vtables_have_type_infos, false);1331config->ltoo = args::getInteger(args, OPT_lto_O, 2);1332if (config->ltoo > 3)1333error("invalid optimization level for LTO: " + Twine(config->ltoo));1334unsigned ltoCgo =1335args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo));1336if (auto level = CodeGenOpt::getLevel(ltoCgo))1337config->ltoCgo = *level;1338else1339error("invalid codegen optimization level for LTO: " + Twine(ltoCgo));1340config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);1341config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);1342config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);1343config->ltoBBAddrMap =1344args.hasFlag(OPT_lto_basic_block_address_map,1345OPT_no_lto_basic_block_address_map, false);1346config->ltoBasicBlockSections =1347args.getLastArgValue(OPT_lto_basic_block_sections);1348config->ltoUniqueBasicBlockSectionNames =1349args.hasFlag(OPT_lto_unique_basic_block_section_names,1350OPT_no_lto_unique_basic_block_section_names, false);1351config->mapFile = args.getLastArgValue(OPT_Map);1352config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);1353config->mergeArmExidx =1354args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);1355config->mmapOutputFile =1356args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);1357config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);1358config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);1359config->nostdlib = args.hasArg(OPT_nostdlib);1360config->oFormatBinary = isOutputFormatBinary(args);1361config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);1362config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);1363config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file);13641365// Parse remarks hotness threshold. Valid value is either integer or 'auto'.1366if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {1367auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());1368if (!resultOrErr)1369error(arg->getSpelling() + ": invalid argument '" + arg->getValue() +1370"', only integer or 'auto' is supported");1371else1372config->optRemarksHotnessThreshold = *resultOrErr;1373}13741375config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);1376config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);1377config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);1378config->optimize = args::getInteger(args, OPT_O, 1);1379config->orphanHandling = getOrphanHandling(args);1380config->outputFile = args.getLastArgValue(OPT_o);1381config->packageMetadata = args.getLastArgValue(OPT_package_metadata);1382config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);1383config->printIcfSections =1384args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);1385config->printGcSections =1386args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);1387config->printMemoryUsage = args.hasArg(OPT_print_memory_usage);1388config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);1389config->printSymbolOrder =1390args.getLastArgValue(OPT_print_symbol_order);1391config->rejectMismatch = !args.hasArg(OPT_no_warn_mismatch);1392config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true);1393config->relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false);1394config->rpath = getRpath(args);1395config->relocatable = args.hasArg(OPT_relocatable);1396config->resolveGroups =1397!args.hasArg(OPT_relocatable) || args.hasArg(OPT_force_group_allocation);13981399if (args.hasArg(OPT_save_temps)) {1400// --save-temps implies saving all temps.1401for (const char *s : saveTempsValues)1402config->saveTempsArgs.insert(s);1403} else {1404for (auto *arg : args.filtered(OPT_save_temps_eq)) {1405StringRef s = arg->getValue();1406if (llvm::is_contained(saveTempsValues, s))1407config->saveTempsArgs.insert(s);1408else1409error("unknown --save-temps value: " + s);1410}1411}14121413config->searchPaths = args::getStrings(args, OPT_library_path);1414config->sectionStartMap = getSectionStartMap(args);1415config->shared = args.hasArg(OPT_shared);1416config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);1417config->soName = args.getLastArgValue(OPT_soname);1418config->sortSection = getSortSection(args);1419config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);1420config->strip = getStrip(args);1421config->sysroot = args.getLastArgValue(OPT_sysroot);1422config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);1423config->target2 = getTarget2(args);1424config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);1425config->thinLTOCachePolicy = CHECK(1426parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),1427"--thinlto-cache-policy: invalid cache policy");1428config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);1429config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||1430args.hasArg(OPT_thinlto_index_only) ||1431args.hasArg(OPT_thinlto_index_only_eq);1432config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||1433args.hasArg(OPT_thinlto_index_only_eq);1434config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);1435config->thinLTOObjectSuffixReplace =1436getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);1437std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,1438config->thinLTOPrefixReplaceNativeObject) =1439getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace_eq);1440if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {1441if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))1442error("--thinlto-object-suffix-replace is not supported with "1443"--thinlto-emit-index-files");1444else if (args.hasArg(OPT_thinlto_prefix_replace_eq))1445error("--thinlto-prefix-replace is not supported with "1446"--thinlto-emit-index-files");1447}1448if (!config->thinLTOPrefixReplaceNativeObject.empty() &&1449config->thinLTOIndexOnlyArg.empty()) {1450error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "1451"--thinlto-index-only=");1452}1453config->thinLTOModulesToCompile =1454args::getStrings(args, OPT_thinlto_single_module_eq);1455config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);1456config->timeTraceGranularity =1457args::getInteger(args, OPT_time_trace_granularity, 500);1458config->trace = args.hasArg(OPT_trace);1459config->undefined = args::getStrings(args, OPT_undefined);1460config->undefinedVersion =1461args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false);1462config->unique = args.hasArg(OPT_unique);1463config->useAndroidRelrTags = args.hasFlag(1464OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);1465config->warnBackrefs =1466args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);1467config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);1468config->warnSymbolOrdering =1469args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);1470config->whyExtract = args.getLastArgValue(OPT_why_extract);1471config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);1472config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);1473config->zForceBti = hasZOption(args, "force-bti");1474config->zForceIbt = hasZOption(args, "force-ibt");1475config->zGcs = getZGcs(args);1476config->zGlobal = hasZOption(args, "global");1477config->zGnustack = getZGnuStack(args);1478config->zHazardplt = hasZOption(args, "hazardplt");1479config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");1480config->zInitfirst = hasZOption(args, "initfirst");1481config->zInterpose = hasZOption(args, "interpose");1482config->zKeepTextSectionPrefix = getZFlag(1483args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);1484config->zLrodataAfterBss =1485getZFlag(args, "lrodata-after-bss", "nolrodata-after-bss", false);1486config->zNodefaultlib = hasZOption(args, "nodefaultlib");1487config->zNodelete = hasZOption(args, "nodelete");1488config->zNodlopen = hasZOption(args, "nodlopen");1489config->zNow = getZFlag(args, "now", "lazy", false);1490config->zOrigin = hasZOption(args, "origin");1491config->zPacPlt = hasZOption(args, "pac-plt");1492config->zRelro = getZFlag(args, "relro", "norelro", true);1493config->zRetpolineplt = hasZOption(args, "retpolineplt");1494config->zRodynamic = hasZOption(args, "rodynamic");1495config->zSeparate = getZSeparate(args);1496config->zShstk = hasZOption(args, "shstk");1497config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);1498config->zStartStopGC =1499getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);1500config->zStartStopVisibility = getZStartStopVisibility(args);1501config->zText = getZFlag(args, "text", "notext", true);1502config->zWxneeded = hasZOption(args, "wxneeded");1503setUnresolvedSymbolPolicy(args);1504config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";15051506if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {1507if (arg->getOption().matches(OPT_eb))1508config->optEB = true;1509else1510config->optEL = true;1511}15121513for (opt::Arg *arg : args.filtered(OPT_remap_inputs)) {1514StringRef value(arg->getValue());1515remapInputs(value, arg->getSpelling());1516}1517for (opt::Arg *arg : args.filtered(OPT_remap_inputs_file)) {1518StringRef filename(arg->getValue());1519std::optional<MemoryBufferRef> buffer = readFile(filename);1520if (!buffer)1521continue;1522// Parse 'from-glob=to-file' lines, ignoring #-led comments.1523for (auto [lineno, line] : llvm::enumerate(args::getLines(*buffer)))1524if (remapInputs(line, filename + ":" + Twine(lineno + 1)))1525break;1526}15271528for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {1529constexpr StringRef errPrefix = "--shuffle-sections=: ";1530std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');1531if (kv.first.empty() || kv.second.empty()) {1532error(errPrefix + "expected <section_glob>=<seed>, but got '" +1533arg->getValue() + "'");1534continue;1535}1536// Signed so that <section_glob>=-1 is allowed.1537int64_t v;1538if (!to_integer(kv.second, v))1539error(errPrefix + "expected an integer, but got '" + kv.second + "'");1540else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))1541config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v));1542else1543error(errPrefix + toString(pat.takeError()) + ": " + kv.first);1544}15451546auto reports = {std::make_pair("bti-report", &config->zBtiReport),1547std::make_pair("cet-report", &config->zCetReport),1548std::make_pair("gcs-report", &config->zGcsReport),1549std::make_pair("pauth-report", &config->zPauthReport)};1550for (opt::Arg *arg : args.filtered(OPT_z)) {1551std::pair<StringRef, StringRef> option =1552StringRef(arg->getValue()).split('=');1553for (auto reportArg : reports) {1554if (option.first != reportArg.first)1555continue;1556arg->claim();1557if (!isValidReportString(option.second)) {1558error(Twine("-z ") + reportArg.first + "= parameter " + option.second +1559" is not recognized");1560continue;1561}1562*reportArg.second = option.second;1563}1564}15651566for (opt::Arg *arg : args.filtered(OPT_compress_sections)) {1567SmallVector<StringRef, 0> fields;1568StringRef(arg->getValue()).split(fields, '=');1569if (fields.size() != 2 || fields[1].empty()) {1570error(arg->getSpelling() +1571": parse error, not 'section-glob=[none|zlib|zstd]'");1572continue;1573}1574auto [typeStr, levelStr] = fields[1].split(':');1575auto type = getCompressionType(typeStr, arg->getSpelling());1576unsigned level = 0;1577if (fields[1].size() != typeStr.size() &&1578!llvm::to_integer(levelStr, level)) {1579error(arg->getSpelling() +1580": expected a non-negative integer compression level, but got '" +1581levelStr + "'");1582}1583if (Expected<GlobPattern> pat = GlobPattern::create(fields[0])) {1584config->compressSections.emplace_back(std::move(*pat), type, level);1585} else {1586error(arg->getSpelling() + ": " + toString(pat.takeError()));1587continue;1588}1589}15901591for (opt::Arg *arg : args.filtered(OPT_z)) {1592std::pair<StringRef, StringRef> option =1593StringRef(arg->getValue()).split('=');1594if (option.first != "dead-reloc-in-nonalloc")1595continue;1596arg->claim();1597constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";1598std::pair<StringRef, StringRef> kv = option.second.split('=');1599if (kv.first.empty() || kv.second.empty()) {1600error(errPrefix + "expected <section_glob>=<value>");1601continue;1602}1603uint64_t v;1604if (!to_integer(kv.second, v))1605error(errPrefix + "expected a non-negative integer, but got '" +1606kv.second + "'");1607else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))1608config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);1609else1610error(errPrefix + toString(pat.takeError()) + ": " + kv.first);1611}16121613cl::ResetAllOptionOccurrences();16141615// Parse LTO options.1616if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))1617parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),1618arg->getSpelling());16191620for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))1621parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());16221623// GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or1624// relative path. Just ignore. If not ended with "lto-wrapper" (or1625// "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an1626// unsupported LLVMgold.so option and error.1627for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) {1628StringRef v(arg->getValue());1629if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe"))1630error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +1631"'");1632}16331634config->passPlugins = args::getStrings(args, OPT_load_pass_plugins);16351636// Parse -mllvm options.1637for (const auto *arg : args.filtered(OPT_mllvm)) {1638parseClangOption(arg->getValue(), arg->getSpelling());1639config->mllvmOpts.emplace_back(arg->getValue());1640}16411642config->ltoKind = LtoKind::Default;1643if (auto *arg = args.getLastArg(OPT_lto)) {1644StringRef s = arg->getValue();1645if (s == "thin")1646config->ltoKind = LtoKind::UnifiedThin;1647else if (s == "full")1648config->ltoKind = LtoKind::UnifiedRegular;1649else if (s == "default")1650config->ltoKind = LtoKind::Default;1651else1652error("unknown LTO mode: " + s);1653}16541655// --threads= takes a positive integer and provides the default value for1656// --thinlto-jobs=. If unspecified, cap the number of threads since1657// overhead outweighs optimization for used parallel algorithms for the1658// non-LTO parts.1659if (auto *arg = args.getLastArg(OPT_threads)) {1660StringRef v(arg->getValue());1661unsigned threads = 0;1662if (!llvm::to_integer(v, threads, 0) || threads == 0)1663error(arg->getSpelling() + ": expected a positive integer, but got '" +1664arg->getValue() + "'");1665parallel::strategy = hardware_concurrency(threads);1666config->thinLTOJobs = v;1667} else if (parallel::strategy.compute_thread_count() > 16) {1668log("set maximum concurrency to 16, specify --threads= to change");1669parallel::strategy = hardware_concurrency(16);1670}1671if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))1672config->thinLTOJobs = arg->getValue();1673config->threadCount = parallel::strategy.compute_thread_count();16741675if (config->ltoPartitions == 0)1676error("--lto-partitions: number of threads must be > 0");1677if (!get_threadpool_strategy(config->thinLTOJobs))1678error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);16791680if (config->splitStackAdjustSize < 0)1681error("--split-stack-adjust-size: size must be >= 0");16821683// The text segment is traditionally the first segment, whose address equals1684// the base address. However, lld places the R PT_LOAD first. -Ttext-segment1685// is an old-fashioned option that does not play well with lld's layout.1686// Suggest --image-base as a likely alternative.1687if (args.hasArg(OPT_Ttext_segment))1688error("-Ttext-segment is not supported. Use --image-base if you "1689"intend to set the base address");16901691// Parse ELF{32,64}{LE,BE} and CPU type.1692if (auto *arg = args.getLastArg(OPT_m)) {1693StringRef s = arg->getValue();1694std::tie(config->ekind, config->emachine, config->osabi) =1695parseEmulation(s);1696config->mipsN32Abi =1697(s.starts_with("elf32btsmipn32") || s.starts_with("elf32ltsmipn32"));1698config->emulation = s;1699}17001701// Parse --hash-style={sysv,gnu,both}.1702if (auto *arg = args.getLastArg(OPT_hash_style)) {1703StringRef s = arg->getValue();1704if (s == "sysv")1705config->sysvHash = true;1706else if (s == "gnu")1707config->gnuHash = true;1708else if (s == "both")1709config->sysvHash = config->gnuHash = true;1710else1711error("unknown --hash-style: " + s);1712}17131714if (args.hasArg(OPT_print_map))1715config->mapFile = "-";17161717// Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).1718// As PT_GNU_RELRO relies on Paging, do not create it when we have disabled1719// it. Also disable RELRO for -r.1720if (config->nmagic || config->omagic || config->relocatable)1721config->zRelro = false;17221723std::tie(config->buildId, config->buildIdVector) = getBuildId(args);17241725if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) {1726config->relrGlibc = true;1727config->relrPackDynRelocs = true;1728} else {1729std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =1730getPackDynRelocs(args);1731}17321733if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){1734if (args.hasArg(OPT_call_graph_ordering_file))1735error("--symbol-ordering-file and --call-graph-order-file "1736"may not be used together");1737if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) {1738config->symbolOrderingFile = getSymbolOrderingFile(*buffer);1739// Also need to disable CallGraphProfileSort to prevent1740// LLD order symbols with CGProfile1741config->callGraphProfileSort = CGProfileSortKind::None;1742}1743}17441745assert(config->versionDefinitions.empty());1746config->versionDefinitions.push_back(1747{"local", (uint16_t)VER_NDX_LOCAL, {}, {}});1748config->versionDefinitions.push_back(1749{"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});17501751// If --retain-symbol-file is used, we'll keep only the symbols listed in1752// the file and discard all others.1753if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {1754config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(1755{"*", /*isExternCpp=*/false, /*hasWildcard=*/true});1756if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))1757for (StringRef s : args::getLines(*buffer))1758config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(1759{s, /*isExternCpp=*/false, /*hasWildcard=*/false});1760}17611762for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {1763StringRef pattern(arg->getValue());1764if (Expected<GlobPattern> pat = GlobPattern::create(pattern))1765config->warnBackrefsExclude.push_back(std::move(*pat));1766else1767error(arg->getSpelling() + ": " + toString(pat.takeError()) + ": " +1768pattern);1769}17701771// For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols1772// which should be exported. For -shared, references to matched non-local1773// STV_DEFAULT symbols are not bound to definitions within the shared object,1774// even if other options express a symbolic intention: -Bsymbolic,1775// -Bsymbolic-functions (if STT_FUNC), --dynamic-list.1776for (auto *arg : args.filtered(OPT_export_dynamic_symbol))1777config->dynamicList.push_back(1778{arg->getValue(), /*isExternCpp=*/false,1779/*hasWildcard=*/hasWildcard(arg->getValue())});17801781// --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol1782// patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic1783// like semantics.1784config->symbolic =1785config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);1786for (auto *arg :1787args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))1788if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))1789readDynamicList(*buffer);17901791for (auto *arg : args.filtered(OPT_version_script))1792if (std::optional<std::string> path = searchScript(arg->getValue())) {1793if (std::optional<MemoryBufferRef> buffer = readFile(*path))1794readVersionScript(*buffer);1795} else {1796error(Twine("cannot find version script ") + arg->getValue());1797}1798}17991800// Some Config members do not directly correspond to any particular1801// command line options, but computed based on other Config values.1802// This function initialize such members. See Config.h for the details1803// of these values.1804static void setConfigs(opt::InputArgList &args) {1805ELFKind k = config->ekind;1806uint16_t m = config->emachine;18071808config->copyRelocs = (config->relocatable || config->emitRelocs);1809config->is64 = (k == ELF64LEKind || k == ELF64BEKind);1810config->isLE = (k == ELF32LEKind || k == ELF64LEKind);1811config->endianness = config->isLE ? endianness::little : endianness::big;1812config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);1813config->isPic = config->pie || config->shared;1814config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);1815config->wordsize = config->is64 ? 8 : 4;18161817// ELF defines two different ways to store relocation addends as shown below:1818//1819// Rel: Addends are stored to the location where relocations are applied. It1820// cannot pack the full range of addend values for all relocation types, but1821// this only affects relocation types that we don't support emitting as1822// dynamic relocations (see getDynRel).1823// Rela: Addends are stored as part of relocation entry.1824//1825// In other words, Rela makes it easy to read addends at the price of extra1826// 4 or 8 byte for each relocation entry.1827//1828// We pick the format for dynamic relocations according to the psABI for each1829// processor, but a contrary choice can be made if the dynamic loader1830// supports.1831config->isRela = getIsRela(args);18321833// If the output uses REL relocations we must store the dynamic relocation1834// addends to the output sections. We also store addends for RELA relocations1835// if --apply-dynamic-relocs is used.1836// We default to not writing the addends when using RELA relocations since1837// any standard conforming tool can find it in r_addend.1838config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,1839OPT_no_apply_dynamic_relocs, false) ||1840!config->isRela;1841// Validation of dynamic relocation addends is on by default for assertions1842// builds and disabled otherwise. This check is enabled when writeAddends is1843// true.1844#ifndef NDEBUG1845bool checkDynamicRelocsDefault = true;1846#else1847bool checkDynamicRelocsDefault = false;1848#endif1849config->checkDynamicRelocs =1850args.hasFlag(OPT_check_dynamic_relocations,1851OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);1852config->tocOptimize =1853args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);1854config->pcRelOptimize =1855args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);18561857if (!args.hasArg(OPT_hash_style)) {1858if (config->emachine == EM_MIPS)1859config->sysvHash = true;1860else1861config->sysvHash = config->gnuHash = true;1862}18631864// Set default entry point and output file if not specified by command line or1865// linker scripts.1866config->warnMissingEntry =1867(!config->entry.empty() || (!config->shared && !config->relocatable));1868if (config->entry.empty() && !config->relocatable)1869config->entry = config->emachine == EM_MIPS ? "__start" : "_start";1870if (config->outputFile.empty())1871config->outputFile = "a.out";18721873// Fail early if the output file or map file is not writable. If a user has a1874// long link, e.g. due to a large LTO link, they do not wish to run it and1875// find that it failed because there was a mistake in their command-line.1876{1877llvm::TimeTraceScope timeScope("Create output files");1878if (auto e = tryCreateFile(config->outputFile))1879error("cannot open output file " + config->outputFile + ": " +1880e.message());1881if (auto e = tryCreateFile(config->mapFile))1882error("cannot open map file " + config->mapFile + ": " + e.message());1883if (auto e = tryCreateFile(config->whyExtract))1884error("cannot open --why-extract= file " + config->whyExtract + ": " +1885e.message());1886}1887}18881889static bool isFormatBinary(StringRef s) {1890if (s == "binary")1891return true;1892if (s == "elf" || s == "default")1893return false;1894error("unknown --format value: " + s +1895" (supported formats: elf, default, binary)");1896return false;1897}18981899void LinkerDriver::createFiles(opt::InputArgList &args) {1900llvm::TimeTraceScope timeScope("Load input files");1901// For --{push,pop}-state.1902std::vector<std::tuple<bool, bool, bool>> stack;19031904// -r implies -Bstatic and has precedence over -Bdynamic.1905config->isStatic = config->relocatable;19061907// Iterate over argv to process input files and positional arguments.1908std::optional<MemoryBufferRef> defaultScript;1909InputFile::isInGroup = false;1910bool hasInput = false, hasScript = false;1911for (auto *arg : args) {1912switch (arg->getOption().getID()) {1913case OPT_library:1914addLibrary(arg->getValue());1915hasInput = true;1916break;1917case OPT_INPUT:1918addFile(arg->getValue(), /*withLOption=*/false);1919hasInput = true;1920break;1921case OPT_defsym: {1922StringRef from;1923StringRef to;1924std::tie(from, to) = StringRef(arg->getValue()).split('=');1925if (from.empty() || to.empty())1926error("--defsym: syntax error: " + StringRef(arg->getValue()));1927else1928readDefsym(from, MemoryBufferRef(to, "--defsym"));1929break;1930}1931case OPT_script:1932case OPT_default_script:1933if (std::optional<std::string> path = searchScript(arg->getValue())) {1934if (std::optional<MemoryBufferRef> mb = readFile(*path)) {1935if (arg->getOption().matches(OPT_default_script)) {1936defaultScript = mb;1937} else {1938readLinkerScript(*mb);1939hasScript = true;1940}1941}1942break;1943}1944error(Twine("cannot find linker script ") + arg->getValue());1945break;1946case OPT_as_needed:1947config->asNeeded = true;1948break;1949case OPT_format:1950config->formatBinary = isFormatBinary(arg->getValue());1951break;1952case OPT_no_as_needed:1953config->asNeeded = false;1954break;1955case OPT_Bstatic:1956case OPT_omagic:1957case OPT_nmagic:1958config->isStatic = true;1959break;1960case OPT_Bdynamic:1961if (!config->relocatable)1962config->isStatic = false;1963break;1964case OPT_whole_archive:1965inWholeArchive = true;1966break;1967case OPT_no_whole_archive:1968inWholeArchive = false;1969break;1970case OPT_just_symbols:1971if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) {1972files.push_back(createObjFile(*mb));1973files.back()->justSymbols = true;1974}1975break;1976case OPT_in_implib:1977if (armCmseImpLib)1978error("multiple CMSE import libraries not supported");1979else if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue()))1980armCmseImpLib = createObjFile(*mb);1981break;1982case OPT_start_group:1983if (InputFile::isInGroup)1984error("nested --start-group");1985InputFile::isInGroup = true;1986break;1987case OPT_end_group:1988if (!InputFile::isInGroup)1989error("stray --end-group");1990InputFile::isInGroup = false;1991++InputFile::nextGroupId;1992break;1993case OPT_start_lib:1994if (inLib)1995error("nested --start-lib");1996if (InputFile::isInGroup)1997error("may not nest --start-lib in --start-group");1998inLib = true;1999InputFile::isInGroup = true;2000break;2001case OPT_end_lib:2002if (!inLib)2003error("stray --end-lib");2004inLib = false;2005InputFile::isInGroup = false;2006++InputFile::nextGroupId;2007break;2008case OPT_push_state:2009stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);2010break;2011case OPT_pop_state:2012if (stack.empty()) {2013error("unbalanced --push-state/--pop-state");2014break;2015}2016std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();2017stack.pop_back();2018break;2019}2020}20212022if (defaultScript && !hasScript)2023readLinkerScript(*defaultScript);2024if (files.empty() && !hasInput && errorCount() == 0)2025error("no input files");2026}20272028// If -m <machine_type> was not given, infer it from object files.2029void LinkerDriver::inferMachineType() {2030if (config->ekind != ELFNoneKind)2031return;20322033bool inferred = false;2034for (InputFile *f : files) {2035if (f->ekind == ELFNoneKind)2036continue;2037if (!inferred) {2038inferred = true;2039config->ekind = f->ekind;2040config->emachine = f->emachine;2041config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);2042}2043config->osabi = f->osabi;2044if (f->osabi != ELFOSABI_NONE)2045return;2046}2047if (!inferred)2048error("target emulation unknown: -m or at least one .o file required");2049}20502051// Parse -z max-page-size=<value>. The default value is defined by2052// each target.2053static uint64_t getMaxPageSize(opt::InputArgList &args) {2054uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",2055target->defaultMaxPageSize);2056if (!isPowerOf2_64(val)) {2057error("max-page-size: value isn't a power of 2");2058return target->defaultMaxPageSize;2059}2060if (config->nmagic || config->omagic) {2061if (val != target->defaultMaxPageSize)2062warn("-z max-page-size set, but paging disabled by omagic or nmagic");2063return 1;2064}2065return val;2066}20672068// Parse -z common-page-size=<value>. The default value is defined by2069// each target.2070static uint64_t getCommonPageSize(opt::InputArgList &args) {2071uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",2072target->defaultCommonPageSize);2073if (!isPowerOf2_64(val)) {2074error("common-page-size: value isn't a power of 2");2075return target->defaultCommonPageSize;2076}2077if (config->nmagic || config->omagic) {2078if (val != target->defaultCommonPageSize)2079warn("-z common-page-size set, but paging disabled by omagic or nmagic");2080return 1;2081}2082// commonPageSize can't be larger than maxPageSize.2083if (val > config->maxPageSize)2084val = config->maxPageSize;2085return val;2086}20872088// Parses --image-base option.2089static std::optional<uint64_t> getImageBase(opt::InputArgList &args) {2090// Because we are using "Config->maxPageSize" here, this function has to be2091// called after the variable is initialized.2092auto *arg = args.getLastArg(OPT_image_base);2093if (!arg)2094return std::nullopt;20952096StringRef s = arg->getValue();2097uint64_t v;2098if (!to_integer(s, v)) {2099error("--image-base: number expected, but got " + s);2100return 0;2101}2102if ((v % config->maxPageSize) != 0)2103warn("--image-base: address isn't multiple of page size: " + s);2104return v;2105}21062107// Parses `--exclude-libs=lib,lib,...`.2108// The library names may be delimited by commas or colons.2109static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {2110DenseSet<StringRef> ret;2111for (auto *arg : args.filtered(OPT_exclude_libs)) {2112StringRef s = arg->getValue();2113for (;;) {2114size_t pos = s.find_first_of(",:");2115if (pos == StringRef::npos)2116break;2117ret.insert(s.substr(0, pos));2118s = s.substr(pos + 1);2119}2120ret.insert(s);2121}2122return ret;2123}21242125// Handles the --exclude-libs option. If a static library file is specified2126// by the --exclude-libs option, all public symbols from the archive become2127// private unless otherwise specified by version scripts or something.2128// A special library name "ALL" means all archive files.2129//2130// This is not a popular option, but some programs such as bionic libc use it.2131static void excludeLibs(opt::InputArgList &args) {2132DenseSet<StringRef> libs = getExcludeLibs(args);2133bool all = libs.count("ALL");21342135auto visit = [&](InputFile *file) {2136if (file->archiveName.empty() ||2137!(all || libs.count(path::filename(file->archiveName))))2138return;2139ArrayRef<Symbol *> symbols = file->getSymbols();2140if (isa<ELFFileBase>(file))2141symbols = cast<ELFFileBase>(file)->getGlobalSymbols();2142for (Symbol *sym : symbols)2143if (!sym->isUndefined() && sym->file == file)2144sym->versionId = VER_NDX_LOCAL;2145};21462147for (ELFFileBase *file : ctx.objectFiles)2148visit(file);21492150for (BitcodeFile *file : ctx.bitcodeFiles)2151visit(file);2152}21532154// Force Sym to be entered in the output.2155static void handleUndefined(Symbol *sym, const char *option) {2156// Since a symbol may not be used inside the program, LTO may2157// eliminate it. Mark the symbol as "used" to prevent it.2158sym->isUsedInRegularObj = true;21592160if (!sym->isLazy())2161return;2162sym->extract();2163if (!config->whyExtract.empty())2164ctx.whyExtractRecords.emplace_back(option, sym->file, *sym);2165}21662167// As an extension to GNU linkers, lld supports a variant of `-u`2168// which accepts wildcard patterns. All symbols that match a given2169// pattern are handled as if they were given by `-u`.2170static void handleUndefinedGlob(StringRef arg) {2171Expected<GlobPattern> pat = GlobPattern::create(arg);2172if (!pat) {2173error("--undefined-glob: " + toString(pat.takeError()) + ": " + arg);2174return;2175}21762177// Calling sym->extract() in the loop is not safe because it may add new2178// symbols to the symbol table, invalidating the current iterator.2179SmallVector<Symbol *, 0> syms;2180for (Symbol *sym : symtab.getSymbols())2181if (!sym->isPlaceholder() && pat->match(sym->getName()))2182syms.push_back(sym);21832184for (Symbol *sym : syms)2185handleUndefined(sym, "--undefined-glob");2186}21872188static void handleLibcall(StringRef name) {2189Symbol *sym = symtab.find(name);2190if (sym && sym->isLazy() && isa<BitcodeFile>(sym->file)) {2191if (!config->whyExtract.empty())2192ctx.whyExtractRecords.emplace_back("<libcall>", sym->file, *sym);2193sym->extract();2194}2195}21962197static void writeArchiveStats() {2198if (config->printArchiveStats.empty())2199return;22002201std::error_code ec;2202raw_fd_ostream os = ctx.openAuxiliaryFile(config->printArchiveStats, ec);2203if (ec) {2204error("--print-archive-stats=: cannot open " + config->printArchiveStats +2205": " + ec.message());2206return;2207}22082209os << "members\textracted\tarchive\n";22102211SmallVector<StringRef, 0> archives;2212DenseMap<CachedHashStringRef, unsigned> all, extracted;2213for (ELFFileBase *file : ctx.objectFiles)2214if (file->archiveName.size())2215++extracted[CachedHashStringRef(file->archiveName)];2216for (BitcodeFile *file : ctx.bitcodeFiles)2217if (file->archiveName.size())2218++extracted[CachedHashStringRef(file->archiveName)];2219for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) {2220unsigned &v = extracted[CachedHashString(f.first)];2221os << f.second << '\t' << v << '\t' << f.first << '\n';2222// If the archive occurs multiple times, other instances have a count of 0.2223v = 0;2224}2225}22262227static void writeWhyExtract() {2228if (config->whyExtract.empty())2229return;22302231std::error_code ec;2232raw_fd_ostream os = ctx.openAuxiliaryFile(config->whyExtract, ec);2233if (ec) {2234error("cannot open --why-extract= file " + config->whyExtract + ": " +2235ec.message());2236return;2237}22382239os << "reference\textracted\tsymbol\n";2240for (auto &entry : ctx.whyExtractRecords) {2241os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t'2242<< toString(std::get<2>(entry)) << '\n';2243}2244}22452246static void reportBackrefs() {2247for (auto &ref : ctx.backwardReferences) {2248const Symbol &sym = *ref.first;2249std::string to = toString(ref.second.second);2250// Some libraries have known problems and can cause noise. Filter them out2251// with --warn-backrefs-exclude=. The value may look like (for --start-lib)2252// *.o or (archive member) *.a(*.o).2253bool exclude = false;2254for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)2255if (pat.match(to)) {2256exclude = true;2257break;2258}2259if (!exclude)2260warn("backward reference detected: " + sym.getName() + " in " +2261toString(ref.second.first) + " refers to " + to);2262}2263}22642265// Handle --dependency-file=<path>. If that option is given, lld creates a2266// file at a given path with the following contents:2267//2268// <output-file>: <input-file> ...2269//2270// <input-file>:2271//2272// where <output-file> is a pathname of an output file and <input-file>2273// ... is a list of pathnames of all input files. `make` command can read a2274// file in the above format and interpret it as a dependency info. We write2275// phony targets for every <input-file> to avoid an error when that file is2276// removed.2277//2278// This option is useful if you want to make your final executable to depend2279// on all input files including system libraries. Here is why.2280//2281// When you write a Makefile, you usually write it so that the final2282// executable depends on all user-generated object files. Normally, you2283// don't make your executable to depend on system libraries (such as libc)2284// because you don't know the exact paths of libraries, even though system2285// libraries that are linked to your executable statically are technically a2286// part of your program. By using --dependency-file option, you can make2287// lld to dump dependency info so that you can maintain exact dependencies2288// easily.2289static void writeDependencyFile() {2290std::error_code ec;2291raw_fd_ostream os = ctx.openAuxiliaryFile(config->dependencyFile, ec);2292if (ec) {2293error("cannot open " + config->dependencyFile + ": " + ec.message());2294return;2295}22962297// We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:2298// * A space is escaped by a backslash which itself must be escaped.2299// * A hash sign is escaped by a single backslash.2300// * $ is escapes as $$.2301auto printFilename = [](raw_fd_ostream &os, StringRef filename) {2302llvm::SmallString<256> nativePath;2303llvm::sys::path::native(filename.str(), nativePath);2304llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);2305for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {2306if (nativePath[i] == '#') {2307os << '\\';2308} else if (nativePath[i] == ' ') {2309os << '\\';2310unsigned j = i;2311while (j > 0 && nativePath[--j] == '\\')2312os << '\\';2313} else if (nativePath[i] == '$') {2314os << '$';2315}2316os << nativePath[i];2317}2318};23192320os << config->outputFile << ":";2321for (StringRef path : config->dependencyFiles) {2322os << " \\\n ";2323printFilename(os, path);2324}2325os << "\n";23262327for (StringRef path : config->dependencyFiles) {2328os << "\n";2329printFilename(os, path);2330os << ":\n";2331}2332}23332334// Replaces common symbols with defined symbols reside in .bss sections.2335// This function is called after all symbol names are resolved. As a2336// result, the passes after the symbol resolution won't see any2337// symbols of type CommonSymbol.2338static void replaceCommonSymbols() {2339llvm::TimeTraceScope timeScope("Replace common symbols");2340for (ELFFileBase *file : ctx.objectFiles) {2341if (!file->hasCommonSyms)2342continue;2343for (Symbol *sym : file->getGlobalSymbols()) {2344auto *s = dyn_cast<CommonSymbol>(sym);2345if (!s)2346continue;23472348auto *bss = make<BssSection>("COMMON", s->size, s->alignment);2349bss->file = s->file;2350ctx.inputSections.push_back(bss);2351Defined(s->file, StringRef(), s->binding, s->stOther, s->type,2352/*value=*/0, s->size, bss)2353.overwrite(*s);2354}2355}2356}23572358// The section referred to by `s` is considered address-significant. Set the2359// keepUnique flag on the section if appropriate.2360static void markAddrsig(Symbol *s) {2361if (auto *d = dyn_cast_or_null<Defined>(s))2362if (d->section)2363// We don't need to keep text sections unique under --icf=all even if they2364// are address-significant.2365if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))2366d->section->keepUnique = true;2367}23682369// Record sections that define symbols mentioned in --keep-unique <symbol>2370// and symbols referred to by address-significance tables. These sections are2371// ineligible for ICF.2372template <class ELFT>2373static void findKeepUniqueSections(opt::InputArgList &args) {2374for (auto *arg : args.filtered(OPT_keep_unique)) {2375StringRef name = arg->getValue();2376auto *d = dyn_cast_or_null<Defined>(symtab.find(name));2377if (!d || !d->section) {2378warn("could not find symbol " + name + " to keep unique");2379continue;2380}2381d->section->keepUnique = true;2382}23832384// --icf=all --ignore-data-address-equality means that we can ignore2385// the dynsym and address-significance tables entirely.2386if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)2387return;23882389// Symbols in the dynsym could be address-significant in other executables2390// or DSOs, so we conservatively mark them as address-significant.2391for (Symbol *sym : symtab.getSymbols())2392if (sym->includeInDynsym())2393markAddrsig(sym);23942395// Visit the address-significance table in each object file and mark each2396// referenced symbol as address-significant.2397for (InputFile *f : ctx.objectFiles) {2398auto *obj = cast<ObjFile<ELFT>>(f);2399ArrayRef<Symbol *> syms = obj->getSymbols();2400if (obj->addrsigSec) {2401ArrayRef<uint8_t> contents =2402check(obj->getObj().getSectionContents(*obj->addrsigSec));2403const uint8_t *cur = contents.begin();2404while (cur != contents.end()) {2405unsigned size;2406const char *err = nullptr;2407uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);2408if (err)2409fatal(toString(f) + ": could not decode addrsig section: " + err);2410markAddrsig(syms[symIndex]);2411cur += size;2412}2413} else {2414// If an object file does not have an address-significance table,2415// conservatively mark all of its symbols as address-significant.2416for (Symbol *s : syms)2417markAddrsig(s);2418}2419}2420}24212422// This function reads a symbol partition specification section. These sections2423// are used to control which partition a symbol is allocated to. See2424// https://lld.llvm.org/Partitions.html for more details on partitions.2425template <typename ELFT>2426static void readSymbolPartitionSection(InputSectionBase *s) {2427// Read the relocation that refers to the partition's entry point symbol.2428Symbol *sym;2429const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();2430if (rels.areRelocsRel())2431sym = &s->file->getRelocTargetSym(rels.rels[0]);2432else2433sym = &s->file->getRelocTargetSym(rels.relas[0]);2434if (!isa<Defined>(sym) || !sym->includeInDynsym())2435return;24362437StringRef partName = reinterpret_cast<const char *>(s->content().data());2438for (Partition &part : partitions) {2439if (part.name == partName) {2440sym->partition = part.getNumber();2441return;2442}2443}24442445// Forbid partitions from being used on incompatible targets, and forbid them2446// from being used together with various linker features that assume a single2447// set of output sections.2448if (script->hasSectionsCommand)2449error(toString(s->file) +2450": partitions cannot be used with the SECTIONS command");2451if (script->hasPhdrsCommands())2452error(toString(s->file) +2453": partitions cannot be used with the PHDRS command");2454if (!config->sectionStartMap.empty())2455error(toString(s->file) + ": partitions cannot be used with "2456"--section-start, -Ttext, -Tdata or -Tbss");2457if (config->emachine == EM_MIPS)2458error(toString(s->file) + ": partitions cannot be used on this target");24592460// Impose a limit of no more than 254 partitions. This limit comes from the2461// sizes of the Partition fields in InputSectionBase and Symbol, as well as2462// the amount of space devoted to the partition number in RankFlags.2463if (partitions.size() == 254)2464fatal("may not have more than 254 partitions");24652466partitions.emplace_back();2467Partition &newPart = partitions.back();2468newPart.name = partName;2469sym->partition = newPart.getNumber();2470}24712472static void markBuffersAsDontNeed(bool skipLinkedOutput) {2473// With --thinlto-index-only, all buffers are nearly unused from now on2474// (except symbol/section names used by infrequent passes). Mark input file2475// buffers as MADV_DONTNEED so that these pages can be reused by the expensive2476// thin link, saving memory.2477if (skipLinkedOutput) {2478for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))2479mb.dontNeedIfMmap();2480return;2481}24822483// Otherwise, just mark MemoryBuffers backing BitcodeFiles.2484DenseSet<const char *> bufs;2485for (BitcodeFile *file : ctx.bitcodeFiles)2486bufs.insert(file->mb.getBufferStart());2487for (BitcodeFile *file : ctx.lazyBitcodeFiles)2488bufs.insert(file->mb.getBufferStart());2489for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))2490if (bufs.count(mb.getBufferStart()))2491mb.dontNeedIfMmap();2492}24932494// This function is where all the optimizations of link-time2495// optimization takes place. When LTO is in use, some input files are2496// not in native object file format but in the LLVM bitcode format.2497// This function compiles bitcode files into a few big native files2498// using LLVM functions and replaces bitcode symbols with the results.2499// Because all bitcode files that the program consists of are passed to2500// the compiler at once, it can do a whole-program optimization.2501template <class ELFT>2502void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) {2503llvm::TimeTraceScope timeScope("LTO");2504// Compile bitcode files and replace bitcode symbols.2505lto.reset(new BitcodeCompiler);2506for (BitcodeFile *file : ctx.bitcodeFiles)2507lto->add(*file);25082509if (!ctx.bitcodeFiles.empty())2510markBuffersAsDontNeed(skipLinkedOutput);25112512for (InputFile *file : lto->compile()) {2513auto *obj = cast<ObjFile<ELFT>>(file);2514obj->parse(/*ignoreComdats=*/true);25152516// Parse '@' in symbol names for non-relocatable output.2517if (!config->relocatable)2518for (Symbol *sym : obj->getGlobalSymbols())2519if (sym->hasVersionSuffix)2520sym->parseSymbolVersion();2521ctx.objectFiles.push_back(obj);2522}2523}25242525// The --wrap option is a feature to rename symbols so that you can write2526// wrappers for existing functions. If you pass `--wrap=foo`, all2527// occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are2528// expected to write `__wrap_foo` function as a wrapper). The original2529// symbol becomes accessible as `__real_foo`, so you can call that from your2530// wrapper.2531//2532// This data structure is instantiated for each --wrap option.2533struct WrappedSymbol {2534Symbol *sym;2535Symbol *real;2536Symbol *wrap;2537};25382539// Handles --wrap option.2540//2541// This function instantiates wrapper symbols. At this point, they seem2542// like they are not being used at all, so we explicitly set some flags so2543// that LTO won't eliminate them.2544static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {2545std::vector<WrappedSymbol> v;2546DenseSet<StringRef> seen;25472548for (auto *arg : args.filtered(OPT_wrap)) {2549StringRef name = arg->getValue();2550if (!seen.insert(name).second)2551continue;25522553Symbol *sym = symtab.find(name);2554if (!sym)2555continue;25562557Symbol *wrap =2558symtab.addUnusedUndefined(saver().save("__wrap_" + name), sym->binding);25592560// If __real_ is referenced, pull in the symbol if it is lazy. Do this after2561// processing __wrap_ as that may have referenced __real_.2562StringRef realName = saver().save("__real_" + name);2563if (Symbol *real = symtab.find(realName)) {2564symtab.addUnusedUndefined(name, sym->binding);2565// Update sym's binding, which will replace real's later in2566// SymbolTable::wrap.2567sym->binding = real->binding;2568}25692570Symbol *real = symtab.addUnusedUndefined(realName);2571v.push_back({sym, real, wrap});25722573// We want to tell LTO not to inline symbols to be overwritten2574// because LTO doesn't know the final symbol contents after renaming.2575real->scriptDefined = true;2576sym->scriptDefined = true;25772578// If a symbol is referenced in any object file, bitcode file or shared2579// object, mark its redirection target (foo for __real_foo and __wrap_foo2580// for foo) as referenced after redirection, which will be used to tell LTO2581// to not eliminate the redirection target. If the object file defining the2582// symbol also references it, we cannot easily distinguish the case from2583// cases where the symbol is not referenced. Retain the redirection target2584// in this case because we choose to wrap symbol references regardless of2585// whether the symbol is defined2586// (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).2587if (real->referenced || real->isDefined())2588sym->referencedAfterWrap = true;2589if (sym->referenced || sym->isDefined())2590wrap->referencedAfterWrap = true;2591}2592return v;2593}25942595static void combineVersionedSymbol(Symbol &sym,2596DenseMap<Symbol *, Symbol *> &map) {2597const char *suffix1 = sym.getVersionSuffix();2598if (suffix1[0] != '@' || suffix1[1] == '@')2599return;26002601// Check the existing symbol foo. We have two special cases to handle:2602//2603// * There is a definition of foo@v1 and foo@@v1.2604// * There is a definition of foo@v1 and foo.2605Defined *sym2 = dyn_cast_or_null<Defined>(symtab.find(sym.getName()));2606if (!sym2)2607return;2608const char *suffix2 = sym2->getVersionSuffix();2609if (suffix2[0] == '@' && suffix2[1] == '@' &&2610strcmp(suffix1 + 1, suffix2 + 2) == 0) {2611// foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.2612map.try_emplace(&sym, sym2);2613// If both foo@v1 and foo@@v1 are defined and non-weak, report a2614// duplicate definition error.2615if (sym.isDefined()) {2616sym2->checkDuplicate(cast<Defined>(sym));2617sym2->resolve(cast<Defined>(sym));2618} else if (sym.isUndefined()) {2619sym2->resolve(cast<Undefined>(sym));2620} else {2621sym2->resolve(cast<SharedSymbol>(sym));2622}2623// Eliminate foo@v1 from the symbol table.2624sym.symbolKind = Symbol::PlaceholderKind;2625sym.isUsedInRegularObj = false;2626} else if (auto *sym1 = dyn_cast<Defined>(&sym)) {2627if (sym2->versionId > VER_NDX_GLOBAL2628? config->versionDefinitions[sym2->versionId].name == suffix1 + 12629: sym1->section == sym2->section && sym1->value == sym2->value) {2630// Due to an assembler design flaw, if foo is defined, .symver foo,2631// foo@v1 defines both foo and foo@v1. Unless foo is bound to a2632// different version, GNU ld makes foo@v1 canonical and eliminates2633// foo. Emulate its behavior, otherwise we would have foo or foo@@v12634// beside foo@v1. foo@v1 and foo combining does not apply if they are2635// not defined in the same place.2636map.try_emplace(sym2, &sym);2637sym2->symbolKind = Symbol::PlaceholderKind;2638sym2->isUsedInRegularObj = false;2639}2640}2641}26422643// Do renaming for --wrap and foo@v1 by updating pointers to symbols.2644//2645// When this function is executed, only InputFiles and symbol table2646// contain pointers to symbol objects. We visit them to replace pointers,2647// so that wrapped symbols are swapped as instructed by the command line.2648static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) {2649llvm::TimeTraceScope timeScope("Redirect symbols");2650DenseMap<Symbol *, Symbol *> map;2651for (const WrappedSymbol &w : wrapped) {2652map[w.sym] = w.wrap;2653map[w.real] = w.sym;2654}26552656// If there are version definitions (versionDefinitions.size() > 2), enumerate2657// symbols with a non-default version (foo@v1) and check whether it should be2658// combined with foo or foo@@v1.2659if (config->versionDefinitions.size() > 2)2660for (Symbol *sym : symtab.getSymbols())2661if (sym->hasVersionSuffix)2662combineVersionedSymbol(*sym, map);26632664if (map.empty())2665return;26662667// Update pointers in input files.2668parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) {2669for (Symbol *&sym : file->getMutableGlobalSymbols())2670if (Symbol *s = map.lookup(sym))2671sym = s;2672});26732674// Update pointers in the symbol table.2675for (const WrappedSymbol &w : wrapped)2676symtab.wrap(w.sym, w.real, w.wrap);2677}26782679static void reportMissingFeature(StringRef config, const Twine &report) {2680if (config == "error")2681error(report);2682else if (config == "warning")2683warn(report);2684}26852686static void checkAndReportMissingFeature(StringRef config, uint32_t features,2687uint32_t mask, const Twine &report) {2688if (!(features & mask))2689reportMissingFeature(config, report);2690}26912692// To enable CET (x86's hardware-assisted control flow enforcement), each2693// source file must be compiled with -fcf-protection. Object files compiled2694// with the flag contain feature flags indicating that they are compatible2695// with CET. We enable the feature only when all object files are compatible2696// with CET.2697//2698// This is also the case with AARCH64's BTI and PAC which use the similar2699// GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.2700//2701// For AArch64 PAuth-enabled object files, the core info of all of them must2702// match. Missing info for some object files with matching info for remaining2703// ones can be allowed (see -z pauth-report).2704static void readSecurityNotes() {2705if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&2706config->emachine != EM_AARCH64)2707return;27082709config->andFeatures = -1;27102711StringRef referenceFileName;2712if (config->emachine == EM_AARCH64) {2713auto it = llvm::find_if(ctx.objectFiles, [](const ELFFileBase *f) {2714return !f->aarch64PauthAbiCoreInfo.empty();2715});2716if (it != ctx.objectFiles.end()) {2717ctx.aarch64PauthAbiCoreInfo = (*it)->aarch64PauthAbiCoreInfo;2718referenceFileName = (*it)->getName();2719}2720}27212722for (ELFFileBase *f : ctx.objectFiles) {2723uint32_t features = f->andFeatures;27242725checkAndReportMissingFeature(2726config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI,2727toString(f) + ": -z bti-report: file does not have "2728"GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");27292730checkAndReportMissingFeature(2731config->zGcsReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_GCS,2732toString(f) + ": -z gcs-report: file does not have "2733"GNU_PROPERTY_AARCH64_FEATURE_1_GCS property");27342735checkAndReportMissingFeature(2736config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT,2737toString(f) + ": -z cet-report: file does not have "2738"GNU_PROPERTY_X86_FEATURE_1_IBT property");27392740checkAndReportMissingFeature(2741config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK,2742toString(f) + ": -z cet-report: file does not have "2743"GNU_PROPERTY_X86_FEATURE_1_SHSTK property");27442745if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {2746features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;2747if (config->zBtiReport == "none")2748warn(toString(f) + ": -z force-bti: file does not have "2749"GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");2750} else if (config->zForceIbt &&2751!(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {2752if (config->zCetReport == "none")2753warn(toString(f) + ": -z force-ibt: file does not have "2754"GNU_PROPERTY_X86_FEATURE_1_IBT property");2755features |= GNU_PROPERTY_X86_FEATURE_1_IBT;2756}2757if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {2758warn(toString(f) + ": -z pac-plt: file does not have "2759"GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");2760features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;2761}2762config->andFeatures &= features;27632764if (ctx.aarch64PauthAbiCoreInfo.empty())2765continue;27662767if (f->aarch64PauthAbiCoreInfo.empty()) {2768reportMissingFeature(config->zPauthReport,2769toString(f) +2770": -z pauth-report: file does not have AArch64 "2771"PAuth core info while '" +2772referenceFileName + "' has one");2773continue;2774}27752776if (ctx.aarch64PauthAbiCoreInfo != f->aarch64PauthAbiCoreInfo)2777errorOrWarn("incompatible values of AArch64 PAuth core info found\n>>> " +2778referenceFileName + ": 0x" +2779toHex(ctx.aarch64PauthAbiCoreInfo, /*LowerCase=*/true) +2780"\n>>> " + toString(f) + ": 0x" +2781toHex(f->aarch64PauthAbiCoreInfo, /*LowerCase=*/true));2782}27832784// Force enable Shadow Stack.2785if (config->zShstk)2786config->andFeatures |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;27872788// Force enable/disable GCS2789if (config->zGcs == GcsPolicy::Always)2790config->andFeatures |= GNU_PROPERTY_AARCH64_FEATURE_1_GCS;2791else if (config->zGcs == GcsPolicy::Never)2792config->andFeatures &= ~GNU_PROPERTY_AARCH64_FEATURE_1_GCS;2793}27942795static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) {2796switch (file->ekind) {2797case ELF32LEKind:2798cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);2799break;2800case ELF32BEKind:2801cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);2802break;2803case ELF64LEKind:2804cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);2805break;2806case ELF64BEKind:2807cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);2808break;2809default:2810llvm_unreachable("");2811}2812}28132814static void postParseObjectFile(ELFFileBase *file) {2815switch (file->ekind) {2816case ELF32LEKind:2817cast<ObjFile<ELF32LE>>(file)->postParse();2818break;2819case ELF32BEKind:2820cast<ObjFile<ELF32BE>>(file)->postParse();2821break;2822case ELF64LEKind:2823cast<ObjFile<ELF64LE>>(file)->postParse();2824break;2825case ELF64BEKind:2826cast<ObjFile<ELF64BE>>(file)->postParse();2827break;2828default:2829llvm_unreachable("");2830}2831}28322833// Do actual linking. Note that when this function is called,2834// all linker scripts have already been parsed.2835template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {2836llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));28372838// Handle --trace-symbol.2839for (auto *arg : args.filtered(OPT_trace_symbol))2840symtab.insert(arg->getValue())->traced = true;28412842ctx.internalFile = createInternalFile("<internal>");28432844// Handle -u/--undefined before input files. If both a.a and b.so define foo,2845// -u foo a.a b.so will extract a.a.2846for (StringRef name : config->undefined)2847symtab.addUnusedUndefined(name)->referenced = true;28482849parseFiles(files, armCmseImpLib);28502851// Create dynamic sections for dynamic linking and static PIE.2852config->hasDynSymTab = !ctx.sharedFiles.empty() || config->isPic;28532854// If an entry symbol is in a static archive, pull out that file now.2855if (Symbol *sym = symtab.find(config->entry))2856handleUndefined(sym, "--entry");28572858// Handle the `--undefined-glob <pattern>` options.2859for (StringRef pat : args::getStrings(args, OPT_undefined_glob))2860handleUndefinedGlob(pat);28612862// After potential archive member extraction involving ENTRY and2863// -u/--undefined-glob, check whether PROVIDE symbols should be defined (the2864// RHS may refer to definitions in just extracted object files).2865script->addScriptReferencedSymbolsToSymTable();28662867// Prevent LTO from removing any definition referenced by -u.2868for (StringRef name : config->undefined)2869if (Defined *sym = dyn_cast_or_null<Defined>(symtab.find(name)))2870sym->isUsedInRegularObj = true;28712872// Mark -init and -fini symbols so that the LTO doesn't eliminate them.2873if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->init)))2874sym->isUsedInRegularObj = true;2875if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->fini)))2876sym->isUsedInRegularObj = true;28772878// If any of our inputs are bitcode files, the LTO code generator may create2879// references to certain library functions that might not be explicit in the2880// bitcode file's symbol table. If any of those library functions are defined2881// in a bitcode file in an archive member, we need to arrange to use LTO to2882// compile those archive members by adding them to the link beforehand.2883//2884// However, adding all libcall symbols to the link can have undesired2885// consequences. For example, the libgcc implementation of2886// __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry2887// that aborts the program if the Linux kernel does not support 64-bit2888// atomics, which would prevent the program from running even if it does not2889// use 64-bit atomics.2890//2891// Therefore, we only add libcall symbols to the link before LTO if we have2892// to, i.e. if the symbol's definition is in bitcode. Any other required2893// libcall symbols will be added to the link after LTO when we add the LTO2894// object file to the link.2895if (!ctx.bitcodeFiles.empty()) {2896llvm::Triple TT(ctx.bitcodeFiles.front()->obj->getTargetTriple());2897for (auto *s : lto::LTO::getRuntimeLibcallSymbols(TT))2898handleLibcall(s);2899}29002901// Archive members defining __wrap symbols may be extracted.2902std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);29032904// No more lazy bitcode can be extracted at this point. Do post parse work2905// like checking duplicate symbols.2906parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {2907initSectionsAndLocalSyms(file, /*ignoreComdats=*/false);2908});2909parallelForEach(ctx.objectFiles, postParseObjectFile);2910parallelForEach(ctx.bitcodeFiles,2911[](BitcodeFile *file) { file->postParse(); });2912for (auto &it : ctx.nonPrevailingSyms) {2913Symbol &sym = *it.first;2914Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type,2915it.second)2916.overwrite(sym);2917cast<Undefined>(sym).nonPrevailing = true;2918}2919ctx.nonPrevailingSyms.clear();2920for (const DuplicateSymbol &d : ctx.duplicates)2921reportDuplicate(*d.sym, d.file, d.section, d.value);2922ctx.duplicates.clear();29232924// Return if there were name resolution errors.2925if (errorCount())2926return;29272928// We want to declare linker script's symbols early,2929// so that we can version them.2930// They also might be exported if referenced by DSOs.2931script->declareSymbols();29322933// Handle --exclude-libs. This is before scanVersionScript() due to a2934// workaround for Android ndk: for a defined versioned symbol in an archive2935// without a version node in the version script, Android does not expect a2936// 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).2937// GNU ld errors in this case.2938if (args.hasArg(OPT_exclude_libs))2939excludeLibs(args);29402941// Create elfHeader early. We need a dummy section in2942// addReservedSymbols to mark the created symbols as not absolute.2943Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);29442945// We need to create some reserved symbols such as _end. Create them.2946if (!config->relocatable)2947addReservedSymbols();29482949// Apply version scripts.2950//2951// For a relocatable output, version scripts don't make sense, and2952// parsing a symbol version string (e.g. dropping "@ver1" from a symbol2953// name "foo@ver1") rather do harm, so we don't call this if -r is given.2954if (!config->relocatable) {2955llvm::TimeTraceScope timeScope("Process symbol versions");2956symtab.scanVersionScript();2957}29582959// Skip the normal linked output if some LTO options are specified.2960//2961// For --thinlto-index-only, index file creation is performed in2962// compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and2963// --plugin-opt=emit-asm create output files in bitcode or assembly code,2964// respectively. When only certain thinLTO modules are specified for2965// compilation, the intermediate object file are the expected output.2966const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM ||2967config->ltoEmitAsm ||2968!config->thinLTOModulesToCompile.empty();29692970// Handle --lto-validate-all-vtables-have-type-infos.2971if (config->ltoValidateAllVtablesHaveTypeInfos)2972ltoValidateAllVtablesHaveTypeInfos<ELFT>(args);29732974// Do link-time optimization if given files are LLVM bitcode files.2975// This compiles bitcode files into real object files.2976//2977// With this the symbol table should be complete. After this, no new names2978// except a few linker-synthesized ones will be added to the symbol table.2979const size_t numObjsBeforeLTO = ctx.objectFiles.size();2980const size_t numInputFilesBeforeLTO = ctx.driver.files.size();2981compileBitcodeFiles<ELFT>(skipLinkedOutput);29822983// Symbol resolution finished. Report backward reference problems,2984// --print-archive-stats=, and --why-extract=.2985reportBackrefs();2986writeArchiveStats();2987writeWhyExtract();2988if (errorCount())2989return;29902991// Bail out if normal linked output is skipped due to LTO.2992if (skipLinkedOutput)2993return;29942995// compileBitcodeFiles may have produced lto.tmp object files. After this, no2996// more file will be added.2997auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO);2998parallelForEach(newObjectFiles, [](ELFFileBase *file) {2999initSectionsAndLocalSyms(file, /*ignoreComdats=*/true);3000});3001parallelForEach(newObjectFiles, postParseObjectFile);3002for (const DuplicateSymbol &d : ctx.duplicates)3003reportDuplicate(*d.sym, d.file, d.section, d.value);30043005// ELF dependent libraries may have introduced new input files after LTO has3006// completed. This is an error if the files haven't already been parsed, since3007// changing the symbol table could break the semantic assumptions of LTO.3008auto newInputFiles = ArrayRef(ctx.driver.files).slice(numInputFilesBeforeLTO);3009if (!newInputFiles.empty()) {3010DenseSet<StringRef> oldFilenames;3011for (InputFile *f :3012ArrayRef(ctx.driver.files).slice(0, numInputFilesBeforeLTO))3013oldFilenames.insert(f->getName());3014for (InputFile *newFile : newInputFiles)3015if (!oldFilenames.contains(newFile->getName()))3016errorOrWarn("input file '" + newFile->getName() + "' added after LTO");3017}30183019// Handle --exclude-libs again because lto.tmp may reference additional3020// libcalls symbols defined in an excluded archive. This may override3021// versionId set by scanVersionScript().3022if (args.hasArg(OPT_exclude_libs))3023excludeLibs(args);30243025// Record [__acle_se_<sym>, <sym>] pairs for later processing.3026processArmCmseSymbols();30273028// Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.3029redirectSymbols(wrapped);30303031// Replace common symbols with regular symbols.3032replaceCommonSymbols();30333034{3035llvm::TimeTraceScope timeScope("Aggregate sections");3036// Now that we have a complete list of input files.3037// Beyond this point, no new files are added.3038// Aggregate all input sections into one place.3039for (InputFile *f : ctx.objectFiles) {3040for (InputSectionBase *s : f->getSections()) {3041if (!s || s == &InputSection::discarded)3042continue;3043if (LLVM_UNLIKELY(isa<EhInputSection>(s)))3044ctx.ehInputSections.push_back(cast<EhInputSection>(s));3045else3046ctx.inputSections.push_back(s);3047}3048}3049for (BinaryFile *f : ctx.binaryFiles)3050for (InputSectionBase *s : f->getSections())3051ctx.inputSections.push_back(cast<InputSection>(s));3052}30533054{3055llvm::TimeTraceScope timeScope("Strip sections");3056if (ctx.hasSympart.load(std::memory_order_relaxed)) {3057llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {3058if (s->type != SHT_LLVM_SYMPART)3059return false;3060readSymbolPartitionSection<ELFT>(s);3061return true;3062});3063}3064// We do not want to emit debug sections if --strip-all3065// or --strip-debug are given.3066if (config->strip != StripPolicy::None) {3067llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {3068if (isDebugSection(*s))3069return true;3070if (auto *isec = dyn_cast<InputSection>(s))3071if (InputSectionBase *rel = isec->getRelocatedSection())3072if (isDebugSection(*rel))3073return true;30743075return false;3076});3077}3078}30793080// Since we now have a complete set of input files, we can create3081// a .d file to record build dependencies.3082if (!config->dependencyFile.empty())3083writeDependencyFile();30843085// Now that the number of partitions is fixed, save a pointer to the main3086// partition.3087mainPart = &partitions[0];30883089// Read .note.gnu.property sections from input object files which3090// contain a hint to tweak linker's and loader's behaviors.3091readSecurityNotes();30923093// The Target instance handles target-specific stuff, such as applying3094// relocations or writing a PLT section. It also contains target-dependent3095// values such as a default image base address.3096target = getTarget();30973098config->eflags = target->calcEFlags();3099// maxPageSize (sometimes called abi page size) is the maximum page size that3100// the output can be run on. For example if the OS can use 4k or 64k page3101// sizes then maxPageSize must be 64k for the output to be useable on both.3102// All important alignment decisions must use this value.3103config->maxPageSize = getMaxPageSize(args);3104// commonPageSize is the most common page size that the output will be run on.3105// For example if an OS can use 4k or 64k page sizes and 4k is more common3106// than 64k then commonPageSize is set to 4k. commonPageSize can be used for3107// optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it3108// is limited to writing trap instructions on the last executable segment.3109config->commonPageSize = getCommonPageSize(args);31103111config->imageBase = getImageBase(args);31123113// This adds a .comment section containing a version string.3114if (!config->relocatable)3115ctx.inputSections.push_back(createCommentSection());31163117// Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.3118splitSections<ELFT>();31193120// Garbage collection and removal of shared symbols from unused shared objects.3121markLive<ELFT>();31223123// Make copies of any input sections that need to be copied into each3124// partition.3125copySectionsIntoPartitions();31263127if (canHaveMemtagGlobals()) {3128llvm::TimeTraceScope timeScope("Process memory tagged symbols");3129createTaggedSymbols(ctx.objectFiles);3130}31313132// Create synthesized sections such as .got and .plt. This is called before3133// processSectionCommands() so that they can be placed by SECTIONS commands.3134createSyntheticSections<ELFT>();31353136// Some input sections that are used for exception handling need to be moved3137// into synthetic sections. Do that now so that they aren't assigned to3138// output sections in the usual way.3139if (!config->relocatable)3140combineEhSections();31413142// Merge .riscv.attributes sections.3143if (config->emachine == EM_RISCV)3144mergeRISCVAttributesSections();31453146{3147llvm::TimeTraceScope timeScope("Assign sections");31483149// Create output sections described by SECTIONS commands.3150script->processSectionCommands();31513152// Linker scripts control how input sections are assigned to output3153// sections. Input sections that were not handled by scripts are called3154// "orphans", and they are assigned to output sections by the default rule.3155// Process that.3156script->addOrphanSections();3157}31583159{3160llvm::TimeTraceScope timeScope("Merge/finalize input sections");31613162// Migrate InputSectionDescription::sectionBases to sections. This includes3163// merging MergeInputSections into a single MergeSyntheticSection. From this3164// point onwards InputSectionDescription::sections should be used instead of3165// sectionBases.3166for (SectionCommand *cmd : script->sectionCommands)3167if (auto *osd = dyn_cast<OutputDesc>(cmd))3168osd->osec.finalizeInputSections(&script.s);3169}31703171// Two input sections with different output sections should not be folded.3172// ICF runs after processSectionCommands() so that we know the output sections.3173if (config->icf != ICFLevel::None) {3174findKeepUniqueSections<ELFT>(args);3175doIcf<ELFT>();3176}31773178// Read the callgraph now that we know what was gced or icfed3179if (config->callGraphProfileSort != CGProfileSortKind::None) {3180if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))3181if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))3182readCallGraph(*buffer);3183readCallGraphsFromObjectFiles<ELFT>();3184}31853186// Write the result to the file.3187writeResult<ELFT>();3188}318931903191