3514 lines · cpp
1//===- Driver.cpp ---------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// The driver drives the entire linking process. It is responsible for10// parsing command line options and doing whatever it is instructed to do.11//12// One notable thing in the LLD's driver when compared to other linkers is13// that the LLD's driver is agnostic on the host operating system.14// Other linkers usually have implicit default values (such as a dynamic15// linker path or library paths) for each host OS.16//17// I don't think implicit default values are useful because they are18// usually explicitly specified by the compiler ctx.driver. They can even19// be harmful when you are doing cross-linking. Therefore, in LLD, we20// simply trust the compiler driver to pass all required options and21// don't try to make effort on our side.22//23//===----------------------------------------------------------------------===//24 25#include "Driver.h"26#include "Config.h"27#include "ICF.h"28#include "InputFiles.h"29#include "InputSection.h"30#include "LTO.h"31#include "LinkerScript.h"32#include "MarkLive.h"33#include "OutputSections.h"34#include "ScriptParser.h"35#include "SymbolTable.h"36#include "Symbols.h"37#include "SyntheticSections.h"38#include "Target.h"39#include "Writer.h"40#include "lld/Common/Args.h"41#include "lld/Common/CommonLinkerContext.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/Version.h"47#include "llvm/ADT/STLExtras.h"48#include "llvm/ADT/SetVector.h"49#include "llvm/ADT/StringExtras.h"50#include "llvm/ADT/StringSwitch.h"51#include "llvm/Config/llvm-config.h"52#include "llvm/LTO/LTO.h"53#include "llvm/Object/Archive.h"54#include "llvm/Object/IRObjectFile.h"55#include "llvm/Remarks/HotnessThresholdParser.h"56#include "llvm/Support/CommandLine.h"57#include "llvm/Support/Compression.h"58#include "llvm/Support/FileSystem.h"59#include "llvm/Support/GlobPattern.h"60#include "llvm/Support/LEB128.h"61#include "llvm/Support/Parallel.h"62#include "llvm/Support/Path.h"63#include "llvm/Support/SaveAndRestore.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>71 72using 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;79 80static void setConfigs(Ctx &ctx, opt::InputArgList &args);81static void readConfigs(Ctx &ctx, opt::InputArgList &args);82 83ELFSyncStream elf::Log(Ctx &ctx) { return {ctx, DiagLevel::Log}; }84ELFSyncStream elf::Msg(Ctx &ctx) { return {ctx, DiagLevel::Msg}; }85ELFSyncStream elf::Warn(Ctx &ctx) { return {ctx, DiagLevel::Warn}; }86ELFSyncStream elf::Err(Ctx &ctx) {87 return {ctx, ctx.arg.noinhibitExec ? DiagLevel::Warn : DiagLevel::Err};88}89ELFSyncStream elf::ErrAlways(Ctx &ctx) { return {ctx, DiagLevel::Err}; }90ELFSyncStream elf::Fatal(Ctx &ctx) { return {ctx, DiagLevel::Fatal}; }91uint64_t elf::errCount(Ctx &ctx) { return ctx.e.errorCount; }92 93ELFSyncStream elf::InternalErr(Ctx &ctx, const uint8_t *buf) {94 ELFSyncStream s(ctx, DiagLevel::Err);95 s << "internal linker error: ";96 return s;97}98 99Ctx::Ctx() : driver(*this) {}100 101llvm::raw_fd_ostream Ctx::openAuxiliaryFile(llvm::StringRef filename,102 std::error_code &ec) {103 using namespace llvm::sys::fs;104 OpenFlags flags =105 auxiliaryFiles.insert(filename).second ? OF_None : OF_Append;106 if (e.disableOutput && filename == "-") {107#ifdef _WIN32108 filename = "NUL";109#else110 filename = "/dev/null";111#endif112 }113 return {filename, ec, flags};114}115 116namespace lld {117namespace elf {118bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,119 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {120 // This driver-specific context will be freed later by unsafeLldMain().121 auto *context = new Ctx;122 Ctx &ctx = *context;123 124 context->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);125 context->e.logName = args::getFilenameWithoutExe(args[0]);126 context->e.errorLimitExceededMsg =127 "too many errors emitted, stopping now (use "128 "--error-limit=0 to see all errors)";129 130 LinkerScript script(ctx);131 ctx.script = &script;132 ctx.symAux.emplace_back();133 ctx.symtab = std::make_unique<SymbolTable>(ctx);134 135 ctx.partitions.clear();136 ctx.partitions.emplace_back(ctx);137 138 ctx.arg.progName = args[0];139 140 ctx.driver.linkerMain(args);141 142 return errCount(ctx) == 0;143}144} // namespace elf145} // namespace lld146 147// Parses a linker -m option.148static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(Ctx &ctx,149 StringRef emul) {150 uint8_t osabi = 0;151 StringRef s = emul;152 if (s.ends_with("_fbsd")) {153 s = s.drop_back(5);154 osabi = ELFOSABI_FREEBSD;155 }156 157 std::pair<ELFKind, uint16_t> ret =158 StringSwitch<std::pair<ELFKind, uint16_t>>(s)159 .Cases({"aarch64elf", "aarch64linux"}, {ELF64LEKind, EM_AARCH64})160 .Cases({"aarch64elfb", "aarch64linuxb"}, {ELF64BEKind, EM_AARCH64})161 .Cases({"armelf", "armelf_linux_eabi"}, {ELF32LEKind, EM_ARM})162 .Cases({"armelfb", "armelfb_linux_eabi"}, {ELF32BEKind, EM_ARM})163 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})164 .Cases({"elf32btsmip", "elf32btsmipn32"}, {ELF32BEKind, EM_MIPS})165 .Cases({"elf32ltsmip", "elf32ltsmipn32"}, {ELF32LEKind, EM_MIPS})166 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})167 .Cases({"elf32ppc", "elf32ppclinux"}, {ELF32BEKind, EM_PPC})168 .Cases({"elf32lppc", "elf32lppclinux"}, {ELF32LEKind, EM_PPC})169 .Case("elf32loongarch", {ELF32LEKind, EM_LOONGARCH})170 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})171 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})172 .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})173 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})174 .Case("elf64lppc", {ELF64LEKind, EM_PPC64})175 .Cases({"elf_amd64", "elf_x86_64"}, {ELF64LEKind, EM_X86_64})176 .Case("elf_i386", {ELF32LEKind, EM_386})177 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})178 .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})179 .Case("msp430elf", {ELF32LEKind, EM_MSP430})180 .Case("elf64_amdgpu", {ELF64LEKind, EM_AMDGPU})181 .Case("elf64loongarch", {ELF64LEKind, EM_LOONGARCH})182 .Case("elf64_s390", {ELF64BEKind, EM_S390})183 .Case("hexagonelf", {ELF32LEKind, EM_HEXAGON})184 .Default({ELFNoneKind, EM_NONE});185 186 if (ret.first == ELFNoneKind)187 ErrAlways(ctx) << "unknown emulation: " << emul;188 if (ret.second == EM_MSP430)189 osabi = ELFOSABI_STANDALONE;190 else if (ret.second == EM_AMDGPU)191 osabi = ELFOSABI_AMDGPU_HSA;192 return std::make_tuple(ret.first, ret.second, osabi);193}194 195// Returns slices of MB by parsing MB as an archive file.196// Each slice consists of a member file in the archive.197std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(198 Ctx &ctx, MemoryBufferRef mb) {199 std::unique_ptr<Archive> file =200 CHECK(Archive::create(mb),201 mb.getBufferIdentifier() + ": failed to parse archive");202 203 std::vector<std::pair<MemoryBufferRef, uint64_t>> v;204 Error err = Error::success();205 bool addToTar = file->isThin() && ctx.tar;206 for (const Archive::Child &c : file->children(err)) {207 MemoryBufferRef mbref =208 CHECK(c.getMemoryBufferRef(),209 mb.getBufferIdentifier() +210 ": could not get the buffer for a child of the archive");211 if (addToTar)212 ctx.tar->append(relativeToRoot(check(c.getFullName())),213 mbref.getBuffer());214 v.push_back(std::make_pair(mbref, c.getChildOffset()));215 }216 if (err)217 Fatal(ctx) << mb.getBufferIdentifier()218 << ": Archive::children failed: " << std::move(err);219 220 // Take ownership of memory buffers created for members of thin archives.221 std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers();222 std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers));223 224 return v;225}226 227static bool isBitcode(MemoryBufferRef mb) {228 return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode;229}230 231bool LinkerDriver::tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName,232 uint64_t offsetInArchive, bool lazy) {233 if (!ctx.arg.fatLTOObjects)234 return false;235 Expected<MemoryBufferRef> fatLTOData =236 IRObjectFile::findBitcodeInMemBuffer(mb);237 if (errorToBool(fatLTOData.takeError()))238 return false;239 files.push_back(std::make_unique<BitcodeFile>(ctx, *fatLTOData, archiveName,240 offsetInArchive, lazy));241 return true;242}243 244// Opens a file and create a file object. Path has to be resolved already.245void LinkerDriver::addFile(StringRef path, bool withLOption) {246 using namespace sys::fs;247 248 std::optional<MemoryBufferRef> buffer = readFile(ctx, path);249 if (!buffer)250 return;251 MemoryBufferRef mbref = *buffer;252 253 if (ctx.arg.formatBinary) {254 files.push_back(std::make_unique<BinaryFile>(ctx, mbref));255 return;256 }257 258 switch (identify_magic(mbref.getBuffer())) {259 case file_magic::unknown:260 readLinkerScript(ctx, mbref);261 return;262 case file_magic::archive: {263 auto members = getArchiveMembers(ctx, mbref);264 if (inWholeArchive) {265 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {266 if (isBitcode(p.first))267 files.push_back(std::make_unique<BitcodeFile>(ctx, p.first, path,268 p.second, false));269 else if (!tryAddFatLTOFile(p.first, path, p.second, false))270 files.push_back(createObjFile(ctx, p.first, path));271 }272 return;273 }274 275 archiveFiles.emplace_back(path, members.size());276 277 // Handle archives and --start-lib/--end-lib using the same code path. This278 // scans all the ELF relocatable object files and bitcode files in the279 // archive rather than just the index file, with the benefit that the280 // symbols are only loaded once. For many projects archives see high281 // utilization rates and it is a net performance win. --start-lib scans282 // symbols in the same order that llvm-ar adds them to the index, so in the283 // common case the semantics are identical. If the archive symbol table was284 // created in a different order, or is incomplete, this strategy has285 // different semantics. Such output differences are considered user error.286 //287 // All files within the archive get the same group ID to allow mutual288 // references for --warn-backrefs.289 SaveAndRestore saved(isInGroup, true);290 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {291 auto magic = identify_magic(p.first.getBuffer());292 if (magic == file_magic::elf_relocatable) {293 if (!tryAddFatLTOFile(p.first, path, p.second, true))294 files.push_back(createObjFile(ctx, p.first, path, true));295 } else if (magic == file_magic::bitcode)296 files.push_back(297 std::make_unique<BitcodeFile>(ctx, p.first, path, p.second, true));298 else299 Warn(ctx) << path << ": archive member '"300 << p.first.getBufferIdentifier()301 << "' is neither ET_REL nor LLVM bitcode";302 }303 if (!saved.get())304 ++nextGroupId;305 return;306 }307 case file_magic::elf_shared_object: {308 if (ctx.arg.isStatic) {309 ErrAlways(ctx) << "attempted static link of dynamic object " << path;310 return;311 }312 313 // Shared objects are identified by soname. soname is (if specified)314 // DT_SONAME and falls back to filename. If a file was specified by -lfoo,315 // the directory part is ignored. Note that path may be a temporary and316 // cannot be stored into SharedFile::soName.317 path = mbref.getBufferIdentifier();318 auto f = std::make_unique<SharedFile>(319 ctx, mbref, withLOption ? path::filename(path) : path);320 f->init();321 files.push_back(std::move(f));322 return;323 }324 case file_magic::bitcode:325 files.push_back(std::make_unique<BitcodeFile>(ctx, mbref, "", 0, inLib));326 break;327 case file_magic::elf_relocatable:328 if (!tryAddFatLTOFile(mbref, "", 0, inLib))329 files.push_back(createObjFile(ctx, mbref, "", inLib));330 break;331 default:332 ErrAlways(ctx) << path << ": unknown file type";333 }334}335 336// Add a given library by searching it from input search paths.337void LinkerDriver::addLibrary(StringRef name) {338 if (std::optional<std::string> path = searchLibrary(ctx, name))339 addFile(ctx.saver.save(*path), /*withLOption=*/true);340 else341 ctx.e.error("unable to find library -l" + name, ErrorTag::LibNotFound,342 {name});343}344 345// This function is called on startup. We need this for LTO since346// LTO calls LLVM functions to compile bitcode files to native code.347// Technically this can be delayed until we read bitcode files, but348// we don't bother to do lazily because the initialization is fast.349static void initLLVM() {350 InitializeAllTargets();351 InitializeAllTargetMCs();352 InitializeAllAsmPrinters();353 InitializeAllAsmParsers();354}355 356// Some command line options or some combinations of them are not allowed.357// This function checks for such errors.358static void checkOptions(Ctx &ctx) {359 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup360 // table which is a relatively new feature.361 if (ctx.arg.emachine == EM_MIPS && ctx.arg.gnuHash)362 ErrAlways(ctx)363 << "the .gnu.hash section is not compatible with the MIPS target";364 365 if (ctx.arg.emachine == EM_ARM) {366 if (!ctx.arg.cmseImplib) {367 if (!ctx.arg.cmseInputLib.empty())368 ErrAlways(ctx) << "--in-implib may not be used without --cmse-implib";369 if (!ctx.arg.cmseOutputLib.empty())370 ErrAlways(ctx) << "--out-implib may not be used without --cmse-implib";371 }372 if (ctx.arg.fixCortexA8 && !ctx.arg.isLE)373 ErrAlways(ctx)374 << "--fix-cortex-a8 is not supported on big endian targets";375 } else {376 if (ctx.arg.cmseImplib)377 ErrAlways(ctx) << "--cmse-implib is only supported on ARM targets";378 if (!ctx.arg.cmseInputLib.empty())379 ErrAlways(ctx) << "--in-implib is only supported on ARM targets";380 if (!ctx.arg.cmseOutputLib.empty())381 ErrAlways(ctx) << "--out-implib is only supported on ARM targets";382 if (ctx.arg.fixCortexA8)383 ErrAlways(ctx) << "--fix-cortex-a8 is only supported on ARM targets";384 if (ctx.arg.armBe8)385 ErrAlways(ctx) << "--be8 is only supported on ARM targets";386 }387 388 if (ctx.arg.emachine != EM_AARCH64) {389 if (ctx.arg.executeOnly)390 ErrAlways(ctx) << "--execute-only is only supported on AArch64 targets";391 if (ctx.arg.fixCortexA53Errata843419)392 ErrAlways(ctx) << "--fix-cortex-a53-843419 is only supported on AArch64";393 if (ctx.arg.zPacPlt)394 ErrAlways(ctx) << "-z pac-plt only supported on AArch64";395 if (ctx.arg.zForceBti)396 ErrAlways(ctx) << "-z force-bti only supported on AArch64";397 if (ctx.arg.zBtiReport != ReportPolicy::None)398 ErrAlways(ctx) << "-z bti-report only supported on AArch64";399 if (ctx.arg.zPauthReport != ReportPolicy::None)400 ErrAlways(ctx) << "-z pauth-report only supported on AArch64";401 if (ctx.arg.zGcsReport != ReportPolicy::None)402 ErrAlways(ctx) << "-z gcs-report only supported on AArch64";403 if (ctx.arg.zGcsReportDynamic != ReportPolicy::None)404 ErrAlways(ctx) << "-z gcs-report-dynamic only supported on AArch64";405 if (ctx.arg.zGcs != GcsPolicy::Implicit)406 ErrAlways(ctx) << "-z gcs only supported on AArch64";407 }408 409 if (ctx.arg.emachine != EM_AARCH64 && ctx.arg.emachine != EM_ARM &&410 ctx.arg.zExecuteOnlyReport != ReportPolicy::None)411 ErrAlways(ctx)412 << "-z execute-only-report only supported on AArch64 and ARM";413 414 if (ctx.arg.emachine != EM_PPC64) {415 if (ctx.arg.tocOptimize)416 ErrAlways(ctx) << "--toc-optimize is only supported on PowerPC64 targets";417 if (ctx.arg.pcRelOptimize)418 ErrAlways(ctx)419 << "--pcrel-optimize is only supported on PowerPC64 targets";420 }421 422 if (ctx.arg.emachine != EM_RISCV) {423 if (ctx.arg.relaxGP)424 ErrAlways(ctx) << "--relax-gp is only supported on RISC-V targets";425 if (ctx.arg.zZicfilpUnlabeledReport != ReportPolicy::None)426 ErrAlways(ctx) << "-z zicfilip-unlabeled-report is only supported on "427 "RISC-V targets";428 if (ctx.arg.zZicfilpFuncSigReport != ReportPolicy::None)429 ErrAlways(ctx) << "-z zicfilip-func-sig-report is only supported on "430 "RISC-V targets";431 if (ctx.arg.zZicfissReport != ReportPolicy::None)432 ErrAlways(ctx) << "-z zicfiss-report is only supported on RISC-V targets";433 if (ctx.arg.zZicfilp != ZicfilpPolicy::Implicit)434 ErrAlways(ctx) << "-z zicfilp is only supported on RISC-V targets";435 if (ctx.arg.zZicfiss != ZicfissPolicy::Implicit)436 ErrAlways(ctx) << "-z zicfiss is only supported on RISC-V targets";437 }438 439 if (ctx.arg.emachine != EM_386 && ctx.arg.emachine != EM_X86_64 &&440 ctx.arg.zCetReport != ReportPolicy::None)441 ErrAlways(ctx) << "-z cet-report only supported on X86 and X86_64";442 443 if (ctx.arg.pie && ctx.arg.shared)444 ErrAlways(ctx) << "-shared and -pie may not be used together";445 446 if (!ctx.arg.shared && !ctx.arg.filterList.empty())447 ErrAlways(ctx) << "-F may not be used without -shared";448 449 if (!ctx.arg.shared && !ctx.arg.auxiliaryList.empty())450 ErrAlways(ctx) << "-f may not be used without -shared";451 452 if (ctx.arg.strip == StripPolicy::All && ctx.arg.emitRelocs)453 ErrAlways(ctx) << "--strip-all and --emit-relocs may not be used together";454 455 if (ctx.arg.zText && ctx.arg.zIfuncNoplt)456 ErrAlways(ctx) << "-z text and -z ifunc-noplt may not be used together";457 458 if (ctx.arg.relocatable) {459 if (ctx.arg.shared)460 ErrAlways(ctx) << "-r and -shared may not be used together";461 if (ctx.arg.gdbIndex)462 ErrAlways(ctx) << "-r and --gdb-index may not be used together";463 if (ctx.arg.icf != ICFLevel::None)464 ErrAlways(ctx) << "-r and --icf may not be used together";465 if (ctx.arg.pie)466 ErrAlways(ctx) << "-r and -pie may not be used together";467 if (ctx.arg.exportDynamic)468 ErrAlways(ctx) << "-r and --export-dynamic may not be used together";469 if (ctx.arg.debugNames)470 ErrAlways(ctx) << "-r and --debug-names may not be used together";471 if (!ctx.arg.zSectionHeader)472 ErrAlways(ctx) << "-r and -z nosectionheader may not be used together";473 }474 475 if (ctx.arg.executeOnly) {476 if (ctx.arg.singleRoRx && !ctx.script->hasSectionsCommand)477 ErrAlways(ctx)478 << "--execute-only and --no-rosegment cannot be used together";479 }480 481 if (ctx.arg.zRetpolineplt && ctx.arg.zForceIbt)482 ErrAlways(ctx) << "-z force-ibt may not be used with -z retpolineplt";483}484 485static const char *getReproduceOption(opt::InputArgList &args) {486 if (auto *arg = args.getLastArg(OPT_reproduce))487 return arg->getValue();488 return getenv("LLD_REPRODUCE");489}490 491static bool hasZOption(opt::InputArgList &args, StringRef key) {492 bool ret = false;493 for (auto *arg : args.filtered(OPT_z))494 if (key == arg->getValue()) {495 ret = true;496 arg->claim();497 }498 return ret;499}500 501static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,502 bool defaultValue) {503 for (auto *arg : args.filtered(OPT_z)) {504 StringRef v = arg->getValue();505 if (k1 == v)506 defaultValue = true;507 else if (k2 == v)508 defaultValue = false;509 else510 continue;511 arg->claim();512 }513 return defaultValue;514}515 516static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {517 auto ret = SeparateSegmentKind::None;518 for (auto *arg : args.filtered(OPT_z)) {519 StringRef v = arg->getValue();520 if (v == "noseparate-code")521 ret = SeparateSegmentKind::None;522 else if (v == "separate-code")523 ret = SeparateSegmentKind::Code;524 else if (v == "separate-loadable-segments")525 ret = SeparateSegmentKind::Loadable;526 else527 continue;528 arg->claim();529 }530 return ret;531}532 533static GnuStackKind getZGnuStack(opt::InputArgList &args) {534 auto ret = GnuStackKind::NoExec;535 for (auto *arg : args.filtered(OPT_z)) {536 StringRef v = arg->getValue();537 if (v == "execstack")538 ret = GnuStackKind::Exec;539 else if (v == "noexecstack")540 ret = GnuStackKind::NoExec;541 else if (v == "nognustack")542 ret = GnuStackKind::None;543 else544 continue;545 arg->claim();546 }547 return ret;548}549 550static uint8_t getZStartStopVisibility(Ctx &ctx, opt::InputArgList &args) {551 uint8_t ret = STV_PROTECTED;552 for (auto *arg : args.filtered(OPT_z)) {553 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');554 if (kv.first == "start-stop-visibility") {555 arg->claim();556 if (kv.second == "default")557 ret = STV_DEFAULT;558 else if (kv.second == "internal")559 ret = STV_INTERNAL;560 else if (kv.second == "hidden")561 ret = STV_HIDDEN;562 else if (kv.second == "protected")563 ret = STV_PROTECTED;564 else565 ErrAlways(ctx) << "unknown -z start-stop-visibility= value: "566 << StringRef(kv.second);567 }568 }569 return ret;570}571 572static GcsPolicy getZGcs(Ctx &ctx, opt::InputArgList &args) {573 GcsPolicy ret = GcsPolicy::Implicit;574 for (auto *arg : args.filtered(OPT_z)) {575 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');576 if (kv.first == "gcs") {577 arg->claim();578 if (kv.second == "implicit")579 ret = GcsPolicy::Implicit;580 else if (kv.second == "never")581 ret = GcsPolicy::Never;582 else if (kv.second == "always")583 ret = GcsPolicy::Always;584 else585 ErrAlways(ctx) << "unknown -z gcs= value: " << kv.second;586 }587 }588 return ret;589}590 591static ZicfilpPolicy getZZicfilp(Ctx &ctx, opt::InputArgList &args) {592 auto ret = ZicfilpPolicy::Implicit;593 for (auto *arg : args.filtered(OPT_z)) {594 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');595 if (kv.first == "zicfilp") {596 arg->claim();597 if (kv.second == "unlabeled")598 ret = ZicfilpPolicy::Unlabeled;599 else if (kv.second == "func-sig")600 ret = ZicfilpPolicy::FuncSig;601 else if (kv.second == "never")602 ret = ZicfilpPolicy::Never;603 else if (kv.second == "implicit")604 ret = ZicfilpPolicy::Implicit;605 else606 ErrAlways(ctx) << "unknown -z zicfilp= value: " << kv.second;607 }608 }609 return ret;610}611 612static ZicfissPolicy getZZicfiss(Ctx &ctx, opt::InputArgList &args) {613 auto ret = ZicfissPolicy::Implicit;614 for (auto *arg : args.filtered(OPT_z)) {615 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');616 if (kv.first == "zicfiss") {617 arg->claim();618 if (kv.second == "always")619 ret = ZicfissPolicy::Always;620 else if (kv.second == "never")621 ret = ZicfissPolicy::Never;622 else if (kv.second == "implicit")623 ret = ZicfissPolicy::Implicit;624 else625 ErrAlways(ctx) << "unknown -z zicfiss= value: " << kv.second;626 }627 }628 return ret;629}630 631// Report a warning for an unknown -z option.632static void checkZOptions(Ctx &ctx, opt::InputArgList &args) {633 // This function is called before getTarget(), when certain options are not634 // initialized yet. Claim them here.635 args::getZOptionValue(args, OPT_z, "max-page-size", 0);636 args::getZOptionValue(args, OPT_z, "common-page-size", 0);637 getZFlag(args, "rel", "rela", false);638 getZFlag(args, "dynamic-undefined-weak", "nodynamic-undefined-weak", false);639 for (auto *arg : args.filtered(OPT_z))640 if (!arg->isClaimed())641 Warn(ctx) << "unknown -z value: " << StringRef(arg->getValue());642}643 644constexpr const char *saveTempsValues[] = {645 "resolution", "preopt", "promote", "internalize", "import",646 "opt", "precodegen", "prelink", "combinedindex"};647 648LinkerDriver::LinkerDriver(Ctx &ctx) : ctx(ctx) {}649 650void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {651 ELFOptTable parser;652 opt::InputArgList args = parser.parse(ctx, argsArr.slice(1));653 654 // Interpret these flags early because Err/Warn depend on them.655 ctx.e.errorLimit = args::getInteger(args, OPT_error_limit, 20);656 ctx.e.fatalWarnings =657 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) &&658 !args.hasArg(OPT_no_warnings);659 ctx.e.suppressWarnings = args.hasArg(OPT_no_warnings);660 661 // Handle -help662 if (args.hasArg(OPT_help)) {663 printHelp(ctx);664 return;665 }666 667 // Handle -v or -version.668 //669 // A note about "compatible with GNU linkers" message: this is a hack for670 // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as671 // a GNU compatible linker. See672 // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.673 //674 // This is somewhat ugly hack, but in reality, we had no choice other675 // than doing this. Considering the very long release cycle of Libtool,676 // it is not easy to improve it to recognize LLD as a GNU compatible677 // linker in a timely manner. Even if we can make it, there are still a678 // lot of "configure" scripts out there that are generated by old version679 // of Libtool. We cannot convince every software developer to migrate to680 // the latest version and re-generate scripts. So we have this hack.681 if (args.hasArg(OPT_v) || args.hasArg(OPT_version))682 Msg(ctx) << getLLDVersion() << " (compatible with GNU linkers)";683 684 if (const char *path = getReproduceOption(args)) {685 // Note that --reproduce is a debug option so you can ignore it686 // if you are trying to understand the whole picture of the code.687 Expected<std::unique_ptr<TarWriter>> errOrWriter =688 TarWriter::create(path, path::stem(path));689 if (errOrWriter) {690 ctx.tar = std::move(*errOrWriter);691 ctx.tar->append("response.txt", createResponseFile(args));692 ctx.tar->append("version.txt", getLLDVersion() + "\n");693 StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);694 if (!ltoSampleProfile.empty())695 readFile(ctx, ltoSampleProfile);696 } else {697 ErrAlways(ctx) << "--reproduce: " << errOrWriter.takeError();698 }699 }700 701 readConfigs(ctx, args);702 checkZOptions(ctx, args);703 704 // The behavior of -v or --version is a bit strange, but this is705 // needed for compatibility with GNU linkers.706 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))707 return;708 if (args.hasArg(OPT_version))709 return;710 711 // Initialize time trace profiler.712 if (ctx.arg.timeTraceEnabled)713 timeTraceProfilerInitialize(ctx.arg.timeTraceGranularity, ctx.arg.progName);714 715 {716 llvm::TimeTraceScope timeScope("ExecuteLinker");717 718 initLLVM();719 createFiles(args);720 if (errCount(ctx))721 return;722 723 inferMachineType();724 setConfigs(ctx, args);725 checkOptions(ctx);726 if (errCount(ctx))727 return;728 729 invokeELFT(link, args);730 }731 732 if (ctx.arg.timeTraceEnabled) {733 checkError(ctx.e, timeTraceProfilerWrite(734 args.getLastArgValue(OPT_time_trace_eq).str(),735 ctx.arg.outputFile));736 timeTraceProfilerCleanup();737 }738}739 740static std::string getRpath(opt::InputArgList &args) {741 SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath);742 return llvm::join(v.begin(), v.end(), ":");743}744 745// Determines what we should do if there are remaining unresolved746// symbols after the name resolution.747static void setUnresolvedSymbolPolicy(Ctx &ctx, opt::InputArgList &args) {748 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,749 OPT_warn_unresolved_symbols, true)750 ? UnresolvedPolicy::ReportError751 : UnresolvedPolicy::Warn;752 // -shared implies --unresolved-symbols=ignore-all because missing753 // symbols are likely to be resolved at runtime.754 bool diagRegular = !ctx.arg.shared, diagShlib = !ctx.arg.shared;755 756 for (const opt::Arg *arg : args) {757 switch (arg->getOption().getID()) {758 case OPT_unresolved_symbols: {759 StringRef s = arg->getValue();760 if (s == "ignore-all") {761 diagRegular = false;762 diagShlib = false;763 } else if (s == "ignore-in-object-files") {764 diagRegular = false;765 diagShlib = true;766 } else if (s == "ignore-in-shared-libs") {767 diagRegular = true;768 diagShlib = false;769 } else if (s == "report-all") {770 diagRegular = true;771 diagShlib = true;772 } else {773 ErrAlways(ctx) << "unknown --unresolved-symbols value: " << s;774 }775 break;776 }777 case OPT_no_undefined:778 diagRegular = true;779 break;780 case OPT_z:781 if (StringRef(arg->getValue()) == "defs")782 diagRegular = true;783 else if (StringRef(arg->getValue()) == "undefs")784 diagRegular = false;785 else786 break;787 arg->claim();788 break;789 case OPT_allow_shlib_undefined:790 diagShlib = false;791 break;792 case OPT_no_allow_shlib_undefined:793 diagShlib = true;794 break;795 }796 }797 798 ctx.arg.unresolvedSymbols =799 diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;800 ctx.arg.unresolvedSymbolsInShlib =801 diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;802}803 804static Target2Policy getTarget2(Ctx &ctx, opt::InputArgList &args) {805 StringRef s = args.getLastArgValue(OPT_target2, "got-rel");806 if (s == "rel")807 return Target2Policy::Rel;808 if (s == "abs")809 return Target2Policy::Abs;810 if (s == "got-rel")811 return Target2Policy::GotRel;812 ErrAlways(ctx) << "unknown --target2 option: " << s;813 return Target2Policy::GotRel;814}815 816static bool isOutputFormatBinary(Ctx &ctx, opt::InputArgList &args) {817 StringRef s = args.getLastArgValue(OPT_oformat, "elf");818 if (s == "binary")819 return true;820 if (!s.starts_with("elf"))821 ErrAlways(ctx) << "unknown --oformat value: " << s;822 return false;823}824 825static DiscardPolicy getDiscard(opt::InputArgList &args) {826 auto *arg =827 args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);828 if (!arg)829 return DiscardPolicy::Default;830 if (arg->getOption().getID() == OPT_discard_all)831 return DiscardPolicy::All;832 if (arg->getOption().getID() == OPT_discard_locals)833 return DiscardPolicy::Locals;834 return DiscardPolicy::None;835}836 837static StringRef getDynamicLinker(Ctx &ctx, opt::InputArgList &args) {838 auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);839 if (!arg)840 return "";841 if (arg->getOption().getID() == OPT_no_dynamic_linker)842 return "";843 return arg->getValue();844}845 846static int getMemtagMode(Ctx &ctx, opt::InputArgList &args) {847 StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode);848 if (memtagModeArg.empty()) {849 if (ctx.arg.androidMemtagStack)850 Warn(ctx) << "--android-memtag-mode is unspecified, leaving "851 "--android-memtag-stack a no-op";852 else if (ctx.arg.androidMemtagHeap)853 Warn(ctx) << "--android-memtag-mode is unspecified, leaving "854 "--android-memtag-heap a no-op";855 return ELF::NT_MEMTAG_LEVEL_NONE;856 }857 858 if (memtagModeArg == "sync")859 return ELF::NT_MEMTAG_LEVEL_SYNC;860 if (memtagModeArg == "async")861 return ELF::NT_MEMTAG_LEVEL_ASYNC;862 if (memtagModeArg == "none")863 return ELF::NT_MEMTAG_LEVEL_NONE;864 865 ErrAlways(ctx) << "unknown --android-memtag-mode value: \"" << memtagModeArg866 << "\", should be one of {async, sync, none}";867 return ELF::NT_MEMTAG_LEVEL_NONE;868}869 870static ICFLevel getICF(opt::InputArgList &args) {871 auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);872 if (!arg || arg->getOption().getID() == OPT_icf_none)873 return ICFLevel::None;874 if (arg->getOption().getID() == OPT_icf_safe)875 return ICFLevel::Safe;876 return ICFLevel::All;877}878 879static void parsePackageMetadata(Ctx &ctx, const opt::Arg &arg) {880 unsigned c0, c1;881 SmallVector<uint8_t, 0> decoded;882 StringRef s = arg.getValue();883 for (size_t i = 0, e = s.size(); i != e; ++i) {884 if (s[i] != '%') {885 decoded.push_back(s[i]);886 } else if (i + 2 < e && (c1 = hexDigitValue(s[i + 1])) != -1u &&887 (c0 = hexDigitValue(s[i + 2])) != -1u) {888 decoded.push_back(uint8_t(c1 * 16 + c0));889 i += 2;890 } else {891 ErrAlways(ctx) << arg.getSpelling() << ": invalid % escape at byte " << i892 << "; supports only %[0-9a-fA-F][0-9a-fA-F]";893 return;894 }895 }896 ctx.arg.packageMetadata = std::move(decoded);897}898 899static StripPolicy getStrip(Ctx &ctx, opt::InputArgList &args) {900 if (args.hasArg(OPT_relocatable))901 return StripPolicy::None;902 if (!ctx.arg.zSectionHeader)903 return StripPolicy::All;904 905 auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);906 if (!arg)907 return StripPolicy::None;908 if (arg->getOption().getID() == OPT_strip_all)909 return StripPolicy::All;910 return StripPolicy::Debug;911}912 913static uint64_t parseSectionAddress(Ctx &ctx, StringRef s,914 opt::InputArgList &args,915 const opt::Arg &arg) {916 uint64_t va = 0;917 s.consume_front("0x");918 if (!to_integer(s, va, 16))919 ErrAlways(ctx) << "invalid argument: " << arg.getAsString(args);920 return va;921}922 923static StringMap<uint64_t> getSectionStartMap(Ctx &ctx,924 opt::InputArgList &args) {925 StringMap<uint64_t> ret;926 for (auto *arg : args.filtered(OPT_section_start)) {927 StringRef name;928 StringRef addr;929 std::tie(name, addr) = StringRef(arg->getValue()).split('=');930 ret[name] = parseSectionAddress(ctx, addr, args, *arg);931 }932 933 if (auto *arg = args.getLastArg(OPT_Ttext))934 ret[".text"] = parseSectionAddress(ctx, arg->getValue(), args, *arg);935 if (auto *arg = args.getLastArg(OPT_Tdata))936 ret[".data"] = parseSectionAddress(ctx, arg->getValue(), args, *arg);937 if (auto *arg = args.getLastArg(OPT_Tbss))938 ret[".bss"] = parseSectionAddress(ctx, arg->getValue(), args, *arg);939 return ret;940}941 942static SortSectionPolicy getSortSection(Ctx &ctx, opt::InputArgList &args) {943 StringRef s = args.getLastArgValue(OPT_sort_section);944 if (s == "alignment")945 return SortSectionPolicy::Alignment;946 if (s == "name")947 return SortSectionPolicy::Name;948 if (!s.empty())949 ErrAlways(ctx) << "unknown --sort-section rule: " << s;950 return SortSectionPolicy::Default;951}952 953static OrphanHandlingPolicy getOrphanHandling(Ctx &ctx,954 opt::InputArgList &args) {955 StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");956 if (s == "warn")957 return OrphanHandlingPolicy::Warn;958 if (s == "error")959 return OrphanHandlingPolicy::Error;960 if (s != "place")961 ErrAlways(ctx) << "unknown --orphan-handling mode: " << s;962 return OrphanHandlingPolicy::Place;963}964 965// Parse --build-id or --build-id=<style>. We handle "tree" as a966// synonym for "sha1" because all our hash functions including967// --build-id=sha1 are actually tree hashes for performance reasons.968static std::pair<BuildIdKind, SmallVector<uint8_t, 0>>969getBuildId(Ctx &ctx, opt::InputArgList &args) {970 auto *arg = args.getLastArg(OPT_build_id);971 if (!arg)972 return {BuildIdKind::None, {}};973 974 StringRef s = arg->getValue();975 if (s == "fast")976 return {BuildIdKind::Fast, {}};977 if (s == "md5")978 return {BuildIdKind::Md5, {}};979 if (s == "sha1" || s == "tree")980 return {BuildIdKind::Sha1, {}};981 if (s == "uuid")982 return {BuildIdKind::Uuid, {}};983 if (s.starts_with("0x"))984 return {BuildIdKind::Hexstring, parseHex(s.substr(2))};985 986 if (s != "none")987 ErrAlways(ctx) << "unknown --build-id style: " << s;988 return {BuildIdKind::None, {}};989}990 991static std::pair<bool, bool> getPackDynRelocs(Ctx &ctx,992 opt::InputArgList &args) {993 StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");994 if (s == "android")995 return {true, false};996 if (s == "relr")997 return {false, true};998 if (s == "android+relr")999 return {true, true};1000 1001 if (s != "none")1002 ErrAlways(ctx) << "unknown --pack-dyn-relocs format: " << s;1003 return {false, false};1004}1005 1006static void readCallGraph(Ctx &ctx, MemoryBufferRef mb) {1007 // Build a map from symbol name to section1008 DenseMap<StringRef, Symbol *> map;1009 for (ELFFileBase *file : ctx.objectFiles)1010 for (Symbol *sym : file->getSymbols())1011 map[sym->getName()] = sym;1012 1013 auto findSection = [&](StringRef name) -> InputSectionBase * {1014 Symbol *sym = map.lookup(name);1015 if (!sym) {1016 if (ctx.arg.warnSymbolOrdering)1017 Warn(ctx) << mb.getBufferIdentifier() << ": no such symbol: " << name;1018 return nullptr;1019 }1020 maybeWarnUnorderableSymbol(ctx, sym);1021 1022 if (Defined *dr = dyn_cast_or_null<Defined>(sym))1023 return dyn_cast_or_null<InputSectionBase>(dr->section);1024 return nullptr;1025 };1026 1027 for (StringRef line : args::getLines(mb)) {1028 SmallVector<StringRef, 3> fields;1029 line.split(fields, ' ');1030 uint64_t count;1031 1032 if (fields.size() != 3 || !to_integer(fields[2], count)) {1033 ErrAlways(ctx) << mb.getBufferIdentifier() << ": parse error";1034 return;1035 }1036 1037 if (InputSectionBase *from = findSection(fields[0]))1038 if (InputSectionBase *to = findSection(fields[1]))1039 ctx.arg.callGraphProfile[std::make_pair(from, to)] += count;1040 }1041}1042 1043// If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns1044// true and populates cgProfile and symbolIndices.1045template <class ELFT>1046static bool1047processCallGraphRelocations(Ctx &ctx, SmallVector<uint32_t, 32> &symbolIndices,1048 ArrayRef<typename ELFT::CGProfile> &cgProfile,1049 ObjFile<ELFT> *inputObj) {1050 if (inputObj->cgProfileSectionIndex == SHN_UNDEF)1051 return false;1052 1053 ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =1054 inputObj->template getELFShdrs<ELFT>();1055 symbolIndices.clear();1056 const ELFFile<ELFT> &obj = inputObj->getObj();1057 cgProfile =1058 check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(1059 objSections[inputObj->cgProfileSectionIndex]));1060 1061 for (size_t i = 0, e = objSections.size(); i < e; ++i) {1062 const Elf_Shdr_Impl<ELFT> &sec = objSections[i];1063 if (sec.sh_info == inputObj->cgProfileSectionIndex) {1064 if (sec.sh_type == SHT_CREL) {1065 auto crels =1066 CHECK(obj.crels(sec), "could not retrieve cg profile rela section");1067 for (const auto &rel : crels.first)1068 symbolIndices.push_back(rel.getSymbol(false));1069 for (const auto &rel : crels.second)1070 symbolIndices.push_back(rel.getSymbol(false));1071 break;1072 }1073 if (sec.sh_type == SHT_RELA) {1074 ArrayRef<typename ELFT::Rela> relas =1075 CHECK(obj.relas(sec), "could not retrieve cg profile rela section");1076 for (const typename ELFT::Rela &rel : relas)1077 symbolIndices.push_back(rel.getSymbol(ctx.arg.isMips64EL));1078 break;1079 }1080 if (sec.sh_type == SHT_REL) {1081 ArrayRef<typename ELFT::Rel> rels =1082 CHECK(obj.rels(sec), "could not retrieve cg profile rel section");1083 for (const typename ELFT::Rel &rel : rels)1084 symbolIndices.push_back(rel.getSymbol(ctx.arg.isMips64EL));1085 break;1086 }1087 }1088 }1089 if (symbolIndices.empty())1090 Warn(ctx)1091 << "SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't";1092 return !symbolIndices.empty();1093}1094 1095template <class ELFT> static void readCallGraphsFromObjectFiles(Ctx &ctx) {1096 SmallVector<uint32_t, 32> symbolIndices;1097 ArrayRef<typename ELFT::CGProfile> cgProfile;1098 for (auto file : ctx.objectFiles) {1099 auto *obj = cast<ObjFile<ELFT>>(file);1100 if (!processCallGraphRelocations(ctx, symbolIndices, cgProfile, obj))1101 continue;1102 1103 if (symbolIndices.size() != cgProfile.size() * 2)1104 Fatal(ctx) << "number of relocations doesn't match Weights";1105 1106 for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {1107 const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];1108 uint32_t fromIndex = symbolIndices[i * 2];1109 uint32_t toIndex = symbolIndices[i * 2 + 1];1110 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));1111 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));1112 if (!fromSym || !toSym)1113 continue;1114 1115 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);1116 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);1117 if (from && to)1118 ctx.arg.callGraphProfile[{from, to}] += cgpe.cgp_weight;1119 }1120 }1121}1122 1123template <class ELFT>1124static void ltoValidateAllVtablesHaveTypeInfos(Ctx &ctx,1125 opt::InputArgList &args) {1126 DenseSet<StringRef> typeInfoSymbols;1127 SmallSetVector<StringRef, 0> vtableSymbols;1128 auto processVtableAndTypeInfoSymbols = [&](StringRef name) {1129 if (name.consume_front("_ZTI"))1130 typeInfoSymbols.insert(name);1131 else if (name.consume_front("_ZTV"))1132 vtableSymbols.insert(name);1133 };1134 1135 // Examine all native symbol tables.1136 for (ELFFileBase *f : ctx.objectFiles) {1137 using Elf_Sym = typename ELFT::Sym;1138 for (const Elf_Sym &s : f->template getGlobalELFSyms<ELFT>()) {1139 if (s.st_shndx != SHN_UNDEF) {1140 StringRef name = check(s.getName(f->getStringTable()));1141 processVtableAndTypeInfoSymbols(name);1142 }1143 }1144 }1145 1146 for (SharedFile *f : ctx.sharedFiles) {1147 using Elf_Sym = typename ELFT::Sym;1148 for (const Elf_Sym &s : f->template getELFSyms<ELFT>()) {1149 if (s.st_shndx != SHN_UNDEF) {1150 StringRef name = check(s.getName(f->getStringTable()));1151 processVtableAndTypeInfoSymbols(name);1152 }1153 }1154 }1155 1156 SmallSetVector<StringRef, 0> vtableSymbolsWithNoRTTI;1157 for (StringRef s : vtableSymbols)1158 if (!typeInfoSymbols.count(s))1159 vtableSymbolsWithNoRTTI.insert(s);1160 1161 // Remove known safe symbols.1162 for (auto *arg : args.filtered(OPT_lto_known_safe_vtables)) {1163 StringRef knownSafeName = arg->getValue();1164 if (!knownSafeName.consume_front("_ZTV"))1165 ErrAlways(ctx)1166 << "--lto-known-safe-vtables=: expected symbol to start with _ZTV, "1167 "but got "1168 << knownSafeName;1169 Expected<GlobPattern> pat = GlobPattern::create(knownSafeName);1170 if (!pat)1171 ErrAlways(ctx) << "--lto-known-safe-vtables=: " << pat.takeError();1172 vtableSymbolsWithNoRTTI.remove_if(1173 [&](StringRef s) { return pat->match(s); });1174 }1175 1176 ctx.ltoAllVtablesHaveTypeInfos = vtableSymbolsWithNoRTTI.empty();1177 // Check for unmatched RTTI symbols1178 for (StringRef s : vtableSymbolsWithNoRTTI) {1179 Msg(ctx) << "--lto-validate-all-vtables-have-type-infos: RTTI missing for "1180 "vtable "1181 "_ZTV"1182 << s << ", --lto-whole-program-visibility disabled";1183 }1184}1185 1186static CGProfileSortKind getCGProfileSortKind(Ctx &ctx,1187 opt::InputArgList &args) {1188 StringRef s = args.getLastArgValue(OPT_call_graph_profile_sort, "cdsort");1189 if (s == "hfsort")1190 return CGProfileSortKind::Hfsort;1191 if (s == "cdsort")1192 return CGProfileSortKind::Cdsort;1193 if (s != "none")1194 ErrAlways(ctx) << "unknown --call-graph-profile-sort= value: " << s;1195 return CGProfileSortKind::None;1196}1197 1198static void parseBPOrdererOptions(Ctx &ctx, opt::InputArgList &args) {1199 if (auto *arg = args.getLastArg(OPT_bp_compression_sort)) {1200 StringRef s = arg->getValue();1201 if (s == "function") {1202 ctx.arg.bpFunctionOrderForCompression = true;1203 } else if (s == "data") {1204 ctx.arg.bpDataOrderForCompression = true;1205 } else if (s == "both") {1206 ctx.arg.bpFunctionOrderForCompression = true;1207 ctx.arg.bpDataOrderForCompression = true;1208 } else if (s != "none") {1209 ErrAlways(ctx) << arg->getSpelling()1210 << ": expected [none|function|data|both]";1211 }1212 if (s != "none" && args.hasArg(OPT_call_graph_ordering_file))1213 ErrAlways(ctx) << "--bp-compression-sort is incompatible with "1214 "--call-graph-ordering-file";1215 }1216 if (auto *arg = args.getLastArg(OPT_bp_startup_sort)) {1217 StringRef s = arg->getValue();1218 if (s == "function") {1219 ctx.arg.bpStartupFunctionSort = true;1220 } else if (s != "none") {1221 ErrAlways(ctx) << arg->getSpelling() << ": expected [none|function]";1222 }1223 if (s != "none" && args.hasArg(OPT_call_graph_ordering_file))1224 ErrAlways(ctx) << "--bp-startup-sort=function is incompatible with "1225 "--call-graph-ordering-file";1226 }1227 1228 ctx.arg.bpCompressionSortStartupFunctions =1229 args.hasFlag(OPT_bp_compression_sort_startup_functions,1230 OPT_no_bp_compression_sort_startup_functions, false);1231 ctx.arg.bpVerboseSectionOrderer = args.hasArg(OPT_verbose_bp_section_orderer);1232 1233 ctx.arg.irpgoProfilePath = args.getLastArgValue(OPT_irpgo_profile);1234 if (ctx.arg.irpgoProfilePath.empty()) {1235 if (ctx.arg.bpStartupFunctionSort)1236 ErrAlways(ctx) << "--bp-startup-sort=function must be used with "1237 "--irpgo-profile";1238 if (ctx.arg.bpCompressionSortStartupFunctions)1239 ErrAlways(ctx)1240 << "--bp-compression-sort-startup-functions must be used with "1241 "--irpgo-profile";1242 }1243}1244 1245static DebugCompressionType getCompressionType(Ctx &ctx, StringRef s,1246 StringRef option) {1247 DebugCompressionType type = StringSwitch<DebugCompressionType>(s)1248 .Case("zlib", DebugCompressionType::Zlib)1249 .Case("zstd", DebugCompressionType::Zstd)1250 .Default(DebugCompressionType::None);1251 if (type == DebugCompressionType::None) {1252 if (s != "none")1253 ErrAlways(ctx) << "unknown " << option << " value: " << s;1254 } else if (const char *reason = compression::getReasonIfUnsupported(1255 compression::formatFor(type))) {1256 ErrAlways(ctx) << option << ": " << reason;1257 }1258 return type;1259}1260 1261static StringRef getAliasSpelling(opt::Arg *arg) {1262 if (const opt::Arg *alias = arg->getAlias())1263 return alias->getSpelling();1264 return arg->getSpelling();1265}1266 1267static std::pair<StringRef, StringRef>1268getOldNewOptions(Ctx &ctx, opt::InputArgList &args, unsigned id) {1269 auto *arg = args.getLastArg(id);1270 if (!arg)1271 return {"", ""};1272 1273 StringRef s = arg->getValue();1274 std::pair<StringRef, StringRef> ret = s.split(';');1275 if (ret.second.empty())1276 ErrAlways(ctx) << getAliasSpelling(arg)1277 << " expects 'old;new' format, but got " << s;1278 return ret;1279}1280 1281// Parse options of the form "old;new[;extra]".1282static std::tuple<StringRef, StringRef, StringRef>1283getOldNewOptionsExtra(Ctx &ctx, opt::InputArgList &args, unsigned id) {1284 auto [oldDir, second] = getOldNewOptions(ctx, args, id);1285 auto [newDir, extraDir] = second.split(';');1286 return {oldDir, newDir, extraDir};1287}1288 1289// Parse the symbol ordering file and warn for any duplicate entries.1290static SmallVector<StringRef, 0> getSymbolOrderingFile(Ctx &ctx,1291 MemoryBufferRef mb) {1292 SetVector<StringRef, SmallVector<StringRef, 0>> names;1293 for (StringRef s : args::getLines(mb))1294 if (!names.insert(s) && ctx.arg.warnSymbolOrdering)1295 Warn(ctx) << mb.getBufferIdentifier()1296 << ": duplicate ordered symbol: " << s;1297 1298 return names.takeVector();1299}1300 1301static bool getIsRela(Ctx &ctx, opt::InputArgList &args) {1302 // The psABI specifies the default relocation entry format.1303 bool rela = is_contained({EM_AARCH64, EM_AMDGPU, EM_HEXAGON, EM_LOONGARCH,1304 EM_PPC, EM_PPC64, EM_RISCV, EM_S390, EM_X86_64},1305 ctx.arg.emachine);1306 // If -z rel or -z rela is specified, use the last option.1307 for (auto *arg : args.filtered(OPT_z)) {1308 StringRef s(arg->getValue());1309 if (s == "rel")1310 rela = false;1311 else if (s == "rela")1312 rela = true;1313 else1314 continue;1315 arg->claim();1316 }1317 return rela;1318}1319 1320static void parseClangOption(Ctx &ctx, StringRef opt, const Twine &msg) {1321 std::string err;1322 raw_string_ostream os(err);1323 1324 const char *argv[] = {ctx.arg.progName.data(), opt.data()};1325 if (cl::ParseCommandLineOptions(2, argv, "", &os))1326 return;1327 ErrAlways(ctx) << msg << ": " << StringRef(err).trim();1328}1329 1330// Process a remap pattern 'from-glob=to-file'.1331static bool remapInputs(Ctx &ctx, StringRef line, const Twine &location) {1332 SmallVector<StringRef, 0> fields;1333 line.split(fields, '=');1334 if (fields.size() != 2 || fields[1].empty()) {1335 ErrAlways(ctx) << location << ": parse error, not 'from-glob=to-file'";1336 return true;1337 }1338 if (!hasWildcard(fields[0]))1339 ctx.arg.remapInputs[fields[0]] = fields[1];1340 else if (Expected<GlobPattern> pat = GlobPattern::create(fields[0]))1341 ctx.arg.remapInputsWildcards.emplace_back(std::move(*pat), fields[1]);1342 else {1343 ErrAlways(ctx) << location << ": " << pat.takeError() << ": " << fields[0];1344 return true;1345 }1346 return false;1347}1348 1349// Initializes Config members by the command line options.1350static void readConfigs(Ctx &ctx, opt::InputArgList &args) {1351 ctx.e.verbose = args.hasArg(OPT_verbose);1352 ctx.e.vsDiagnostics =1353 args.hasArg(OPT_visual_studio_diagnostics_format, false);1354 1355 ctx.arg.allowMultipleDefinition =1356 hasZOption(args, "muldefs") ||1357 args.hasFlag(OPT_allow_multiple_definition,1358 OPT_no_allow_multiple_definition, false);1359 ctx.arg.androidMemtagHeap =1360 args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false);1361 ctx.arg.androidMemtagStack = args.hasFlag(OPT_android_memtag_stack,1362 OPT_no_android_memtag_stack, false);1363 ctx.arg.fatLTOObjects =1364 args.hasFlag(OPT_fat_lto_objects, OPT_no_fat_lto_objects, false);1365 ctx.arg.androidMemtagMode = getMemtagMode(ctx, args);1366 ctx.arg.auxiliaryList = args::getStrings(args, OPT_auxiliary);1367 ctx.arg.armBe8 = args.hasArg(OPT_be8);1368 if (opt::Arg *arg = args.getLastArg(1369 OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,1370 OPT_Bsymbolic_functions, OPT_Bsymbolic_non_weak, OPT_Bsymbolic)) {1371 if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))1372 ctx.arg.bsymbolic = BsymbolicKind::NonWeakFunctions;1373 else if (arg->getOption().matches(OPT_Bsymbolic_functions))1374 ctx.arg.bsymbolic = BsymbolicKind::Functions;1375 else if (arg->getOption().matches(OPT_Bsymbolic_non_weak))1376 ctx.arg.bsymbolic = BsymbolicKind::NonWeak;1377 else if (arg->getOption().matches(OPT_Bsymbolic))1378 ctx.arg.bsymbolic = BsymbolicKind::All;1379 }1380 ctx.arg.callGraphProfileSort = getCGProfileSortKind(ctx, args);1381 parseBPOrdererOptions(ctx, args);1382 ctx.arg.checkSections =1383 args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);1384 ctx.arg.chroot = args.getLastArgValue(OPT_chroot);1385 if (auto *arg = args.getLastArg(OPT_compress_debug_sections)) {1386 ctx.arg.compressDebugSections =1387 getCompressionType(ctx, arg->getValue(), "--compress-debug-sections");1388 }1389 ctx.arg.cref = args.hasArg(OPT_cref);1390 ctx.arg.optimizeBBJumps =1391 args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);1392 ctx.arg.debugNames = args.hasFlag(OPT_debug_names, OPT_no_debug_names, false);1393 ctx.arg.demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);1394 ctx.arg.dependencyFile = args.getLastArgValue(OPT_dependency_file);1395 ctx.arg.dependentLibraries =1396 args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);1397 ctx.arg.disableVerify = args.hasArg(OPT_disable_verify);1398 ctx.arg.discard = getDiscard(args);1399 ctx.arg.dtltoDistributor = args.getLastArgValue(OPT_thinlto_distributor_eq);1400 ctx.arg.dtltoDistributorArgs =1401 args::getStrings(args, OPT_thinlto_distributor_arg);1402 ctx.arg.dtltoCompiler = args.getLastArgValue(OPT_thinlto_remote_compiler_eq);1403 ctx.arg.dtltoCompilerPrependArgs =1404 args::getStrings(args, OPT_thinlto_remote_compiler_prepend_arg);1405 ctx.arg.dtltoCompilerArgs =1406 args::getStrings(args, OPT_thinlto_remote_compiler_arg);1407 ctx.arg.dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);1408 ctx.arg.dynamicLinker = getDynamicLinker(ctx, args);1409 ctx.arg.ehFrameHdr =1410 args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);1411 ctx.arg.emitLLVM = args.hasArg(OPT_lto_emit_llvm);1412 ctx.arg.emitRelocs = args.hasArg(OPT_emit_relocs);1413 ctx.arg.enableNewDtags =1414 args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);1415 ctx.arg.enableNonContiguousRegions =1416 args.hasArg(OPT_enable_non_contiguous_regions);1417 ctx.arg.entry = args.getLastArgValue(OPT_entry);1418 1419 ctx.e.errorHandlingScript = args.getLastArgValue(OPT_error_handling_script);1420 1421 ctx.arg.executeOnly =1422 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);1423 ctx.arg.exportDynamic =1424 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) ||1425 args.hasArg(OPT_shared);1426 ctx.arg.filterList = args::getStrings(args, OPT_filter);1427 ctx.arg.fini = args.getLastArgValue(OPT_fini, "_fini");1428 ctx.arg.fixCortexA53Errata843419 =1429 args.hasArg(OPT_fix_cortex_a53_843419) && !args.hasArg(OPT_relocatable);1430 ctx.arg.cmseImplib = args.hasArg(OPT_cmse_implib);1431 ctx.arg.cmseInputLib = args.getLastArgValue(OPT_in_implib);1432 ctx.arg.cmseOutputLib = args.getLastArgValue(OPT_out_implib);1433 ctx.arg.fixCortexA8 =1434 args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);1435 ctx.arg.fortranCommon =1436 args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false);1437 ctx.arg.gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);1438 ctx.arg.gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);1439 ctx.arg.gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);1440 ctx.arg.icf = getICF(args);1441 ctx.arg.ignoreDataAddressEquality =1442 args.hasArg(OPT_ignore_data_address_equality);1443 ctx.arg.ignoreFunctionAddressEquality =1444 args.hasArg(OPT_ignore_function_address_equality);1445 ctx.arg.init = args.getLastArgValue(OPT_init, "_init");1446 ctx.arg.ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);1447 ctx.arg.ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);1448 ctx.arg.ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);1449 ctx.arg.ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,1450 OPT_no_lto_pgo_warn_mismatch, true);1451 ctx.arg.ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);1452 ctx.arg.ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);1453 ctx.arg.ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);1454 ctx.arg.ltoWholeProgramVisibility =1455 args.hasFlag(OPT_lto_whole_program_visibility,1456 OPT_no_lto_whole_program_visibility, false);1457 ctx.arg.ltoValidateAllVtablesHaveTypeInfos =1458 args.hasFlag(OPT_lto_validate_all_vtables_have_type_infos,1459 OPT_no_lto_validate_all_vtables_have_type_infos, false);1460 ctx.arg.ltoo = args::getInteger(args, OPT_lto_O, 2);1461 if (ctx.arg.ltoo > 3)1462 ErrAlways(ctx) << "invalid optimization level for LTO: " << ctx.arg.ltoo;1463 unsigned ltoCgo =1464 args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(ctx.arg.ltoo));1465 if (auto level = CodeGenOpt::getLevel(ltoCgo))1466 ctx.arg.ltoCgo = *level;1467 else1468 ErrAlways(ctx) << "invalid codegen optimization level for LTO: " << ltoCgo;1469 ctx.arg.ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);1470 ctx.arg.ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);1471 ctx.arg.ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);1472 ctx.arg.ltoBBAddrMap =1473 args.hasFlag(OPT_lto_basic_block_address_map,1474 OPT_no_lto_basic_block_address_map, false);1475 ctx.arg.ltoBasicBlockSections =1476 args.getLastArgValue(OPT_lto_basic_block_sections);1477 ctx.arg.ltoUniqueBasicBlockSectionNames =1478 args.hasFlag(OPT_lto_unique_basic_block_section_names,1479 OPT_no_lto_unique_basic_block_section_names, false);1480 ctx.arg.mapFile = args.getLastArgValue(OPT_Map);1481 ctx.arg.mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);1482 ctx.arg.mergeArmExidx =1483 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);1484 ctx.arg.mmapOutputFile =1485 args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, false);1486 ctx.arg.nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);1487 ctx.arg.noinhibitExec = args.hasArg(OPT_noinhibit_exec);1488 ctx.arg.nostdlib = args.hasArg(OPT_nostdlib);1489 ctx.arg.oFormatBinary = isOutputFormatBinary(ctx, args);1490 ctx.arg.omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);1491 ctx.arg.optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);1492 ctx.arg.optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file);1493 1494 // Parse remarks hotness threshold. Valid value is either integer or 'auto'.1495 if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {1496 auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());1497 if (!resultOrErr)1498 ErrAlways(ctx) << arg->getSpelling() << ": invalid argument '"1499 << arg->getValue()1500 << "', only integer or 'auto' is supported";1501 else1502 ctx.arg.optRemarksHotnessThreshold = *resultOrErr;1503 }1504 1505 ctx.arg.optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);1506 ctx.arg.optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);1507 ctx.arg.optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);1508 ctx.arg.optimize = args::getInteger(args, OPT_O, 1);1509 ctx.arg.orphanHandling = getOrphanHandling(ctx, args);1510 ctx.arg.outputFile = args.getLastArgValue(OPT_o);1511 if (auto *arg = args.getLastArg(OPT_package_metadata))1512 parsePackageMetadata(ctx, *arg);1513 ctx.arg.pie = args.hasFlag(OPT_pie, OPT_no_pie, false);1514 ctx.arg.printIcfSections =1515 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);1516 if (auto *arg =1517 args.getLastArg(OPT_print_gc_sections, OPT_no_print_gc_sections,1518 OPT_print_gc_sections_eq)) {1519 if (arg->getOption().matches(OPT_print_gc_sections))1520 ctx.arg.printGcSections = "-";1521 else if (arg->getOption().matches(OPT_print_gc_sections_eq))1522 ctx.arg.printGcSections = arg->getValue();1523 }1524 ctx.arg.printMemoryUsage = args.hasArg(OPT_print_memory_usage);1525 ctx.arg.printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);1526 ctx.arg.printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order);1527 ctx.arg.rejectMismatch = !args.hasArg(OPT_no_warn_mismatch);1528 ctx.arg.relax = args.hasFlag(OPT_relax, OPT_no_relax, true);1529 ctx.arg.relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false);1530 ctx.arg.rpath = getRpath(args);1531 ctx.arg.relocatable = args.hasArg(OPT_relocatable);1532 ctx.arg.resolveGroups =1533 !args.hasArg(OPT_relocatable) || args.hasArg(OPT_force_group_allocation);1534 1535 if (args.hasArg(OPT_save_temps)) {1536 // --save-temps implies saving all temps.1537 ctx.arg.saveTempsArgs.insert_range(saveTempsValues);1538 } else {1539 for (auto *arg : args.filtered(OPT_save_temps_eq)) {1540 StringRef s = arg->getValue();1541 if (llvm::is_contained(saveTempsValues, s))1542 ctx.arg.saveTempsArgs.insert(s);1543 else1544 ErrAlways(ctx) << "unknown --save-temps value: " << s;1545 }1546 }1547 1548 ctx.arg.searchPaths = args::getStrings(args, OPT_library_path);1549 ctx.arg.sectionStartMap = getSectionStartMap(ctx, args);1550 ctx.arg.shared = args.hasArg(OPT_shared);1551 if (args.hasArg(OPT_randomize_section_padding))1552 ctx.arg.randomizeSectionPadding =1553 args::getInteger(args, OPT_randomize_section_padding, 0);1554 ctx.arg.singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);1555 ctx.arg.singleXoRx = !args.hasFlag(OPT_xosegment, OPT_no_xosegment, false);1556 ctx.arg.soName = args.getLastArgValue(OPT_soname);1557 ctx.arg.sortSection = getSortSection(ctx, args);1558 ctx.arg.splitStackAdjustSize =1559 args::getInteger(args, OPT_split_stack_adjust_size, 16384);1560 ctx.arg.zSectionHeader =1561 getZFlag(args, "sectionheader", "nosectionheader", true);1562 ctx.arg.strip = getStrip(ctx, args); // needs zSectionHeader1563 ctx.arg.sysroot = args.getLastArgValue(OPT_sysroot);1564 ctx.arg.target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);1565 ctx.arg.target2 = getTarget2(ctx, args);1566 ctx.arg.thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);1567 ctx.arg.thinLTOCachePolicy = CHECK(1568 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),1569 "--thinlto-cache-policy: invalid cache policy");1570 ctx.arg.thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);1571 ctx.arg.thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||1572 args.hasArg(OPT_thinlto_index_only) ||1573 args.hasArg(OPT_thinlto_index_only_eq);1574 ctx.arg.thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||1575 args.hasArg(OPT_thinlto_index_only_eq);1576 ctx.arg.thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);1577 ctx.arg.thinLTOObjectSuffixReplace =1578 getOldNewOptions(ctx, args, OPT_thinlto_object_suffix_replace_eq);1579 std::tie(ctx.arg.thinLTOPrefixReplaceOld, ctx.arg.thinLTOPrefixReplaceNew,1580 ctx.arg.thinLTOPrefixReplaceNativeObject) =1581 getOldNewOptionsExtra(ctx, args, OPT_thinlto_prefix_replace_eq);1582 if (ctx.arg.thinLTOEmitIndexFiles && !ctx.arg.thinLTOIndexOnly) {1583 if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))1584 ErrAlways(ctx) << "--thinlto-object-suffix-replace is not supported with "1585 "--thinlto-emit-index-files";1586 else if (args.hasArg(OPT_thinlto_prefix_replace_eq))1587 ErrAlways(ctx) << "--thinlto-prefix-replace is not supported with "1588 "--thinlto-emit-index-files";1589 }1590 if (!ctx.arg.thinLTOPrefixReplaceNativeObject.empty() &&1591 ctx.arg.thinLTOIndexOnlyArg.empty()) {1592 ErrAlways(ctx)1593 << "--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "1594 "--thinlto-index-only=";1595 }1596 ctx.arg.thinLTOModulesToCompile =1597 args::getStrings(args, OPT_thinlto_single_module_eq);1598 ctx.arg.timeTraceEnabled =1599 args.hasArg(OPT_time_trace_eq) && !ctx.e.disableOutput;1600 ctx.arg.timeTraceGranularity =1601 args::getInteger(args, OPT_time_trace_granularity, 500);1602 ctx.arg.trace = args.hasArg(OPT_trace);1603 ctx.arg.undefined = args::getStrings(args, OPT_undefined);1604 ctx.arg.undefinedVersion =1605 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false);1606 ctx.arg.unique = args.hasArg(OPT_unique);1607 ctx.arg.useAndroidRelrTags = args.hasFlag(1608 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);1609 ctx.arg.warnBackrefs =1610 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);1611 ctx.arg.warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);1612 ctx.arg.warnSymbolOrdering =1613 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);1614 ctx.arg.whyExtract = args.getLastArgValue(OPT_why_extract);1615 for (opt::Arg *arg : args.filtered(OPT_why_live)) {1616 StringRef value(arg->getValue());1617 if (Expected<GlobPattern> pat = GlobPattern::create(arg->getValue())) {1618 ctx.arg.whyLive.emplace_back(std::move(*pat));1619 } else {1620 ErrAlways(ctx) << arg->getSpelling() << ": " << pat.takeError();1621 continue;1622 }1623 }1624 ctx.arg.zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);1625 ctx.arg.zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);1626 ctx.arg.zForceBti = hasZOption(args, "force-bti");1627 ctx.arg.zForceIbt = hasZOption(args, "force-ibt");1628 ctx.arg.zZicfilp = getZZicfilp(ctx, args);1629 ctx.arg.zZicfiss = getZZicfiss(ctx, args);1630 ctx.arg.zGcs = getZGcs(ctx, args);1631 ctx.arg.zGlobal = hasZOption(args, "global");1632 ctx.arg.zGnustack = getZGnuStack(args);1633 ctx.arg.zHazardplt = hasZOption(args, "hazardplt");1634 ctx.arg.zIfuncNoplt = hasZOption(args, "ifunc-noplt");1635 ctx.arg.zInitfirst = hasZOption(args, "initfirst");1636 ctx.arg.zInterpose = hasZOption(args, "interpose");1637 ctx.arg.zKeepDataSectionPrefix = getZFlag(1638 args, "keep-data-section-prefix", "nokeep-data-section-prefix", false);1639 ctx.arg.zKeepTextSectionPrefix = getZFlag(1640 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);1641 ctx.arg.zLrodataAfterBss =1642 getZFlag(args, "lrodata-after-bss", "nolrodata-after-bss", false);1643 ctx.arg.zNoBtCfi = hasZOption(args, "nobtcfi");1644 ctx.arg.zNodefaultlib = hasZOption(args, "nodefaultlib");1645 ctx.arg.zNodelete = hasZOption(args, "nodelete");1646 ctx.arg.zNodlopen = hasZOption(args, "nodlopen");1647 ctx.arg.zNow = getZFlag(args, "now", "lazy", false);1648 ctx.arg.zOrigin = hasZOption(args, "origin");1649 ctx.arg.zPacPlt = getZFlag(args, "pac-plt", "nopac-plt", false);1650 ctx.arg.zRelro = getZFlag(args, "relro", "norelro", true);1651 ctx.arg.zRetpolineplt = hasZOption(args, "retpolineplt");1652 ctx.arg.zRodynamic = hasZOption(args, "rodynamic");1653 ctx.arg.zSeparate = getZSeparate(args);1654 ctx.arg.zShstk = hasZOption(args, "shstk");1655 ctx.arg.zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);1656 ctx.arg.zStartStopGC =1657 getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);1658 ctx.arg.zStartStopVisibility = getZStartStopVisibility(ctx, args);1659 ctx.arg.zText = getZFlag(args, "text", "notext", true);1660 ctx.arg.zWxneeded = hasZOption(args, "wxneeded");1661 setUnresolvedSymbolPolicy(ctx, args);1662 ctx.arg.power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";1663 ctx.arg.branchToBranch = args.hasFlag(1664 OPT_branch_to_branch, OPT_no_branch_to_branch, ctx.arg.optimize >= 2);1665 1666 if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {1667 if (arg->getOption().matches(OPT_eb))1668 ctx.arg.optEB = true;1669 else1670 ctx.arg.optEL = true;1671 }1672 1673 for (opt::Arg *arg : args.filtered(OPT_remap_inputs)) {1674 StringRef value(arg->getValue());1675 remapInputs(ctx, value, arg->getSpelling());1676 }1677 for (opt::Arg *arg : args.filtered(OPT_remap_inputs_file)) {1678 StringRef filename(arg->getValue());1679 std::optional<MemoryBufferRef> buffer = readFile(ctx, filename);1680 if (!buffer)1681 continue;1682 // Parse 'from-glob=to-file' lines, ignoring #-led comments.1683 for (auto [lineno, line] : llvm::enumerate(args::getLines(*buffer)))1684 if (remapInputs(ctx, line, filename + ":" + Twine(lineno + 1)))1685 break;1686 }1687 1688 for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {1689 constexpr StringRef errPrefix = "--shuffle-sections=: ";1690 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');1691 if (kv.first.empty() || kv.second.empty()) {1692 ErrAlways(ctx) << errPrefix << "expected <section_glob>=<seed>, but got '"1693 << arg->getValue() << "'";1694 continue;1695 }1696 // Signed so that <section_glob>=-1 is allowed.1697 int64_t v;1698 if (!to_integer(kv.second, v))1699 ErrAlways(ctx) << errPrefix << "expected an integer, but got '"1700 << kv.second << "'";1701 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))1702 ctx.arg.shuffleSections.emplace_back(std::move(*pat), uint32_t(v));1703 else1704 ErrAlways(ctx) << errPrefix << pat.takeError() << ": " << kv.first;1705 }1706 1707 auto reports = {1708 std::make_pair("bti-report", &ctx.arg.zBtiReport),1709 std::make_pair("cet-report", &ctx.arg.zCetReport),1710 std::make_pair("execute-only-report", &ctx.arg.zExecuteOnlyReport),1711 std::make_pair("gcs-report", &ctx.arg.zGcsReport),1712 std::make_pair("gcs-report-dynamic", &ctx.arg.zGcsReportDynamic),1713 std::make_pair("pauth-report", &ctx.arg.zPauthReport),1714 std::make_pair("zicfilp-unlabeled-report",1715 &ctx.arg.zZicfilpUnlabeledReport),1716 std::make_pair("zicfilp-func-sig-report", &ctx.arg.zZicfilpFuncSigReport),1717 std::make_pair("zicfiss-report", &ctx.arg.zZicfissReport)};1718 bool hasGcsReportDynamic = false;1719 for (opt::Arg *arg : args.filtered(OPT_z)) {1720 std::pair<StringRef, StringRef> option =1721 StringRef(arg->getValue()).split('=');1722 for (auto reportArg : reports) {1723 if (option.first != reportArg.first)1724 continue;1725 arg->claim();1726 if (option.second == "none")1727 *reportArg.second = ReportPolicy::None;1728 else if (option.second == "warning")1729 *reportArg.second = ReportPolicy::Warning;1730 else if (option.second == "error")1731 *reportArg.second = ReportPolicy::Error;1732 else {1733 ErrAlways(ctx) << "unknown -z " << reportArg.first1734 << "= value: " << option.second;1735 continue;1736 }1737 hasGcsReportDynamic |= option.first == "gcs-report-dynamic";1738 }1739 }1740 1741 // When -zgcs-report-dynamic is unspecified, it inherits -zgcs-report1742 // but is capped at warning to avoid needing to rebuild the shared library1743 // with GCS enabled.1744 if (!hasGcsReportDynamic && ctx.arg.zGcsReport != ReportPolicy::None)1745 ctx.arg.zGcsReportDynamic = ReportPolicy::Warning;1746 1747 for (opt::Arg *arg : args.filtered(OPT_compress_sections)) {1748 SmallVector<StringRef, 0> fields;1749 StringRef(arg->getValue()).split(fields, '=');1750 if (fields.size() != 2 || fields[1].empty()) {1751 ErrAlways(ctx) << arg->getSpelling()1752 << ": parse error, not 'section-glob=[none|zlib|zstd]'";1753 continue;1754 }1755 auto [typeStr, levelStr] = fields[1].split(':');1756 auto type = getCompressionType(ctx, typeStr, arg->getSpelling());1757 unsigned level = 0;1758 if (fields[1].size() != typeStr.size() &&1759 !llvm::to_integer(levelStr, level)) {1760 ErrAlways(ctx)1761 << arg->getSpelling()1762 << ": expected a non-negative integer compression level, but got '"1763 << levelStr << "'";1764 }1765 if (Expected<GlobPattern> pat = GlobPattern::create(fields[0])) {1766 ctx.arg.compressSections.emplace_back(std::move(*pat), type, level);1767 } else {1768 ErrAlways(ctx) << arg->getSpelling() << ": " << pat.takeError();1769 continue;1770 }1771 }1772 1773 for (opt::Arg *arg : args.filtered(OPT_z)) {1774 std::pair<StringRef, StringRef> option =1775 StringRef(arg->getValue()).split('=');1776 if (option.first != "dead-reloc-in-nonalloc")1777 continue;1778 arg->claim();1779 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";1780 std::pair<StringRef, StringRef> kv = option.second.split('=');1781 if (kv.first.empty() || kv.second.empty()) {1782 ErrAlways(ctx) << errPrefix << "expected <section_glob>=<value>";1783 continue;1784 }1785 uint64_t v;1786 if (!to_integer(kv.second, v))1787 ErrAlways(ctx) << errPrefix1788 << "expected a non-negative integer, but got '"1789 << kv.second << "'";1790 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))1791 ctx.arg.deadRelocInNonAlloc.emplace_back(std::move(*pat), v);1792 else1793 ErrAlways(ctx) << errPrefix << pat.takeError() << ": " << kv.first;1794 }1795 1796 cl::ResetAllOptionOccurrences();1797 1798 // Parse LTO options.1799 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))1800 parseClangOption(ctx, ctx.saver.save("-mcpu=" + StringRef(arg->getValue())),1801 arg->getSpelling());1802 1803 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))1804 parseClangOption(ctx, std::string("-") + arg->getValue(),1805 arg->getSpelling());1806 1807 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or1808 // relative path. Just ignore. If not ended with "lto-wrapper" (or1809 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an1810 // unsupported LLVMgold.so option and error.1811 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) {1812 StringRef v(arg->getValue());1813 if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe"))1814 ErrAlways(ctx) << arg->getSpelling() << ": unknown plugin option '"1815 << arg->getValue() << "'";1816 }1817 1818 ctx.arg.passPlugins = args::getStrings(args, OPT_load_pass_plugins);1819 1820 // Parse -mllvm options.1821 for (const auto *arg : args.filtered(OPT_mllvm)) {1822 parseClangOption(ctx, arg->getValue(), arg->getSpelling());1823 ctx.arg.mllvmOpts.emplace_back(arg->getValue());1824 }1825 1826 ctx.arg.ltoKind = LtoKind::Default;1827 if (auto *arg = args.getLastArg(OPT_lto)) {1828 StringRef s = arg->getValue();1829 if (s == "thin")1830 ctx.arg.ltoKind = LtoKind::UnifiedThin;1831 else if (s == "full")1832 ctx.arg.ltoKind = LtoKind::UnifiedRegular;1833 else if (s == "default")1834 ctx.arg.ltoKind = LtoKind::Default;1835 else1836 ErrAlways(ctx) << "unknown LTO mode: " << s;1837 }1838 1839 // --threads= takes a positive integer and provides the default value for1840 // --thinlto-jobs=. If unspecified, cap the number of threads since1841 // overhead outweighs optimization for used parallel algorithms for the1842 // non-LTO parts.1843 if (auto *arg = args.getLastArg(OPT_threads)) {1844 StringRef v(arg->getValue());1845 unsigned threads = 0;1846 if (!llvm::to_integer(v, threads, 0) || threads == 0)1847 ErrAlways(ctx) << arg->getSpelling()1848 << ": expected a positive integer, but got '"1849 << arg->getValue() << "'";1850 parallel::strategy = hardware_concurrency(threads);1851 ctx.arg.thinLTOJobs = v;1852 } else if (parallel::strategy.compute_thread_count() > 16) {1853 Log(ctx) << "set maximum concurrency to 16, specify --threads= to change";1854 parallel::strategy = hardware_concurrency(16);1855 }1856 if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))1857 ctx.arg.thinLTOJobs = arg->getValue();1858 ctx.arg.threadCount = parallel::strategy.compute_thread_count();1859 1860 if (ctx.arg.ltoPartitions == 0)1861 ErrAlways(ctx) << "--lto-partitions: number of threads must be > 0";1862 if (!get_threadpool_strategy(ctx.arg.thinLTOJobs))1863 ErrAlways(ctx) << "--thinlto-jobs: invalid job count: "1864 << ctx.arg.thinLTOJobs;1865 1866 if (ctx.arg.splitStackAdjustSize < 0)1867 ErrAlways(ctx) << "--split-stack-adjust-size: size must be >= 0";1868 1869 // The text segment is traditionally the first segment, whose address equals1870 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment1871 // is an old-fashioned option that does not play well with lld's layout.1872 // Suggest --image-base as a likely alternative.1873 if (args.hasArg(OPT_Ttext_segment))1874 ErrAlways(ctx)1875 << "-Ttext-segment is not supported. Use --image-base if you "1876 "intend to set the base address";1877 1878 // Parse ELF{32,64}{LE,BE} and CPU type.1879 if (auto *arg = args.getLastArg(OPT_m)) {1880 StringRef s = arg->getValue();1881 std::tie(ctx.arg.ekind, ctx.arg.emachine, ctx.arg.osabi) =1882 parseEmulation(ctx, s);1883 ctx.arg.mipsN32Abi =1884 (s.starts_with("elf32btsmipn32") || s.starts_with("elf32ltsmipn32"));1885 ctx.arg.emulation = s;1886 }1887 1888 // Parse --hash-style={sysv,gnu,both}.1889 if (auto *arg = args.getLastArg(OPT_hash_style)) {1890 StringRef s = arg->getValue();1891 if (s == "sysv")1892 ctx.arg.sysvHash = true;1893 else if (s == "gnu")1894 ctx.arg.gnuHash = true;1895 else if (s == "both")1896 ctx.arg.sysvHash = ctx.arg.gnuHash = true;1897 else1898 ErrAlways(ctx) << "unknown --hash-style: " << s;1899 }1900 1901 if (args.hasArg(OPT_print_map))1902 ctx.arg.mapFile = "-";1903 1904 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).1905 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled1906 // it. Also disable RELRO for -r.1907 if (ctx.arg.nmagic || ctx.arg.omagic || ctx.arg.relocatable)1908 ctx.arg.zRelro = false;1909 1910 std::tie(ctx.arg.buildId, ctx.arg.buildIdVector) = getBuildId(ctx, args);1911 1912 if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) {1913 ctx.arg.relrGlibc = true;1914 ctx.arg.relrPackDynRelocs = true;1915 } else {1916 std::tie(ctx.arg.androidPackDynRelocs, ctx.arg.relrPackDynRelocs) =1917 getPackDynRelocs(ctx, args);1918 }1919 1920 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){1921 if (args.hasArg(OPT_call_graph_ordering_file))1922 ErrAlways(ctx) << "--symbol-ordering-file and --call-graph-order-file "1923 "may not be used together";1924 if (auto buffer = readFile(ctx, arg->getValue()))1925 ctx.arg.symbolOrderingFile = getSymbolOrderingFile(ctx, *buffer);1926 }1927 1928 assert(ctx.arg.versionDefinitions.empty());1929 ctx.arg.versionDefinitions.push_back(1930 {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});1931 ctx.arg.versionDefinitions.push_back(1932 {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});1933 1934 // If --retain-symbol-file is used, we'll keep only the symbols listed in1935 // the file and discard all others.1936 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {1937 ctx.arg.versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(1938 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});1939 if (std::optional<MemoryBufferRef> buffer = readFile(ctx, arg->getValue()))1940 for (StringRef s : args::getLines(*buffer))1941 ctx.arg.versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(1942 {s, /*isExternCpp=*/false, /*hasWildcard=*/false});1943 }1944 1945 for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {1946 StringRef pattern(arg->getValue());1947 if (Expected<GlobPattern> pat = GlobPattern::create(pattern))1948 ctx.arg.warnBackrefsExclude.push_back(std::move(*pat));1949 else1950 ErrAlways(ctx) << arg->getSpelling() << ": " << pat.takeError() << ": "1951 << pattern;1952 }1953 1954 // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols1955 // which should be exported. For -shared, references to matched non-local1956 // STV_DEFAULT symbols are not bound to definitions within the shared object,1957 // even if other options express a symbolic intention: -Bsymbolic,1958 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.1959 for (auto *arg : args.filtered(OPT_export_dynamic_symbol))1960 ctx.arg.dynamicList.push_back(1961 {arg->getValue(), /*isExternCpp=*/false,1962 /*hasWildcard=*/hasWildcard(arg->getValue())});1963 1964 // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol1965 // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic1966 // like semantics.1967 ctx.arg.symbolic =1968 ctx.arg.bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);1969 for (auto *arg :1970 args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))1971 if (std::optional<MemoryBufferRef> buffer = readFile(ctx, arg->getValue()))1972 readDynamicList(ctx, *buffer);1973 1974 for (auto *arg : args.filtered(OPT_version_script))1975 if (std::optional<std::string> path = searchScript(ctx, arg->getValue())) {1976 if (std::optional<MemoryBufferRef> buffer = readFile(ctx, *path))1977 readVersionScript(ctx, *buffer);1978 } else {1979 ErrAlways(ctx) << "cannot find version script " << arg->getValue();1980 }1981}1982 1983// Some Config members do not directly correspond to any particular1984// command line options, but computed based on other Config values.1985// This function initialize such members. See Config.h for the details1986// of these values.1987static void setConfigs(Ctx &ctx, opt::InputArgList &args) {1988 ELFKind k = ctx.arg.ekind;1989 uint16_t m = ctx.arg.emachine;1990 1991 ctx.arg.copyRelocs = (ctx.arg.relocatable || ctx.arg.emitRelocs);1992 ctx.arg.is64 = (k == ELF64LEKind || k == ELF64BEKind);1993 ctx.arg.isLE = (k == ELF32LEKind || k == ELF64LEKind);1994 ctx.arg.endianness = ctx.arg.isLE ? endianness::little : endianness::big;1995 ctx.arg.isMips64EL = (k == ELF64LEKind && m == EM_MIPS);1996 ctx.arg.isPic = ctx.arg.pie || ctx.arg.shared;1997 ctx.arg.picThunk = args.hasArg(OPT_pic_veneer, ctx.arg.isPic);1998 ctx.arg.wordsize = ctx.arg.is64 ? 8 : 4;1999 2000 // ELF defines two different ways to store relocation addends as shown below:2001 //2002 // Rel: Addends are stored to the location where relocations are applied. It2003 // cannot pack the full range of addend values for all relocation types, but2004 // this only affects relocation types that we don't support emitting as2005 // dynamic relocations (see getDynRel).2006 // Rela: Addends are stored as part of relocation entry.2007 //2008 // In other words, Rela makes it easy to read addends at the price of extra2009 // 4 or 8 byte for each relocation entry.2010 //2011 // We pick the format for dynamic relocations according to the psABI for each2012 // processor, but a contrary choice can be made if the dynamic loader2013 // supports.2014 ctx.arg.isRela = getIsRela(ctx, args);2015 2016 // If the output uses REL relocations we must store the dynamic relocation2017 // addends to the output sections. We also store addends for RELA relocations2018 // if --apply-dynamic-relocs is used.2019 // We default to not writing the addends when using RELA relocations since2020 // any standard conforming tool can find it in r_addend.2021 ctx.arg.writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,2022 OPT_no_apply_dynamic_relocs, false) ||2023 !ctx.arg.isRela;2024 // Validation of dynamic relocation addends is on by default for assertions2025 // builds and disabled otherwise. This check is enabled when writeAddends is2026 // true.2027#ifndef NDEBUG2028 bool checkDynamicRelocsDefault = true;2029#else2030 bool checkDynamicRelocsDefault = false;2031#endif2032 ctx.arg.checkDynamicRelocs =2033 args.hasFlag(OPT_check_dynamic_relocations,2034 OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);2035 ctx.arg.tocOptimize =2036 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);2037 ctx.arg.pcRelOptimize =2038 args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);2039 2040 if (!args.hasArg(OPT_hash_style)) {2041 if (ctx.arg.emachine == EM_MIPS)2042 ctx.arg.sysvHash = true;2043 else2044 ctx.arg.sysvHash = ctx.arg.gnuHash = true;2045 }2046 2047 // Set default entry point and output file if not specified by command line or2048 // linker scripts.2049 ctx.arg.warnMissingEntry =2050 (!ctx.arg.entry.empty() || (!ctx.arg.shared && !ctx.arg.relocatable));2051 if (ctx.arg.entry.empty() && !ctx.arg.relocatable)2052 ctx.arg.entry = ctx.arg.emachine == EM_MIPS ? "__start" : "_start";2053 if (ctx.arg.outputFile.empty())2054 ctx.arg.outputFile = "a.out";2055 2056 // Fail early if the output file or map file is not writable. If a user has a2057 // long link, e.g. due to a large LTO link, they do not wish to run it and2058 // find that it failed because there was a mistake in their command-line.2059 {2060 llvm::TimeTraceScope timeScope("Create output files");2061 if (auto e = tryCreateFile(ctx.arg.outputFile))2062 ErrAlways(ctx) << "cannot open output file " << ctx.arg.outputFile << ": "2063 << e.message();2064 if (auto e = tryCreateFile(ctx.arg.mapFile))2065 ErrAlways(ctx) << "cannot open map file " << ctx.arg.mapFile << ": "2066 << e.message();2067 if (auto e = tryCreateFile(ctx.arg.whyExtract))2068 ErrAlways(ctx) << "cannot open --why-extract= file " << ctx.arg.whyExtract2069 << ": " << e.message();2070 }2071}2072 2073static bool isFormatBinary(Ctx &ctx, StringRef s) {2074 if (s == "binary")2075 return true;2076 if (s == "elf" || s == "default")2077 return false;2078 ErrAlways(ctx) << "unknown --format value: " << s2079 << " (supported formats: elf, default, binary)";2080 return false;2081}2082 2083void LinkerDriver::createFiles(opt::InputArgList &args) {2084 llvm::TimeTraceScope timeScope("Load input files");2085 // For --{push,pop}-state.2086 std::vector<std::tuple<bool, bool, bool>> stack;2087 2088 // -r implies -Bstatic and has precedence over -Bdynamic.2089 ctx.arg.isStatic = ctx.arg.relocatable;2090 2091 // Iterate over argv to process input files and positional arguments.2092 std::optional<MemoryBufferRef> defaultScript;2093 nextGroupId = 0;2094 isInGroup = false;2095 bool hasInput = false, hasScript = false;2096 for (auto *arg : args) {2097 switch (arg->getOption().getID()) {2098 case OPT_library:2099 addLibrary(arg->getValue());2100 hasInput = true;2101 break;2102 case OPT_INPUT:2103 addFile(arg->getValue(), /*withLOption=*/false);2104 hasInput = true;2105 break;2106 case OPT_defsym: {2107 readDefsym(ctx, MemoryBufferRef(arg->getValue(), "--defsym"));2108 break;2109 }2110 case OPT_script:2111 case OPT_default_script:2112 if (std::optional<std::string> path =2113 searchScript(ctx, arg->getValue())) {2114 if (std::optional<MemoryBufferRef> mb = readFile(ctx, *path)) {2115 if (arg->getOption().matches(OPT_default_script)) {2116 defaultScript = mb;2117 } else {2118 readLinkerScript(ctx, *mb);2119 hasScript = true;2120 }2121 }2122 break;2123 }2124 ErrAlways(ctx) << "cannot find linker script " << arg->getValue();2125 break;2126 case OPT_as_needed:2127 ctx.arg.asNeeded = true;2128 break;2129 case OPT_format:2130 ctx.arg.formatBinary = isFormatBinary(ctx, arg->getValue());2131 break;2132 case OPT_no_as_needed:2133 ctx.arg.asNeeded = false;2134 break;2135 case OPT_Bstatic:2136 case OPT_omagic:2137 case OPT_nmagic:2138 ctx.arg.isStatic = true;2139 break;2140 case OPT_Bdynamic:2141 if (!ctx.arg.relocatable)2142 ctx.arg.isStatic = false;2143 break;2144 case OPT_whole_archive:2145 inWholeArchive = true;2146 break;2147 case OPT_no_whole_archive:2148 inWholeArchive = false;2149 break;2150 case OPT_just_symbols:2151 if (std::optional<MemoryBufferRef> mb = readFile(ctx, arg->getValue())) {2152 files.push_back(createObjFile(ctx, *mb));2153 files.back()->justSymbols = true;2154 }2155 break;2156 case OPT_in_implib:2157 if (armCmseImpLib)2158 ErrAlways(ctx) << "multiple CMSE import libraries not supported";2159 else if (std::optional<MemoryBufferRef> mb =2160 readFile(ctx, arg->getValue()))2161 armCmseImpLib = createObjFile(ctx, *mb);2162 break;2163 case OPT_start_group:2164 if (isInGroup)2165 ErrAlways(ctx) << "nested --start-group";2166 isInGroup = true;2167 break;2168 case OPT_end_group:2169 if (!isInGroup)2170 ErrAlways(ctx) << "stray --end-group";2171 isInGroup = false;2172 ++nextGroupId;2173 break;2174 case OPT_start_lib:2175 if (inLib)2176 ErrAlways(ctx) << "nested --start-lib";2177 if (isInGroup)2178 ErrAlways(ctx) << "may not nest --start-lib in --start-group";2179 inLib = true;2180 isInGroup = true;2181 break;2182 case OPT_end_lib:2183 if (!inLib)2184 ErrAlways(ctx) << "stray --end-lib";2185 inLib = false;2186 isInGroup = false;2187 ++nextGroupId;2188 break;2189 case OPT_push_state:2190 stack.emplace_back(ctx.arg.asNeeded, ctx.arg.isStatic, inWholeArchive);2191 break;2192 case OPT_pop_state:2193 if (stack.empty()) {2194 ErrAlways(ctx) << "unbalanced --push-state/--pop-state";2195 break;2196 }2197 std::tie(ctx.arg.asNeeded, ctx.arg.isStatic, inWholeArchive) =2198 stack.back();2199 stack.pop_back();2200 break;2201 }2202 }2203 2204 if (defaultScript && !hasScript)2205 readLinkerScript(ctx, *defaultScript);2206 if (files.empty() && !hasInput && errCount(ctx) == 0)2207 ErrAlways(ctx) << "no input files";2208}2209 2210// If -m <machine_type> was not given, infer it from object files.2211void LinkerDriver::inferMachineType() {2212 if (ctx.arg.ekind != ELFNoneKind)2213 return;2214 2215 bool inferred = false;2216 for (auto &f : files) {2217 if (f->ekind == ELFNoneKind)2218 continue;2219 if (!inferred) {2220 inferred = true;2221 ctx.arg.ekind = f->ekind;2222 ctx.arg.emachine = f->emachine;2223 ctx.arg.mipsN32Abi = ctx.arg.emachine == EM_MIPS && isMipsN32Abi(ctx, *f);2224 }2225 ctx.arg.osabi = f->osabi;2226 if (f->osabi != ELFOSABI_NONE)2227 return;2228 }2229 if (!inferred)2230 ErrAlways(ctx)2231 << "target emulation unknown: -m or at least one .o file required";2232}2233 2234// Parse -z max-page-size=<value>. The default value is defined by2235// each target.2236static uint64_t getMaxPageSize(Ctx &ctx, opt::InputArgList &args) {2237 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",2238 ctx.target->defaultMaxPageSize);2239 if (!isPowerOf2_64(val)) {2240 ErrAlways(ctx) << "max-page-size: value isn't a power of 2";2241 return ctx.target->defaultMaxPageSize;2242 }2243 if (ctx.arg.nmagic || ctx.arg.omagic) {2244 if (val != ctx.target->defaultMaxPageSize)2245 Warn(ctx)2246 << "-z max-page-size set, but paging disabled by omagic or nmagic";2247 return 1;2248 }2249 return val;2250}2251 2252// Parse -z common-page-size=<value>. The default value is defined by2253// each target.2254static uint64_t getCommonPageSize(Ctx &ctx, opt::InputArgList &args) {2255 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",2256 ctx.target->defaultCommonPageSize);2257 if (!isPowerOf2_64(val)) {2258 ErrAlways(ctx) << "common-page-size: value isn't a power of 2";2259 return ctx.target->defaultCommonPageSize;2260 }2261 if (ctx.arg.nmagic || ctx.arg.omagic) {2262 if (val != ctx.target->defaultCommonPageSize)2263 Warn(ctx)2264 << "-z common-page-size set, but paging disabled by omagic or nmagic";2265 return 1;2266 }2267 // commonPageSize can't be larger than maxPageSize.2268 if (val > ctx.arg.maxPageSize)2269 val = ctx.arg.maxPageSize;2270 return val;2271}2272 2273// Parses --image-base option.2274static std::optional<uint64_t> getImageBase(Ctx &ctx, opt::InputArgList &args) {2275 // Because we are using `ctx.arg.maxPageSize` here, this function has to be2276 // called after the variable is initialized.2277 auto *arg = args.getLastArg(OPT_image_base);2278 if (!arg)2279 return std::nullopt;2280 2281 StringRef s = arg->getValue();2282 uint64_t v;2283 if (!to_integer(s, v)) {2284 ErrAlways(ctx) << "--image-base: number expected, but got " << s;2285 return 0;2286 }2287 if ((v % ctx.arg.maxPageSize) != 0)2288 Warn(ctx) << "--image-base: address isn't multiple of page size: " << s;2289 return v;2290}2291 2292// Parses `--exclude-libs=lib,lib,...`.2293// The library names may be delimited by commas or colons.2294static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {2295 DenseSet<StringRef> ret;2296 for (auto *arg : args.filtered(OPT_exclude_libs)) {2297 StringRef s = arg->getValue();2298 for (;;) {2299 size_t pos = s.find_first_of(",:");2300 if (pos == StringRef::npos)2301 break;2302 ret.insert(s.substr(0, pos));2303 s = s.substr(pos + 1);2304 }2305 ret.insert(s);2306 }2307 return ret;2308}2309 2310// Handles the --exclude-libs option. If a static library file is specified2311// by the --exclude-libs option, all public symbols from the archive become2312// private unless otherwise specified by version scripts or something.2313// A special library name "ALL" means all archive files.2314//2315// This is not a popular option, but some programs such as bionic libc use it.2316static void excludeLibs(Ctx &ctx, opt::InputArgList &args) {2317 DenseSet<StringRef> libs = getExcludeLibs(args);2318 bool all = libs.count("ALL");2319 2320 auto visit = [&](InputFile *file) {2321 if (file->archiveName.empty() ||2322 !(all || libs.count(path::filename(file->archiveName))))2323 return;2324 ArrayRef<Symbol *> symbols = file->getSymbols();2325 if (isa<ELFFileBase>(file))2326 symbols = cast<ELFFileBase>(file)->getGlobalSymbols();2327 for (Symbol *sym : symbols) {2328 if (!sym->isUndefined() && sym->file == file) {2329 sym->versionId = VER_NDX_LOCAL;2330 sym->isExported = false;2331 }2332 }2333 };2334 2335 for (ELFFileBase *file : ctx.objectFiles)2336 visit(file);2337 2338 for (BitcodeFile *file : ctx.bitcodeFiles)2339 visit(file);2340}2341 2342// Force Sym to be entered in the output.2343static void handleUndefined(Ctx &ctx, Symbol *sym, const char *option) {2344 // Since a symbol may not be used inside the program, LTO may2345 // eliminate it. Mark the symbol as "used" to prevent it.2346 sym->isUsedInRegularObj = true;2347 2348 if (!sym->isLazy())2349 return;2350 sym->extract(ctx);2351 if (!ctx.arg.whyExtract.empty())2352 ctx.whyExtractRecords.emplace_back(option, sym->file, *sym);2353}2354 2355// As an extension to GNU linkers, lld supports a variant of `-u`2356// which accepts wildcard patterns. All symbols that match a given2357// pattern are handled as if they were given by `-u`.2358static void handleUndefinedGlob(Ctx &ctx, StringRef arg) {2359 Expected<GlobPattern> pat = GlobPattern::create(arg);2360 if (!pat) {2361 ErrAlways(ctx) << "--undefined-glob: " << pat.takeError() << ": " << arg;2362 return;2363 }2364 2365 // Calling sym->extract() in the loop is not safe because it may add new2366 // symbols to the symbol table, invalidating the current iterator.2367 SmallVector<Symbol *, 0> syms;2368 for (Symbol *sym : ctx.symtab->getSymbols())2369 if (!sym->isPlaceholder() && pat->match(sym->getName()))2370 syms.push_back(sym);2371 2372 for (Symbol *sym : syms)2373 handleUndefined(ctx, sym, "--undefined-glob");2374}2375 2376static void handleLibcall(Ctx &ctx, StringRef name) {2377 Symbol *sym = ctx.symtab->find(name);2378 if (sym && sym->isLazy() && isa<BitcodeFile>(sym->file)) {2379 if (!ctx.arg.whyExtract.empty())2380 ctx.whyExtractRecords.emplace_back("<libcall>", sym->file, *sym);2381 sym->extract(ctx);2382 }2383}2384 2385static void writeArchiveStats(Ctx &ctx) {2386 if (ctx.arg.printArchiveStats.empty())2387 return;2388 2389 std::error_code ec;2390 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.printArchiveStats, ec);2391 if (ec) {2392 ErrAlways(ctx) << "--print-archive-stats=: cannot open "2393 << ctx.arg.printArchiveStats << ": " << ec.message();2394 return;2395 }2396 2397 os << "members\textracted\tarchive\n";2398 2399 DenseMap<CachedHashStringRef, unsigned> extracted;2400 for (ELFFileBase *file : ctx.objectFiles)2401 if (file->archiveName.size())2402 ++extracted[CachedHashStringRef(file->archiveName)];2403 for (BitcodeFile *file : ctx.bitcodeFiles)2404 if (file->archiveName.size())2405 ++extracted[CachedHashStringRef(file->archiveName)];2406 for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) {2407 unsigned &v = extracted[CachedHashString(f.first)];2408 os << f.second << '\t' << v << '\t' << f.first << '\n';2409 // If the archive occurs multiple times, other instances have a count of 0.2410 v = 0;2411 }2412}2413 2414static void writeWhyExtract(Ctx &ctx) {2415 if (ctx.arg.whyExtract.empty())2416 return;2417 2418 std::error_code ec;2419 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.whyExtract, ec);2420 if (ec) {2421 ErrAlways(ctx) << "cannot open --why-extract= file " << ctx.arg.whyExtract2422 << ": " << ec.message();2423 return;2424 }2425 2426 os << "reference\textracted\tsymbol\n";2427 for (auto &entry : ctx.whyExtractRecords) {2428 os << std::get<0>(entry) << '\t' << toStr(ctx, std::get<1>(entry)) << '\t'2429 << toStr(ctx, std::get<2>(entry)) << '\n';2430 }2431}2432 2433static void reportBackrefs(Ctx &ctx) {2434 for (auto &ref : ctx.backwardReferences) {2435 const Symbol &sym = *ref.first;2436 std::string to = toStr(ctx, ref.second.second);2437 // Some libraries have known problems and can cause noise. Filter them out2438 // with --warn-backrefs-exclude=. The value may look like (for --start-lib)2439 // *.o or (archive member) *.a(*.o).2440 bool exclude = false;2441 for (const llvm::GlobPattern &pat : ctx.arg.warnBackrefsExclude)2442 if (pat.match(to)) {2443 exclude = true;2444 break;2445 }2446 if (!exclude)2447 Warn(ctx) << "backward reference detected: " << sym.getName() << " in "2448 << ref.second.first << " refers to " << to;2449 }2450}2451 2452// Handle --dependency-file=<path>. If that option is given, lld creates a2453// file at a given path with the following contents:2454//2455// <output-file>: <input-file> ...2456//2457// <input-file>:2458//2459// where <output-file> is a pathname of an output file and <input-file>2460// ... is a list of pathnames of all input files. `make` command can read a2461// file in the above format and interpret it as a dependency info. We write2462// phony targets for every <input-file> to avoid an error when that file is2463// removed.2464//2465// This option is useful if you want to make your final executable to depend2466// on all input files including system libraries. Here is why.2467//2468// When you write a Makefile, you usually write it so that the final2469// executable depends on all user-generated object files. Normally, you2470// don't make your executable to depend on system libraries (such as libc)2471// because you don't know the exact paths of libraries, even though system2472// libraries that are linked to your executable statically are technically a2473// part of your program. By using --dependency-file option, you can make2474// lld to dump dependency info so that you can maintain exact dependencies2475// easily.2476static void writeDependencyFile(Ctx &ctx) {2477 std::error_code ec;2478 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.dependencyFile, ec);2479 if (ec) {2480 ErrAlways(ctx) << "cannot open " << ctx.arg.dependencyFile << ": "2481 << ec.message();2482 return;2483 }2484 2485 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:2486 // * A space is escaped by a backslash which itself must be escaped.2487 // * A hash sign is escaped by a single backslash.2488 // * $ is escapes as $$.2489 auto printFilename = [](raw_fd_ostream &os, StringRef filename) {2490 llvm::SmallString<256> nativePath;2491 llvm::sys::path::native(filename.str(), nativePath);2492 llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);2493 for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {2494 if (nativePath[i] == '#') {2495 os << '\\';2496 } else if (nativePath[i] == ' ') {2497 os << '\\';2498 unsigned j = i;2499 while (j > 0 && nativePath[--j] == '\\')2500 os << '\\';2501 } else if (nativePath[i] == '$') {2502 os << '$';2503 }2504 os << nativePath[i];2505 }2506 };2507 2508 os << ctx.arg.outputFile << ":";2509 for (StringRef path : ctx.arg.dependencyFiles) {2510 os << " \\\n ";2511 printFilename(os, path);2512 }2513 os << "\n";2514 2515 for (StringRef path : ctx.arg.dependencyFiles) {2516 os << "\n";2517 printFilename(os, path);2518 os << ":\n";2519 }2520}2521 2522// Replaces common symbols with defined symbols reside in .bss sections.2523// This function is called after all symbol names are resolved. As a2524// result, the passes after the symbol resolution won't see any2525// symbols of type CommonSymbol.2526static void replaceCommonSymbols(Ctx &ctx) {2527 llvm::TimeTraceScope timeScope("Replace common symbols");2528 for (ELFFileBase *file : ctx.objectFiles) {2529 if (!file->hasCommonSyms)2530 continue;2531 for (Symbol *sym : file->getGlobalSymbols()) {2532 auto *s = dyn_cast<CommonSymbol>(sym);2533 if (!s)2534 continue;2535 2536 auto *bss = make<BssSection>(ctx, "COMMON", s->size, s->alignment);2537 bss->file = s->file;2538 ctx.inputSections.push_back(bss);2539 Defined(ctx, s->file, StringRef(), s->binding, s->stOther, s->type,2540 /*value=*/0, s->size, bss)2541 .overwrite(*s);2542 }2543 }2544}2545 2546// The section referred to by `s` is considered address-significant. Set the2547// keepUnique flag on the section if appropriate.2548static void markAddrsig(bool icfSafe, Symbol *s) {2549 // We don't need to keep text sections unique under --icf=all even if they2550 // are address-significant.2551 if (auto *d = dyn_cast_or_null<Defined>(s))2552 if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section))2553 if (icfSafe || !(sec->flags & SHF_EXECINSTR))2554 sec->keepUnique = true;2555}2556 2557// Record sections that define symbols mentioned in --keep-unique <symbol>2558// and symbols referred to by address-significance tables. These sections are2559// ineligible for ICF.2560template <class ELFT>2561static void findKeepUniqueSections(Ctx &ctx, opt::InputArgList &args) {2562 for (auto *arg : args.filtered(OPT_keep_unique)) {2563 StringRef name = arg->getValue();2564 auto *d = dyn_cast_or_null<Defined>(ctx.symtab->find(name));2565 if (!d || !d->section) {2566 Warn(ctx) << "could not find symbol " << name << " to keep unique";2567 continue;2568 }2569 if (auto *sec = dyn_cast<InputSectionBase>(d->section))2570 sec->keepUnique = true;2571 }2572 2573 // --icf=all --ignore-data-address-equality means that we can ignore2574 // the dynsym and address-significance tables entirely.2575 if (ctx.arg.icf == ICFLevel::All && ctx.arg.ignoreDataAddressEquality)2576 return;2577 2578 // Symbols in the dynsym could be address-significant in other executables2579 // or DSOs, so we conservatively mark them as address-significant.2580 bool icfSafe = ctx.arg.icf == ICFLevel::Safe;2581 for (Symbol *sym : ctx.symtab->getSymbols())2582 if (sym->isExported)2583 markAddrsig(icfSafe, sym);2584 2585 // Visit the address-significance table in each object file and mark each2586 // referenced symbol as address-significant.2587 for (InputFile *f : ctx.objectFiles) {2588 auto *obj = cast<ObjFile<ELFT>>(f);2589 ArrayRef<Symbol *> syms = obj->getSymbols();2590 if (obj->addrsigSec) {2591 ArrayRef<uint8_t> contents =2592 check(obj->getObj().getSectionContents(*obj->addrsigSec));2593 const uint8_t *cur = contents.begin();2594 while (cur != contents.end()) {2595 unsigned size;2596 const char *err = nullptr;2597 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);2598 if (err) {2599 Err(ctx) << f << ": could not decode addrsig section: " << err;2600 break;2601 }2602 markAddrsig(icfSafe, syms[symIndex]);2603 cur += size;2604 }2605 } else {2606 // If an object file does not have an address-significance table,2607 // conservatively mark all of its symbols as address-significant.2608 for (Symbol *s : syms)2609 markAddrsig(icfSafe, s);2610 }2611 }2612}2613 2614// This function reads a symbol partition specification section. These sections2615// are used to control which partition a symbol is allocated to. See2616// https://lld.llvm.org/Partitions.html for more details on partitions.2617template <typename ELFT>2618static void readSymbolPartitionSection(Ctx &ctx, InputSectionBase *s) {2619 // Read the relocation that refers to the partition's entry point symbol.2620 Symbol *sym;2621 const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();2622 auto readEntry = [](InputFile *file, const auto &rels) -> Symbol * {2623 for (const auto &rel : rels)2624 return &file->getRelocTargetSym(rel);2625 return nullptr;2626 };2627 if (rels.areRelocsCrel())2628 sym = readEntry(s->file, rels.crels);2629 else if (rels.areRelocsRel())2630 sym = readEntry(s->file, rels.rels);2631 else2632 sym = readEntry(s->file, rels.relas);2633 if (!isa_and_nonnull<Defined>(sym) || !sym->isExported)2634 return;2635 2636 StringRef partName = reinterpret_cast<const char *>(s->content().data());2637 for (Partition &part : ctx.partitions) {2638 if (part.name == partName) {2639 sym->partition = part.getNumber(ctx);2640 return;2641 }2642 }2643 2644 // Forbid partitions from being used on incompatible targets, and forbid them2645 // from being used together with various linker features that assume a single2646 // set of output sections.2647 if (ctx.script->hasSectionsCommand)2648 ErrAlways(ctx) << s->file2649 << ": partitions cannot be used with the SECTIONS command";2650 if (ctx.script->hasPhdrsCommands())2651 ErrAlways(ctx) << s->file2652 << ": partitions cannot be used with the PHDRS command";2653 if (!ctx.arg.sectionStartMap.empty())2654 ErrAlways(ctx) << s->file2655 << ": partitions cannot be used with "2656 "--section-start, -Ttext, -Tdata or -Tbss";2657 if (ctx.arg.emachine == EM_MIPS)2658 ErrAlways(ctx) << s->file << ": partitions cannot be used on this target";2659 2660 // Impose a limit of no more than 254 partitions. This limit comes from the2661 // sizes of the Partition fields in InputSectionBase and Symbol, as well as2662 // the amount of space devoted to the partition number in RankFlags.2663 if (ctx.partitions.size() == 254)2664 Fatal(ctx) << "may not have more than 254 partitions";2665 2666 ctx.partitions.emplace_back(ctx);2667 Partition &newPart = ctx.partitions.back();2668 newPart.name = partName;2669 sym->partition = newPart.getNumber(ctx);2670}2671 2672static void markBuffersAsDontNeed(Ctx &ctx, bool skipLinkedOutput) {2673 // With --thinlto-index-only, all buffers are nearly unused from now on2674 // (except symbol/section names used by infrequent passes). Mark input file2675 // buffers as MADV_DONTNEED so that these pages can be reused by the expensive2676 // thin link, saving memory.2677 if (skipLinkedOutput) {2678 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))2679 mb.dontNeedIfMmap();2680 return;2681 }2682 2683 // Otherwise, just mark MemoryBuffers backing BitcodeFiles.2684 DenseSet<const char *> bufs;2685 for (BitcodeFile *file : ctx.bitcodeFiles)2686 bufs.insert(file->mb.getBufferStart());2687 for (BitcodeFile *file : ctx.lazyBitcodeFiles)2688 bufs.insert(file->mb.getBufferStart());2689 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))2690 if (bufs.count(mb.getBufferStart()))2691 mb.dontNeedIfMmap();2692}2693 2694// This function is where all the optimizations of link-time2695// optimization takes place. When LTO is in use, some input files are2696// not in native object file format but in the LLVM bitcode format.2697// This function compiles bitcode files into a few big native files2698// using LLVM functions and replaces bitcode symbols with the results.2699// Because all bitcode files that the program consists of are passed to2700// the compiler at once, it can do a whole-program optimization.2701template <class ELFT>2702void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) {2703 llvm::TimeTraceScope timeScope("LTO");2704 // Compile bitcode files and replace bitcode symbols.2705 lto.reset(new BitcodeCompiler(ctx));2706 for (BitcodeFile *file : ctx.bitcodeFiles)2707 lto->add(*file);2708 2709 if (!ctx.bitcodeFiles.empty())2710 markBuffersAsDontNeed(ctx, skipLinkedOutput);2711 2712 ltoObjectFiles = lto->compile();2713 for (auto &file : ltoObjectFiles) {2714 auto *obj = cast<ObjFile<ELFT>>(file.get());2715 obj->parse(/*ignoreComdats=*/true);2716 2717 // This is only needed for AArch64 PAuth to set correct key in AUTH GOT2718 // entry based on symbol type (STT_FUNC or not).2719 // TODO: check if PAuth is actually used.2720 if (ctx.arg.emachine == EM_AARCH64) {2721 for (typename ELFT::Sym elfSym : obj->template getGlobalELFSyms<ELFT>()) {2722 StringRef elfSymName = check(elfSym.getName(obj->getStringTable()));2723 if (Symbol *sym = ctx.symtab->find(elfSymName))2724 if (sym->type == STT_NOTYPE)2725 sym->type = elfSym.getType();2726 }2727 }2728 2729 // For defined symbols in non-relocatable output,2730 // compute isExported and parse '@'.2731 if (!ctx.arg.relocatable)2732 for (Symbol *sym : obj->getGlobalSymbols()) {2733 if (!sym->isDefined())2734 continue;2735 if (ctx.arg.exportDynamic && sym->computeBinding(ctx) != STB_LOCAL)2736 sym->isExported = true;2737 if (sym->hasVersionSuffix)2738 sym->parseSymbolVersion(ctx);2739 }2740 ctx.objectFiles.push_back(obj);2741 }2742}2743 2744// The --wrap option is a feature to rename symbols so that you can write2745// wrappers for existing functions. If you pass `--wrap=foo`, all2746// occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are2747// expected to write `__wrap_foo` function as a wrapper). The original2748// symbol becomes accessible as `__real_foo`, so you can call that from your2749// wrapper.2750//2751// This data structure is instantiated for each --wrap option.2752struct WrappedSymbol {2753 Symbol *sym;2754 Symbol *real;2755 Symbol *wrap;2756};2757 2758// Handles --wrap option.2759//2760// This function instantiates wrapper symbols. At this point, they seem2761// like they are not being used at all, so we explicitly set some flags so2762// that LTO won't eliminate them.2763static std::vector<WrappedSymbol> addWrappedSymbols(Ctx &ctx,2764 opt::InputArgList &args) {2765 std::vector<WrappedSymbol> v;2766 DenseSet<StringRef> seen;2767 auto &ss = ctx.saver;2768 for (auto *arg : args.filtered(OPT_wrap)) {2769 StringRef name = arg->getValue();2770 if (!seen.insert(name).second)2771 continue;2772 2773 Symbol *sym = ctx.symtab->find(name);2774 if (!sym)2775 continue;2776 2777 Symbol *wrap =2778 ctx.symtab->addUnusedUndefined(ss.save("__wrap_" + name), sym->binding);2779 2780 // If __real_ is referenced, pull in the symbol if it is lazy. Do this after2781 // processing __wrap_ as that may have referenced __real_.2782 StringRef realName = ctx.saver.save("__real_" + name);2783 if (Symbol *real = ctx.symtab->find(realName)) {2784 ctx.symtab->addUnusedUndefined(name, sym->binding);2785 // Update sym's binding, which will replace real's later in2786 // SymbolTable::wrap.2787 sym->binding = real->binding;2788 }2789 2790 Symbol *real = ctx.symtab->addUnusedUndefined(realName);2791 v.push_back({sym, real, wrap});2792 2793 // We want to tell LTO not to inline symbols to be overwritten2794 // because LTO doesn't know the final symbol contents after renaming.2795 real->scriptDefined = true;2796 sym->scriptDefined = true;2797 2798 // If a symbol is referenced in any object file, bitcode file or shared2799 // object, mark its redirection target (foo for __real_foo and __wrap_foo2800 // for foo) as referenced after redirection, which will be used to tell LTO2801 // to not eliminate the redirection target. If the object file defining the2802 // symbol also references it, we cannot easily distinguish the case from2803 // cases where the symbol is not referenced. Retain the redirection target2804 // in this case because we choose to wrap symbol references regardless of2805 // whether the symbol is defined2806 // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).2807 if (real->referenced || real->isDefined())2808 sym->referencedAfterWrap = true;2809 if (sym->referenced || sym->isDefined())2810 wrap->referencedAfterWrap = true;2811 }2812 return v;2813}2814 2815static void combineVersionedSymbol(Ctx &ctx, Symbol &sym,2816 DenseMap<Symbol *, Symbol *> &map) {2817 const char *suffix1 = sym.getVersionSuffix();2818 if (suffix1[0] != '@' || suffix1[1] == '@')2819 return;2820 2821 // Check the existing symbol foo. We have two special cases to handle:2822 //2823 // * There is a definition of foo@v1 and foo@@v1.2824 // * There is a definition of foo@v1 and foo.2825 Defined *sym2 = dyn_cast_or_null<Defined>(ctx.symtab->find(sym.getName()));2826 if (!sym2)2827 return;2828 const char *suffix2 = sym2->getVersionSuffix();2829 if (suffix2[0] == '@' && suffix2[1] == '@' &&2830 strcmp(suffix1 + 1, suffix2 + 2) == 0) {2831 // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.2832 map.try_emplace(&sym, sym2);2833 // If both foo@v1 and foo@@v1 are defined and non-weak, report a2834 // duplicate definition error.2835 if (sym.isDefined()) {2836 sym2->checkDuplicate(ctx, cast<Defined>(sym));2837 sym2->resolve(ctx, cast<Defined>(sym));2838 } else if (sym.isUndefined()) {2839 sym2->resolve(ctx, cast<Undefined>(sym));2840 } else {2841 sym2->resolve(ctx, cast<SharedSymbol>(sym));2842 }2843 // Eliminate foo@v1 from the symbol table.2844 sym.symbolKind = Symbol::PlaceholderKind;2845 sym.isUsedInRegularObj = false;2846 } else if (auto *sym1 = dyn_cast<Defined>(&sym)) {2847 if (sym2->versionId > VER_NDX_GLOBAL2848 ? ctx.arg.versionDefinitions[sym2->versionId].name == suffix1 + 12849 : sym1->section == sym2->section && sym1->value == sym2->value) {2850 // Due to an assembler design flaw, if foo is defined, .symver foo,2851 // foo@v1 defines both foo and foo@v1. Unless foo is bound to a2852 // different version, GNU ld makes foo@v1 canonical and eliminates2853 // foo. Emulate its behavior, otherwise we would have foo or foo@@v12854 // beside foo@v1. foo@v1 and foo combining does not apply if they are2855 // not defined in the same place.2856 map.try_emplace(sym2, &sym);2857 sym2->symbolKind = Symbol::PlaceholderKind;2858 sym2->isUsedInRegularObj = false;2859 }2860 }2861}2862 2863// Do renaming for --wrap and foo@v1 by updating pointers to symbols.2864//2865// When this function is executed, only InputFiles and symbol table2866// contain pointers to symbol objects. We visit them to replace pointers,2867// so that wrapped symbols are swapped as instructed by the command line.2868static void redirectSymbols(Ctx &ctx, ArrayRef<WrappedSymbol> wrapped) {2869 llvm::TimeTraceScope timeScope("Redirect symbols");2870 DenseMap<Symbol *, Symbol *> map;2871 for (const WrappedSymbol &w : wrapped) {2872 map[w.sym] = w.wrap;2873 map[w.real] = w.sym;2874 }2875 2876 // If there are version definitions (versionDefinitions.size() > 2), enumerate2877 // symbols with a non-default version (foo@v1) and check whether it should be2878 // combined with foo or foo@@v1.2879 if (ctx.arg.versionDefinitions.size() > 2)2880 for (Symbol *sym : ctx.symtab->getSymbols())2881 if (sym->hasVersionSuffix)2882 combineVersionedSymbol(ctx, *sym, map);2883 2884 if (map.empty())2885 return;2886 2887 // Update pointers in input files.2888 parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) {2889 for (Symbol *&sym : file->getMutableGlobalSymbols())2890 if (Symbol *s = map.lookup(sym))2891 sym = s;2892 });2893 2894 // Update pointers in the symbol table.2895 for (const WrappedSymbol &w : wrapped)2896 ctx.symtab->wrap(w.sym, w.real, w.wrap);2897}2898 2899// To enable CET (x86's hardware-assisted control flow enforcement), each2900// source file must be compiled with -fcf-protection. Object files compiled2901// with the flag contain feature flags indicating that they are compatible2902// with CET. We enable the feature only when all object files are compatible2903// with CET.2904//2905// This is also the case with AARCH64's BTI and PAC which use the similar2906// GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.2907//2908// For AArch64 PAuth-enabled object files, the core info of all of them must2909// match. Missing info for some object files with matching info for remaining2910// ones can be allowed (see -z pauth-report).2911//2912// RISC-V Zicfilp/Zicfiss extension also use the same mechanism to record2913// enabled features in the GNU_PROPERTY_RISCV_FEATURE_1_AND bit mask.2914static void readSecurityNotes(Ctx &ctx) {2915 if (ctx.arg.emachine != EM_386 && ctx.arg.emachine != EM_X86_64 &&2916 ctx.arg.emachine != EM_AARCH64 && ctx.arg.emachine != EM_RISCV)2917 return;2918 2919 ctx.arg.andFeatures = -1;2920 2921 StringRef referenceFileName;2922 if (ctx.arg.emachine == EM_AARCH64) {2923 auto it = llvm::find_if(ctx.objectFiles, [](const ELFFileBase *f) {2924 return f->aarch64PauthAbiCoreInfo.has_value();2925 });2926 if (it != ctx.objectFiles.end()) {2927 ctx.aarch64PauthAbiCoreInfo = (*it)->aarch64PauthAbiCoreInfo;2928 referenceFileName = (*it)->getName();2929 }2930 }2931 bool hasValidPauthAbiCoreInfo =2932 ctx.aarch64PauthAbiCoreInfo && ctx.aarch64PauthAbiCoreInfo->isValid();2933 2934 auto report = [&](ReportPolicy policy) -> ELFSyncStream {2935 return {ctx, toDiagLevel(policy)};2936 };2937 auto reportUnless = [&](ReportPolicy policy, bool cond) -> ELFSyncStream {2938 if (cond)2939 return {ctx, DiagLevel::None};2940 return {ctx, toDiagLevel(policy)};2941 };2942 for (ELFFileBase *f : ctx.objectFiles) {2943 uint32_t features = f->andFeatures;2944 2945 reportUnless(ctx.arg.zBtiReport,2946 features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)2947 << f2948 << ": -z bti-report: file does not have "2949 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property";2950 2951 reportUnless(ctx.arg.zGcsReport,2952 features & GNU_PROPERTY_AARCH64_FEATURE_1_GCS)2953 << f2954 << ": -z gcs-report: file does not have "2955 "GNU_PROPERTY_AARCH64_FEATURE_1_GCS property";2956 2957 reportUnless(ctx.arg.zCetReport, features & GNU_PROPERTY_X86_FEATURE_1_IBT)2958 << f2959 << ": -z cet-report: file does not have "2960 "GNU_PROPERTY_X86_FEATURE_1_IBT property";2961 2962 reportUnless(ctx.arg.zCetReport,2963 features & GNU_PROPERTY_X86_FEATURE_1_SHSTK)2964 << f2965 << ": -z cet-report: file does not have "2966 "GNU_PROPERTY_X86_FEATURE_1_SHSTK property";2967 2968 if (ctx.arg.emachine == EM_RISCV) {2969 reportUnless(ctx.arg.zZicfilpUnlabeledReport,2970 features & GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED)2971 << f2972 << ": -z zicfilp-unlabeled-report: file does not have "2973 "GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED property";2974 2975 reportUnless(ctx.arg.zZicfilpFuncSigReport,2976 features & GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG)2977 << f2978 << ": -z zicfilp-func-sig-report: file does not have "2979 "GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG property";2980 2981 if ((features & GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED) &&2982 (features & GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG))2983 Err(ctx) << f2984 << ": file has conflicting properties: "2985 "GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED and "2986 "GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG";2987 2988 reportUnless(ctx.arg.zZicfissReport,2989 features & GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS)2990 << f2991 << ": -z zicfiss-report: file does not have "2992 "GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS property";2993 2994 if (ctx.arg.zZicfilp == ZicfilpPolicy::Unlabeled &&2995 (features & GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG))2996 Warn(ctx) << f2997 << ": -z zicfilp=unlabeled: file has conflicting property: "2998 "GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG";2999 3000 if (ctx.arg.zZicfilp == ZicfilpPolicy::FuncSig &&3001 (features & GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED))3002 Warn(ctx) << f3003 << ": -z zicfilp=func-sig: file has conflicting property: "3004 "GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED";3005 }3006 3007 if (ctx.arg.zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {3008 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;3009 if (ctx.arg.zBtiReport == ReportPolicy::None)3010 Warn(ctx) << f3011 << ": -z force-bti: file does not have "3012 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property";3013 } else if (ctx.arg.zForceIbt &&3014 !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {3015 if (ctx.arg.zCetReport == ReportPolicy::None)3016 Warn(ctx) << f3017 << ": -z force-ibt: file does not have "3018 "GNU_PROPERTY_X86_FEATURE_1_IBT property";3019 features |= GNU_PROPERTY_X86_FEATURE_1_IBT;3020 }3021 if (ctx.arg.zPacPlt && !(hasValidPauthAbiCoreInfo ||3022 (features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC))) {3023 Warn(ctx) << f3024 << ": -z pac-plt: file does not have "3025 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property and no valid "3026 "PAuth core info present for this link job";3027 features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;3028 }3029 ctx.arg.andFeatures &= features;3030 3031 if (!ctx.aarch64PauthAbiCoreInfo)3032 continue;3033 3034 if (!f->aarch64PauthAbiCoreInfo) {3035 report(ctx.arg.zPauthReport)3036 << f3037 << ": -z pauth-report: file does not have AArch64 "3038 "PAuth core info while '"3039 << referenceFileName << "' has one";3040 continue;3041 }3042 3043 if (ctx.aarch64PauthAbiCoreInfo != f->aarch64PauthAbiCoreInfo)3044 Err(ctx)3045 << "incompatible values of AArch64 PAuth core info found\n"3046 << "platform:\n"3047 << ">>> " << referenceFileName << ": 0x"3048 << toHex(ctx.aarch64PauthAbiCoreInfo->platform, /*LowerCase=*/true)3049 << "\n>>> " << f << ": 0x"3050 << toHex(f->aarch64PauthAbiCoreInfo->platform, /*LowerCase=*/true)3051 << "\nversion:\n"3052 << ">>> " << referenceFileName << ": 0x"3053 << toHex(ctx.aarch64PauthAbiCoreInfo->version, /*LowerCase=*/true)3054 << "\n>>> " << f << ": 0x"3055 << toHex(f->aarch64PauthAbiCoreInfo->version, /*LowerCase=*/true);3056 }3057 3058 // Force enable Shadow Stack.3059 if (ctx.arg.zShstk)3060 ctx.arg.andFeatures |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;3061 3062 // Force enable/disable GCS3063 if (ctx.arg.zGcs == GcsPolicy::Always)3064 ctx.arg.andFeatures |= GNU_PROPERTY_AARCH64_FEATURE_1_GCS;3065 else if (ctx.arg.zGcs == GcsPolicy::Never)3066 ctx.arg.andFeatures &= ~GNU_PROPERTY_AARCH64_FEATURE_1_GCS;3067 3068 if (ctx.arg.emachine == EM_RISCV) {3069 // Force enable/disable Zicfilp.3070 if (ctx.arg.zZicfilp == ZicfilpPolicy::Unlabeled) {3071 ctx.arg.andFeatures |= GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED;3072 ctx.arg.andFeatures &= ~GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG;3073 } else if (ctx.arg.zZicfilp == ZicfilpPolicy::FuncSig) {3074 ctx.arg.andFeatures |= GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG;3075 ctx.arg.andFeatures &= ~GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED;3076 } else if (ctx.arg.zZicfilp == ZicfilpPolicy::Never)3077 ctx.arg.andFeatures &= ~(GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED |3078 GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG);3079 3080 // Force enable/disable Zicfiss.3081 if (ctx.arg.zZicfiss == ZicfissPolicy::Always)3082 ctx.arg.andFeatures |= GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS;3083 else if (ctx.arg.zZicfiss == ZicfissPolicy::Never)3084 ctx.arg.andFeatures &= ~GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS;3085 }3086 3087 // If we are utilising GCS at any stage, the sharedFiles should be checked to3088 // ensure they also support this feature. The gcs-report-dynamic option is3089 // used to indicate if the user wants information relating to this, and will3090 // be set depending on the user's input, or warning if gcs-report is set to3091 // either `warning` or `error`.3092 if (ctx.arg.andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_GCS)3093 for (SharedFile *f : ctx.sharedFiles)3094 reportUnless(ctx.arg.zGcsReportDynamic,3095 f->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_GCS)3096 << f3097 << ": GCS is required by -z gcs, but this shared library lacks the "3098 "necessary property note. The "3099 << "dynamic loader might not enable GCS or refuse to load the "3100 "program unless all shared library "3101 << "dependencies have the GCS marking.";3102}3103 3104static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) {3105 switch (file->ekind) {3106 case ELF32LEKind:3107 cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);3108 break;3109 case ELF32BEKind:3110 cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);3111 break;3112 case ELF64LEKind:3113 cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);3114 break;3115 case ELF64BEKind:3116 cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);3117 break;3118 default:3119 llvm_unreachable("");3120 }3121}3122 3123static void postParseObjectFile(ELFFileBase *file) {3124 switch (file->ekind) {3125 case ELF32LEKind:3126 cast<ObjFile<ELF32LE>>(file)->postParse();3127 break;3128 case ELF32BEKind:3129 cast<ObjFile<ELF32BE>>(file)->postParse();3130 break;3131 case ELF64LEKind:3132 cast<ObjFile<ELF64LE>>(file)->postParse();3133 break;3134 case ELF64BEKind:3135 cast<ObjFile<ELF64BE>>(file)->postParse();3136 break;3137 default:3138 llvm_unreachable("");3139 }3140}3141 3142// Do actual linking. Note that when this function is called,3143// all linker scripts have already been parsed.3144template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {3145 llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));3146 3147 // Handle --trace-symbol.3148 for (auto *arg : args.filtered(OPT_trace_symbol))3149 ctx.symtab->insert(arg->getValue())->traced = true;3150 3151 ctx.internalFile = createInternalFile(ctx, "<internal>");3152 ctx.dummySym = make<Undefined>(ctx.internalFile, "", STB_LOCAL, 0, 0);3153 3154 // Handle -u/--undefined before input files. If both a.a and b.so define foo,3155 // -u foo a.a b.so will extract a.a.3156 for (StringRef name : ctx.arg.undefined)3157 ctx.symtab->addUnusedUndefined(name)->referenced = true;3158 3159 parseFiles(ctx, files);3160 3161 // Create dynamic sections for dynamic linking and static PIE.3162 ctx.hasDynsym = !ctx.sharedFiles.empty() || ctx.arg.isPic;3163 ctx.arg.exportDynamic &= ctx.hasDynsym;3164 3165 // Preemptibility of undefined symbols when ctx.hasDynsym is true. Default is3166 // true for dynamic linking.3167 ctx.arg.zDynamicUndefined =3168 getZFlag(args, "dynamic-undefined-weak", "nodynamic-undefined-weak",3169 ctx.sharedFiles.size() || ctx.arg.shared) &&3170 ctx.hasDynsym;3171 3172 // If an entry symbol is in a static archive, pull out that file now.3173 if (Symbol *sym = ctx.symtab->find(ctx.arg.entry))3174 handleUndefined(ctx, sym, "--entry");3175 3176 // Handle the `--undefined-glob <pattern>` options.3177 for (StringRef pat : args::getStrings(args, OPT_undefined_glob))3178 handleUndefinedGlob(ctx, pat);3179 3180 // After potential archive member extraction involving ENTRY and3181 // -u/--undefined-glob, check whether PROVIDE symbols should be defined (the3182 // RHS may refer to definitions in just extracted object files).3183 ctx.script->addScriptReferencedSymbolsToSymTable();3184 3185 // Prevent LTO from removing any definition referenced by -u.3186 for (StringRef name : ctx.arg.undefined)3187 if (Defined *sym = dyn_cast_or_null<Defined>(ctx.symtab->find(name)))3188 sym->isUsedInRegularObj = true;3189 3190 // Mark -init and -fini symbols so that the LTO doesn't eliminate them.3191 if (Symbol *sym = dyn_cast_or_null<Defined>(ctx.symtab->find(ctx.arg.init)))3192 sym->isUsedInRegularObj = true;3193 if (Symbol *sym = dyn_cast_or_null<Defined>(ctx.symtab->find(ctx.arg.fini)))3194 sym->isUsedInRegularObj = true;3195 3196 // If any of our inputs are bitcode files, the LTO code generator may create3197 // references to certain library functions that might not be explicit in the3198 // bitcode file's symbol table. If any of those library functions are defined3199 // in a bitcode file in an archive member, we need to arrange to use LTO to3200 // compile those archive members by adding them to the link beforehand.3201 //3202 // However, adding all libcall symbols to the link can have undesired3203 // consequences. For example, the libgcc implementation of3204 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry3205 // that aborts the program if the Linux kernel does not support 64-bit3206 // atomics, which would prevent the program from running even if it does not3207 // use 64-bit atomics.3208 //3209 // Therefore, we only add libcall symbols to the link before LTO if we have3210 // to, i.e. if the symbol's definition is in bitcode. Any other required3211 // libcall symbols will be added to the link after LTO when we add the LTO3212 // object file to the link.3213 if (!ctx.bitcodeFiles.empty()) {3214 llvm::Triple TT(ctx.bitcodeFiles.front()->obj->getTargetTriple());3215 for (auto *s : lto::LTO::getRuntimeLibcallSymbols(TT))3216 handleLibcall(ctx, s);3217 }3218 3219 // Archive members defining __wrap symbols may be extracted.3220 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args);3221 3222 // No more lazy bitcode can be extracted at this point. Do post parse work3223 // like checking duplicate symbols.3224 parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {3225 initSectionsAndLocalSyms(file, /*ignoreComdats=*/false);3226 });3227 parallelForEach(ctx.objectFiles, postParseObjectFile);3228 parallelForEach(ctx.bitcodeFiles,3229 [](BitcodeFile *file) { file->postParse(); });3230 for (auto &it : ctx.nonPrevailingSyms) {3231 Symbol &sym = *it.first;3232 Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type,3233 it.second)3234 .overwrite(sym);3235 cast<Undefined>(sym).nonPrevailing = true;3236 }3237 ctx.nonPrevailingSyms.clear();3238 for (const DuplicateSymbol &d : ctx.duplicates)3239 reportDuplicate(ctx, *d.sym, d.file, d.section, d.value);3240 ctx.duplicates.clear();3241 3242 // Return if there were name resolution errors.3243 if (errCount(ctx))3244 return;3245 3246 // We want to declare linker script's symbols early,3247 // so that we can version them.3248 // They also might be exported if referenced by DSOs.3249 ctx.script->declareSymbols();3250 3251 // Handle --exclude-libs. This is before scanVersionScript() due to a3252 // workaround for Android ndk: for a defined versioned symbol in an archive3253 // without a version node in the version script, Android does not expect a3254 // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).3255 // GNU ld errors in this case.3256 if (args.hasArg(OPT_exclude_libs))3257 excludeLibs(ctx, args);3258 3259 // Create elfHeader early. We need a dummy section in3260 // addReservedSymbols to mark the created symbols as not absolute.3261 ctx.out.elfHeader = std::make_unique<OutputSection>(ctx, "", 0, SHF_ALLOC);3262 3263 // We need to create some reserved symbols such as _end. Create them.3264 if (!ctx.arg.relocatable)3265 addReservedSymbols(ctx);3266 3267 // Apply version scripts.3268 //3269 // For a relocatable output, version scripts don't make sense, and3270 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol3271 // name "foo@ver1") rather do harm, so we don't call this if -r is given.3272 if (!ctx.arg.relocatable) {3273 llvm::TimeTraceScope timeScope("Process symbol versions");3274 ctx.symtab->scanVersionScript();3275 3276 parseVersionAndComputeIsPreemptible(ctx);3277 }3278 3279 // Skip the normal linked output if some LTO options are specified.3280 //3281 // For --thinlto-index-only, index file creation is performed in3282 // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and3283 // --plugin-opt=emit-asm create output files in bitcode or assembly code,3284 // respectively. When only certain thinLTO modules are specified for3285 // compilation, the intermediate object file are the expected output.3286 const bool skipLinkedOutput = ctx.arg.thinLTOIndexOnly || ctx.arg.emitLLVM ||3287 ctx.arg.ltoEmitAsm ||3288 !ctx.arg.thinLTOModulesToCompile.empty();3289 3290 // Handle --lto-validate-all-vtables-have-type-infos.3291 if (ctx.arg.ltoValidateAllVtablesHaveTypeInfos)3292 ltoValidateAllVtablesHaveTypeInfos<ELFT>(ctx, args);3293 3294 // Do link-time optimization if given files are LLVM bitcode files.3295 // This compiles bitcode files into real object files.3296 //3297 // With this the symbol table should be complete. After this, no new names3298 // except a few linker-synthesized ones will be added to the symbol table.3299 const size_t numObjsBeforeLTO = ctx.objectFiles.size();3300 const size_t numInputFilesBeforeLTO = ctx.driver.files.size();3301 compileBitcodeFiles<ELFT>(skipLinkedOutput);3302 3303 // Symbol resolution finished. Report backward reference problems,3304 // --print-archive-stats=, and --why-extract=.3305 reportBackrefs(ctx);3306 writeArchiveStats(ctx);3307 writeWhyExtract(ctx);3308 if (errCount(ctx))3309 return;3310 3311 // Bail out if normal linked output is skipped due to LTO.3312 if (skipLinkedOutput)3313 return;3314 3315 // compileBitcodeFiles may have produced lto.tmp object files. After this, no3316 // more file will be added.3317 auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO);3318 parallelForEach(newObjectFiles, [](ELFFileBase *file) {3319 initSectionsAndLocalSyms(file, /*ignoreComdats=*/true);3320 });3321 parallelForEach(newObjectFiles, postParseObjectFile);3322 for (const DuplicateSymbol &d : ctx.duplicates)3323 reportDuplicate(ctx, *d.sym, d.file, d.section, d.value);3324 3325 // ELF dependent libraries may have introduced new input files after LTO has3326 // completed. This is an error if the files haven't already been parsed, since3327 // changing the symbol table could break the semantic assumptions of LTO.3328 auto newInputFiles = ArrayRef(ctx.driver.files).slice(numInputFilesBeforeLTO);3329 if (!newInputFiles.empty()) {3330 DenseSet<StringRef> oldFilenames;3331 for (auto &f : ArrayRef(ctx.driver.files).slice(0, numInputFilesBeforeLTO))3332 oldFilenames.insert(f->getName());3333 for (auto &newFile : newInputFiles)3334 if (!oldFilenames.contains(newFile->getName()))3335 Err(ctx) << "input file '" << newFile->getName() << "' added after LTO";3336 }3337 3338 // Handle --exclude-libs again because lto.tmp may reference additional3339 // libcalls symbols defined in an excluded archive. This may override3340 // versionId set by scanVersionScript() and isExported.3341 if (args.hasArg(OPT_exclude_libs))3342 excludeLibs(ctx, args);3343 3344 // Record [__acle_se_<sym>, <sym>] pairs for later processing.3345 processArmCmseSymbols(ctx);3346 3347 // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.3348 redirectSymbols(ctx, wrapped);3349 3350 // Replace common symbols with regular symbols.3351 replaceCommonSymbols(ctx);3352 3353 {3354 llvm::TimeTraceScope timeScope("Aggregate sections");3355 // Now that we have a complete list of input files.3356 // Beyond this point, no new files are added.3357 // Aggregate all input sections into one place.3358 for (InputFile *f : ctx.objectFiles) {3359 for (InputSectionBase *s : f->getSections()) {3360 if (!s || s == &InputSection::discarded)3361 continue;3362 if (LLVM_UNLIKELY(isa<EhInputSection>(s)))3363 ctx.ehInputSections.push_back(cast<EhInputSection>(s));3364 else3365 ctx.inputSections.push_back(s);3366 }3367 }3368 for (BinaryFile *f : ctx.binaryFiles)3369 for (InputSectionBase *s : f->getSections())3370 ctx.inputSections.push_back(cast<InputSection>(s));3371 }3372 3373 {3374 llvm::TimeTraceScope timeScope("Strip sections");3375 if (ctx.hasSympart.load(std::memory_order_relaxed)) {3376 llvm::erase_if(ctx.inputSections, [&ctx = ctx](InputSectionBase *s) {3377 if (s->type != SHT_LLVM_SYMPART)3378 return false;3379 readSymbolPartitionSection<ELFT>(ctx, s);3380 return true;3381 });3382 }3383 // We do not want to emit debug sections if --strip-all3384 // or --strip-debug are given.3385 if (ctx.arg.strip != StripPolicy::None) {3386 llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {3387 if (isDebugSection(*s))3388 return true;3389 if (auto *isec = dyn_cast<InputSection>(s))3390 if (InputSectionBase *rel = isec->getRelocatedSection())3391 if (isDebugSection(*rel))3392 return true;3393 3394 return false;3395 });3396 }3397 }3398 3399 // Since we now have a complete set of input files, we can create3400 // a .d file to record build dependencies.3401 if (!ctx.arg.dependencyFile.empty())3402 writeDependencyFile(ctx);3403 3404 // Now that the number of partitions is fixed, save a pointer to the main3405 // partition.3406 ctx.mainPart = &ctx.partitions[0];3407 3408 // Read .note.gnu.property sections from input object files which3409 // contain a hint to tweak linker's and loader's behaviors.3410 readSecurityNotes(ctx);3411 3412 // The Target instance handles target-specific stuff, such as applying3413 // relocations or writing a PLT section. It also contains target-dependent3414 // values such as a default image base address.3415 setTarget(ctx);3416 3417 ctx.arg.eflags = ctx.target->calcEFlags();3418 // maxPageSize (sometimes called abi page size) is the maximum page size that3419 // the output can be run on. For example if the OS can use 4k or 64k page3420 // sizes then maxPageSize must be 64k for the output to be useable on both.3421 // All important alignment decisions must use this value.3422 ctx.arg.maxPageSize = getMaxPageSize(ctx, args);3423 // commonPageSize is the most common page size that the output will be run on.3424 // For example if an OS can use 4k or 64k page sizes and 4k is more common3425 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for3426 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it3427 // is limited to writing trap instructions on the last executable segment.3428 ctx.arg.commonPageSize = getCommonPageSize(ctx, args);3429 3430 ctx.arg.imageBase = getImageBase(ctx, args);3431 3432 // This adds a .comment section containing a version string.3433 if (!ctx.arg.relocatable)3434 ctx.inputSections.push_back(createCommentSection(ctx));3435 3436 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.3437 splitSections<ELFT>(ctx);3438 3439 // Garbage collection and removal of shared symbols from unused shared objects.3440 markLive<ELFT>(ctx);3441 3442 // Make copies of any input sections that need to be copied into each3443 // partition.3444 copySectionsIntoPartitions(ctx);3445 3446 if (canHaveMemtagGlobals(ctx)) {3447 llvm::TimeTraceScope timeScope("Process memory tagged symbols");3448 createTaggedSymbols(ctx);3449 }3450 3451 // Create synthesized sections such as .got and .plt. This is called before3452 // processSectionCommands() so that they can be placed by SECTIONS commands.3453 createSyntheticSections<ELFT>(ctx);3454 3455 // Some input sections that are used for exception handling need to be moved3456 // into synthetic sections. Do that now so that they aren't assigned to3457 // output sections in the usual way.3458 if (!ctx.arg.relocatable)3459 combineEhSections(ctx);3460 3461 // Merge .hexagon.attributes sections.3462 if (ctx.arg.emachine == EM_HEXAGON)3463 mergeHexagonAttributesSections(ctx);3464 3465 // Merge .riscv.attributes sections.3466 if (ctx.arg.emachine == EM_RISCV)3467 mergeRISCVAttributesSections(ctx);3468 3469 {3470 llvm::TimeTraceScope timeScope("Assign sections");3471 3472 // Create output sections described by SECTIONS commands.3473 ctx.script->processSectionCommands();3474 3475 // Linker scripts control how input sections are assigned to output3476 // sections. Input sections that were not handled by scripts are called3477 // "orphans", and they are assigned to output sections by the default rule.3478 // Process that.3479 ctx.script->addOrphanSections();3480 }3481 3482 {3483 llvm::TimeTraceScope timeScope("Merge/finalize input sections");3484 3485 // Migrate InputSectionDescription::sectionBases to sections. This includes3486 // merging MergeInputSections into a single MergeSyntheticSection. From this3487 // point onwards InputSectionDescription::sections should be used instead of3488 // sectionBases.3489 for (SectionCommand *cmd : ctx.script->sectionCommands)3490 if (auto *osd = dyn_cast<OutputDesc>(cmd))3491 osd->osec.finalizeInputSections();3492 }3493 3494 // Two input sections with different output sections should not be folded.3495 // ICF runs after processSectionCommands() so that we know the output sections.3496 if (ctx.arg.icf != ICFLevel::None) {3497 findKeepUniqueSections<ELFT>(ctx, args);3498 doIcf<ELFT>(ctx);3499 }3500 3501 // Read the callgraph now that we know what was gced or icfed3502 if (ctx.arg.callGraphProfileSort != CGProfileSortKind::None) {3503 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {3504 if (std::optional<MemoryBufferRef> buffer =3505 readFile(ctx, arg->getValue()))3506 readCallGraph(ctx, *buffer);3507 } else3508 readCallGraphsFromObjectFiles<ELFT>(ctx);3509 }3510 3511 // Write the result to the file.3512 writeResult<ELFT>(ctx);3513}3514