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-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // The driver drives the entire linking process. It is responsible for 10 // 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 is 13 // that the LLD's driver is agnostic on the host operating system. 14 // Other linkers usually have implicit default values (such as a dynamic 15 // linker path or library paths) for each host OS. 16 // 17 // I don't think implicit default values are useful because they are 18 // usually explicitly specified by the compiler ctx.driver. They can even 19 // be harmful when you are doing cross-linking. Therefore, in LLD, we 20 // simply trust the compiler driver to pass all required options and 21 // 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/Driver.h" 43 #include "lld/Common/ErrorHandler.h" 44 #include "lld/Common/Filesystem.h" 45 #include "lld/Common/Memory.h" 46 #include "lld/Common/Strings.h" 47 #include "lld/Common/TargetOptionsCommandFlags.h" 48 #include "lld/Common/Version.h" 49 #include "llvm/ADT/SetVector.h" 50 #include "llvm/ADT/StringExtras.h" 51 #include "llvm/ADT/StringSwitch.h" 52 #include "llvm/Config/llvm-config.h" 53 #include "llvm/LTO/LTO.h" 54 #include "llvm/Object/Archive.h" 55 #include "llvm/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/TarWriter.h" 64 #include "llvm/Support/TargetSelect.h" 65 #include "llvm/Support/TimeProfiler.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include <cstdlib> 68 #include <utility> 69 70 using namespace llvm; 71 using namespace llvm::ELF; 72 using namespace llvm::object; 73 using namespace llvm::sys; 74 using namespace llvm::support; 75 using namespace lld; 76 using namespace lld::elf; 77 78 ConfigWrapper elf::config; 79 Ctx elf::ctx; 80 81 static void setConfigs(opt::InputArgList &args); 82 static void readConfigs(opt::InputArgList &args); 83 84 void elf::errorOrWarn(const Twine &msg) { 85 if (config->noinhibitExec) 86 warn(msg); 87 else 88 error(msg); 89 } 90 91 void Ctx::reset() { 92 driver = LinkerDriver(); 93 memoryBuffers.clear(); 94 objectFiles.clear(); 95 sharedFiles.clear(); 96 binaryFiles.clear(); 97 bitcodeFiles.clear(); 98 lazyBitcodeFiles.clear(); 99 inputSections.clear(); 100 ehInputSections.clear(); 101 duplicates.clear(); 102 nonPrevailingSyms.clear(); 103 whyExtractRecords.clear(); 104 backwardReferences.clear(); 105 hasSympart.store(false, std::memory_order_relaxed); 106 needsTlsLd.store(false, std::memory_order_relaxed); 107 } 108 109 bool elf::link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS, 110 llvm::raw_ostream &stderrOS, bool exitEarly, 111 bool disableOutput) { 112 // This driver-specific context will be freed later by lldMain(). 113 auto *ctx = new CommonLinkerContext; 114 115 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); 116 ctx->e.cleanupCallback = []() { 117 elf::ctx.reset(); 118 symtab = SymbolTable(); 119 120 outputSections.clear(); 121 symAux.clear(); 122 123 tar = nullptr; 124 in.reset(); 125 126 partitions.clear(); 127 partitions.emplace_back(); 128 129 SharedFile::vernauxNum = 0; 130 }; 131 ctx->e.logName = args::getFilenameWithoutExe(args[0]); 132 ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use " 133 "--error-limit=0 to see all errors)"; 134 135 config = ConfigWrapper(); 136 script = std::make_unique<LinkerScript>(); 137 138 symAux.emplace_back(); 139 140 partitions.clear(); 141 partitions.emplace_back(); 142 143 config->progName = args[0]; 144 145 elf::ctx.driver.linkerMain(args); 146 147 return errorCount() == 0; 148 } 149 150 // Parses a linker -m option. 151 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) { 152 uint8_t osabi = 0; 153 StringRef s = emul; 154 if (s.endswith("_fbsd")) { 155 s = s.drop_back(5); 156 osabi = ELFOSABI_FREEBSD; 157 } 158 159 std::pair<ELFKind, uint16_t> ret = 160 StringSwitch<std::pair<ELFKind, uint16_t>>(s) 161 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64}) 162 .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64}) 163 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 164 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 165 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 166 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 167 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV}) 168 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC}) 169 .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC}) 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 .Default({ELFNoneKind, EM_NONE}); 182 183 if (ret.first == ELFNoneKind) 184 error("unknown emulation: " + emul); 185 if (ret.second == EM_MSP430) 186 osabi = ELFOSABI_STANDALONE; 187 else if (ret.second == EM_AMDGPU) 188 osabi = ELFOSABI_AMDGPU_HSA; 189 return std::make_tuple(ret.first, ret.second, osabi); 190 } 191 192 // Returns slices of MB by parsing MB as an archive file. 193 // Each slice consists of a member file in the archive. 194 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 195 MemoryBufferRef mb) { 196 std::unique_ptr<Archive> file = 197 CHECK(Archive::create(mb), 198 mb.getBufferIdentifier() + ": failed to parse archive"); 199 200 std::vector<std::pair<MemoryBufferRef, uint64_t>> v; 201 Error err = Error::success(); 202 bool addToTar = file->isThin() && tar; 203 for (const Archive::Child &c : file->children(err)) { 204 MemoryBufferRef mbref = 205 CHECK(c.getMemoryBufferRef(), 206 mb.getBufferIdentifier() + 207 ": could not get the buffer for a child of the archive"); 208 if (addToTar) 209 tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer()); 210 v.push_back(std::make_pair(mbref, c.getChildOffset())); 211 } 212 if (err) 213 fatal(mb.getBufferIdentifier() + ": Archive::children failed: " + 214 toString(std::move(err))); 215 216 // Take ownership of memory buffers created for members of thin archives. 217 std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers(); 218 std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers)); 219 220 return v; 221 } 222 223 static bool isBitcode(MemoryBufferRef mb) { 224 return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode; 225 } 226 227 // Opens a file and create a file object. Path has to be resolved already. 228 void LinkerDriver::addFile(StringRef path, bool withLOption) { 229 using namespace sys::fs; 230 231 std::optional<MemoryBufferRef> buffer = readFile(path); 232 if (!buffer) 233 return; 234 MemoryBufferRef mbref = *buffer; 235 236 if (config->formatBinary) { 237 files.push_back(make<BinaryFile>(mbref)); 238 return; 239 } 240 241 switch (identify_magic(mbref.getBuffer())) { 242 case file_magic::unknown: 243 readLinkerScript(mbref); 244 return; 245 case file_magic::archive: { 246 auto members = getArchiveMembers(mbref); 247 if (inWholeArchive) { 248 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) { 249 if (isBitcode(p.first)) 250 files.push_back(make<BitcodeFile>(p.first, path, p.second, false)); 251 else 252 files.push_back(createObjFile(p.first, path)); 253 } 254 return; 255 } 256 257 archiveFiles.emplace_back(path, members.size()); 258 259 // Handle archives and --start-lib/--end-lib using the same code path. This 260 // scans all the ELF relocatable object files and bitcode files in the 261 // archive rather than just the index file, with the benefit that the 262 // symbols are only loaded once. For many projects archives see high 263 // utilization rates and it is a net performance win. --start-lib scans 264 // symbols in the same order that llvm-ar adds them to the index, so in the 265 // common case the semantics are identical. If the archive symbol table was 266 // created in a different order, or is incomplete, this strategy has 267 // different semantics. Such output differences are considered user error. 268 // 269 // All files within the archive get the same group ID to allow mutual 270 // references for --warn-backrefs. 271 bool saved = InputFile::isInGroup; 272 InputFile::isInGroup = true; 273 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) { 274 auto magic = identify_magic(p.first.getBuffer()); 275 if (magic == file_magic::elf_relocatable) 276 files.push_back(createObjFile(p.first, path, true)); 277 else if (magic == file_magic::bitcode) 278 files.push_back(make<BitcodeFile>(p.first, path, p.second, true)); 279 else 280 warn(path + ": archive member '" + p.first.getBufferIdentifier() + 281 "' is neither ET_REL nor LLVM bitcode"); 282 } 283 InputFile::isInGroup = saved; 284 if (!saved) 285 ++InputFile::nextGroupId; 286 return; 287 } 288 case file_magic::elf_shared_object: { 289 if (config->isStatic || config->relocatable) { 290 error("attempted static link of dynamic object " + path); 291 return; 292 } 293 294 // Shared objects are identified by soname. soname is (if specified) 295 // DT_SONAME and falls back to filename. If a file was specified by -lfoo, 296 // the directory part is ignored. Note that path may be a temporary and 297 // cannot be stored into SharedFile::soName. 298 path = mbref.getBufferIdentifier(); 299 auto *f = 300 make<SharedFile>(mbref, withLOption ? path::filename(path) : path); 301 f->init(); 302 files.push_back(f); 303 return; 304 } 305 case file_magic::bitcode: 306 files.push_back(make<BitcodeFile>(mbref, "", 0, inLib)); 307 break; 308 case file_magic::elf_relocatable: 309 files.push_back(createObjFile(mbref, "", inLib)); 310 break; 311 default: 312 error(path + ": unknown file type"); 313 } 314 } 315 316 // Add a given library by searching it from input search paths. 317 void LinkerDriver::addLibrary(StringRef name) { 318 if (std::optional<std::string> path = searchLibrary(name)) 319 addFile(saver().save(*path), /*withLOption=*/true); 320 else 321 error("unable to find library -l" + name, ErrorTag::LibNotFound, {name}); 322 } 323 324 // This function is called on startup. We need this for LTO since 325 // LTO calls LLVM functions to compile bitcode files to native code. 326 // Technically this can be delayed until we read bitcode files, but 327 // we don't bother to do lazily because the initialization is fast. 328 static void initLLVM() { 329 InitializeAllTargets(); 330 InitializeAllTargetMCs(); 331 InitializeAllAsmPrinters(); 332 InitializeAllAsmParsers(); 333 } 334 335 // Some command line options or some combinations of them are not allowed. 336 // This function checks for such errors. 337 static void checkOptions() { 338 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 339 // table which is a relatively new feature. 340 if (config->emachine == EM_MIPS && config->gnuHash) 341 error("the .gnu.hash section is not compatible with the MIPS target"); 342 343 if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64) 344 error("--fix-cortex-a53-843419 is only supported on AArch64 targets"); 345 346 if (config->fixCortexA8 && config->emachine != EM_ARM) 347 error("--fix-cortex-a8 is only supported on ARM targets"); 348 349 if (config->tocOptimize && config->emachine != EM_PPC64) 350 error("--toc-optimize is only supported on PowerPC64 targets"); 351 352 if (config->pcRelOptimize && config->emachine != EM_PPC64) 353 error("--pcrel-optimize is only supported on PowerPC64 targets"); 354 355 if (config->pie && config->shared) 356 error("-shared and -pie may not be used together"); 357 358 if (!config->shared && !config->filterList.empty()) 359 error("-F may not be used without -shared"); 360 361 if (!config->shared && !config->auxiliaryList.empty()) 362 error("-f may not be used without -shared"); 363 364 if (config->strip == StripPolicy::All && config->emitRelocs) 365 error("--strip-all and --emit-relocs may not be used together"); 366 367 if (config->zText && config->zIfuncNoplt) 368 error("-z text and -z ifunc-noplt may not be used together"); 369 370 if (config->relocatable) { 371 if (config->shared) 372 error("-r and -shared may not be used together"); 373 if (config->gdbIndex) 374 error("-r and --gdb-index may not be used together"); 375 if (config->icf != ICFLevel::None) 376 error("-r and --icf may not be used together"); 377 if (config->pie) 378 error("-r and -pie may not be used together"); 379 if (config->exportDynamic) 380 error("-r and --export-dynamic may not be used together"); 381 } 382 383 if (config->executeOnly) { 384 if (config->emachine != EM_AARCH64) 385 error("--execute-only is only supported on AArch64 targets"); 386 387 if (config->singleRoRx && !script->hasSectionsCommand) 388 error("--execute-only and --no-rosegment cannot be used together"); 389 } 390 391 if (config->zRetpolineplt && config->zForceIbt) 392 error("-z force-ibt may not be used with -z retpolineplt"); 393 394 if (config->emachine != EM_AARCH64) { 395 if (config->zPacPlt) 396 error("-z pac-plt only supported on AArch64"); 397 if (config->zForceBti) 398 error("-z force-bti only supported on AArch64"); 399 if (config->zBtiReport != "none") 400 error("-z bti-report only supported on AArch64"); 401 } 402 403 if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 404 config->zCetReport != "none") 405 error("-z cet-report only supported on X86 and X86_64"); 406 } 407 408 static const char *getReproduceOption(opt::InputArgList &args) { 409 if (auto *arg = args.getLastArg(OPT_reproduce)) 410 return arg->getValue(); 411 return getenv("LLD_REPRODUCE"); 412 } 413 414 static bool hasZOption(opt::InputArgList &args, StringRef key) { 415 for (auto *arg : args.filtered(OPT_z)) 416 if (key == arg->getValue()) 417 return true; 418 return false; 419 } 420 421 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2, 422 bool Default) { 423 for (auto *arg : args.filtered_reverse(OPT_z)) { 424 if (k1 == arg->getValue()) 425 return true; 426 if (k2 == arg->getValue()) 427 return false; 428 } 429 return Default; 430 } 431 432 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) { 433 for (auto *arg : args.filtered_reverse(OPT_z)) { 434 StringRef v = arg->getValue(); 435 if (v == "noseparate-code") 436 return SeparateSegmentKind::None; 437 if (v == "separate-code") 438 return SeparateSegmentKind::Code; 439 if (v == "separate-loadable-segments") 440 return SeparateSegmentKind::Loadable; 441 } 442 return SeparateSegmentKind::None; 443 } 444 445 static GnuStackKind getZGnuStack(opt::InputArgList &args) { 446 for (auto *arg : args.filtered_reverse(OPT_z)) { 447 if (StringRef("execstack") == arg->getValue()) 448 return GnuStackKind::Exec; 449 if (StringRef("noexecstack") == arg->getValue()) 450 return GnuStackKind::NoExec; 451 if (StringRef("nognustack") == arg->getValue()) 452 return GnuStackKind::None; 453 } 454 455 return GnuStackKind::NoExec; 456 } 457 458 static uint8_t getZStartStopVisibility(opt::InputArgList &args) { 459 for (auto *arg : args.filtered_reverse(OPT_z)) { 460 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 461 if (kv.first == "start-stop-visibility") { 462 if (kv.second == "default") 463 return STV_DEFAULT; 464 else if (kv.second == "internal") 465 return STV_INTERNAL; 466 else if (kv.second == "hidden") 467 return STV_HIDDEN; 468 else if (kv.second == "protected") 469 return STV_PROTECTED; 470 error("unknown -z start-stop-visibility= value: " + StringRef(kv.second)); 471 } 472 } 473 return STV_PROTECTED; 474 } 475 476 constexpr const char *knownZFlags[] = { 477 "combreloc", 478 "copyreloc", 479 "defs", 480 "execstack", 481 "force-bti", 482 "force-ibt", 483 "global", 484 "hazardplt", 485 "ifunc-noplt", 486 "initfirst", 487 "interpose", 488 "keep-text-section-prefix", 489 "lazy", 490 "muldefs", 491 "nocombreloc", 492 "nocopyreloc", 493 "nodefaultlib", 494 "nodelete", 495 "nodlopen", 496 "noexecstack", 497 "nognustack", 498 "nokeep-text-section-prefix", 499 "nopack-relative-relocs", 500 "norelro", 501 "noseparate-code", 502 "nostart-stop-gc", 503 "notext", 504 "now", 505 "origin", 506 "pac-plt", 507 "pack-relative-relocs", 508 "rel", 509 "rela", 510 "relro", 511 "retpolineplt", 512 "rodynamic", 513 "separate-code", 514 "separate-loadable-segments", 515 "shstk", 516 "start-stop-gc", 517 "text", 518 "undefs", 519 "wxneeded", 520 }; 521 522 static bool isKnownZFlag(StringRef s) { 523 return llvm::is_contained(knownZFlags, s) || 524 s.startswith("common-page-size=") || s.startswith("bti-report=") || 525 s.startswith("cet-report=") || 526 s.startswith("dead-reloc-in-nonalloc=") || 527 s.startswith("max-page-size=") || s.startswith("stack-size=") || 528 s.startswith("start-stop-visibility="); 529 } 530 531 // Report a warning for an unknown -z option. 532 static void checkZOptions(opt::InputArgList &args) { 533 for (auto *arg : args.filtered(OPT_z)) 534 if (!isKnownZFlag(arg->getValue())) 535 warn("unknown -z value: " + StringRef(arg->getValue())); 536 } 537 538 constexpr const char *saveTempsValues[] = { 539 "resolution", "preopt", "promote", "internalize", "import", 540 "opt", "precodegen", "prelink", "combinedindex"}; 541 542 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 543 ELFOptTable parser; 544 opt::InputArgList args = parser.parse(argsArr.slice(1)); 545 546 // Interpret these flags early because error()/warn() depend on them. 547 errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20); 548 errorHandler().fatalWarnings = 549 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) && 550 !args.hasArg(OPT_no_warnings); 551 errorHandler().suppressWarnings = args.hasArg(OPT_no_warnings); 552 checkZOptions(args); 553 554 // Handle -help 555 if (args.hasArg(OPT_help)) { 556 printHelp(); 557 return; 558 } 559 560 // Handle -v or -version. 561 // 562 // A note about "compatible with GNU linkers" message: this is a hack for 563 // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as 564 // a GNU compatible linker. See 565 // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>. 566 // 567 // This is somewhat ugly hack, but in reality, we had no choice other 568 // than doing this. Considering the very long release cycle of Libtool, 569 // it is not easy to improve it to recognize LLD as a GNU compatible 570 // linker in a timely manner. Even if we can make it, there are still a 571 // lot of "configure" scripts out there that are generated by old version 572 // of Libtool. We cannot convince every software developer to migrate to 573 // the latest version and re-generate scripts. So we have this hack. 574 if (args.hasArg(OPT_v) || args.hasArg(OPT_version)) 575 message(getLLDVersion() + " (compatible with GNU linkers)"); 576 577 if (const char *path = getReproduceOption(args)) { 578 // Note that --reproduce is a debug option so you can ignore it 579 // if you are trying to understand the whole picture of the code. 580 Expected<std::unique_ptr<TarWriter>> errOrWriter = 581 TarWriter::create(path, path::stem(path)); 582 if (errOrWriter) { 583 tar = std::move(*errOrWriter); 584 tar->append("response.txt", createResponseFile(args)); 585 tar->append("version.txt", getLLDVersion() + "\n"); 586 StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 587 if (!ltoSampleProfile.empty()) 588 readFile(ltoSampleProfile); 589 } else { 590 error("--reproduce: " + toString(errOrWriter.takeError())); 591 } 592 } 593 594 readConfigs(args); 595 596 // The behavior of -v or --version is a bit strange, but this is 597 // needed for compatibility with GNU linkers. 598 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT)) 599 return; 600 if (args.hasArg(OPT_version)) 601 return; 602 603 // Initialize time trace profiler. 604 if (config->timeTraceEnabled) 605 timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName); 606 607 { 608 llvm::TimeTraceScope timeScope("ExecuteLinker"); 609 610 initLLVM(); 611 createFiles(args); 612 if (errorCount()) 613 return; 614 615 inferMachineType(); 616 setConfigs(args); 617 checkOptions(); 618 if (errorCount()) 619 return; 620 621 link(args); 622 } 623 624 if (config->timeTraceEnabled) { 625 checkError(timeTraceProfilerWrite( 626 args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile)); 627 timeTraceProfilerCleanup(); 628 } 629 } 630 631 static std::string getRpath(opt::InputArgList &args) { 632 SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath); 633 return llvm::join(v.begin(), v.end(), ":"); 634 } 635 636 // Determines what we should do if there are remaining unresolved 637 // symbols after the name resolution. 638 static void setUnresolvedSymbolPolicy(opt::InputArgList &args) { 639 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols, 640 OPT_warn_unresolved_symbols, true) 641 ? UnresolvedPolicy::ReportError 642 : UnresolvedPolicy::Warn; 643 // -shared implies --unresolved-symbols=ignore-all because missing 644 // symbols are likely to be resolved at runtime. 645 bool diagRegular = !config->shared, diagShlib = !config->shared; 646 647 for (const opt::Arg *arg : args) { 648 switch (arg->getOption().getID()) { 649 case OPT_unresolved_symbols: { 650 StringRef s = arg->getValue(); 651 if (s == "ignore-all") { 652 diagRegular = false; 653 diagShlib = false; 654 } else if (s == "ignore-in-object-files") { 655 diagRegular = false; 656 diagShlib = true; 657 } else if (s == "ignore-in-shared-libs") { 658 diagRegular = true; 659 diagShlib = false; 660 } else if (s == "report-all") { 661 diagRegular = true; 662 diagShlib = true; 663 } else { 664 error("unknown --unresolved-symbols value: " + s); 665 } 666 break; 667 } 668 case OPT_no_undefined: 669 diagRegular = true; 670 break; 671 case OPT_z: 672 if (StringRef(arg->getValue()) == "defs") 673 diagRegular = true; 674 else if (StringRef(arg->getValue()) == "undefs") 675 diagRegular = false; 676 break; 677 case OPT_allow_shlib_undefined: 678 diagShlib = false; 679 break; 680 case OPT_no_allow_shlib_undefined: 681 diagShlib = true; 682 break; 683 } 684 } 685 686 config->unresolvedSymbols = 687 diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore; 688 config->unresolvedSymbolsInShlib = 689 diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore; 690 } 691 692 static Target2Policy getTarget2(opt::InputArgList &args) { 693 StringRef s = args.getLastArgValue(OPT_target2, "got-rel"); 694 if (s == "rel") 695 return Target2Policy::Rel; 696 if (s == "abs") 697 return Target2Policy::Abs; 698 if (s == "got-rel") 699 return Target2Policy::GotRel; 700 error("unknown --target2 option: " + s); 701 return Target2Policy::GotRel; 702 } 703 704 static bool isOutputFormatBinary(opt::InputArgList &args) { 705 StringRef s = args.getLastArgValue(OPT_oformat, "elf"); 706 if (s == "binary") 707 return true; 708 if (!s.startswith("elf")) 709 error("unknown --oformat value: " + s); 710 return false; 711 } 712 713 static DiscardPolicy getDiscard(opt::InputArgList &args) { 714 auto *arg = 715 args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 716 if (!arg) 717 return DiscardPolicy::Default; 718 if (arg->getOption().getID() == OPT_discard_all) 719 return DiscardPolicy::All; 720 if (arg->getOption().getID() == OPT_discard_locals) 721 return DiscardPolicy::Locals; 722 return DiscardPolicy::None; 723 } 724 725 static StringRef getDynamicLinker(opt::InputArgList &args) { 726 auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 727 if (!arg) 728 return ""; 729 if (arg->getOption().getID() == OPT_no_dynamic_linker) { 730 // --no-dynamic-linker suppresses undefined weak symbols in .dynsym 731 config->noDynamicLinker = true; 732 return ""; 733 } 734 return arg->getValue(); 735 } 736 737 static int getMemtagMode(opt::InputArgList &args) { 738 StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode); 739 if (!config->androidMemtagHeap && !config->androidMemtagStack) { 740 if (!memtagModeArg.empty()) 741 error("when using --android-memtag-mode, at least one of " 742 "--android-memtag-heap or " 743 "--android-memtag-stack is required"); 744 return ELF::NT_MEMTAG_LEVEL_NONE; 745 } 746 747 if (memtagModeArg == "sync" || memtagModeArg.empty()) 748 return ELF::NT_MEMTAG_LEVEL_SYNC; 749 if (memtagModeArg == "async") 750 return ELF::NT_MEMTAG_LEVEL_ASYNC; 751 if (memtagModeArg == "none") 752 return ELF::NT_MEMTAG_LEVEL_NONE; 753 754 error("unknown --android-memtag-mode value: \"" + memtagModeArg + 755 "\", should be one of {async, sync, none}"); 756 return ELF::NT_MEMTAG_LEVEL_NONE; 757 } 758 759 static ICFLevel getICF(opt::InputArgList &args) { 760 auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all); 761 if (!arg || arg->getOption().getID() == OPT_icf_none) 762 return ICFLevel::None; 763 if (arg->getOption().getID() == OPT_icf_safe) 764 return ICFLevel::Safe; 765 return ICFLevel::All; 766 } 767 768 static StripPolicy getStrip(opt::InputArgList &args) { 769 if (args.hasArg(OPT_relocatable)) 770 return StripPolicy::None; 771 772 auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug); 773 if (!arg) 774 return StripPolicy::None; 775 if (arg->getOption().getID() == OPT_strip_all) 776 return StripPolicy::All; 777 return StripPolicy::Debug; 778 } 779 780 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args, 781 const opt::Arg &arg) { 782 uint64_t va = 0; 783 if (s.startswith("0x")) 784 s = s.drop_front(2); 785 if (!to_integer(s, va, 16)) 786 error("invalid argument: " + arg.getAsString(args)); 787 return va; 788 } 789 790 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) { 791 StringMap<uint64_t> ret; 792 for (auto *arg : args.filtered(OPT_section_start)) { 793 StringRef name; 794 StringRef addr; 795 std::tie(name, addr) = StringRef(arg->getValue()).split('='); 796 ret[name] = parseSectionAddress(addr, args, *arg); 797 } 798 799 if (auto *arg = args.getLastArg(OPT_Ttext)) 800 ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg); 801 if (auto *arg = args.getLastArg(OPT_Tdata)) 802 ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg); 803 if (auto *arg = args.getLastArg(OPT_Tbss)) 804 ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg); 805 return ret; 806 } 807 808 static SortSectionPolicy getSortSection(opt::InputArgList &args) { 809 StringRef s = args.getLastArgValue(OPT_sort_section); 810 if (s == "alignment") 811 return SortSectionPolicy::Alignment; 812 if (s == "name") 813 return SortSectionPolicy::Name; 814 if (!s.empty()) 815 error("unknown --sort-section rule: " + s); 816 return SortSectionPolicy::Default; 817 } 818 819 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) { 820 StringRef s = args.getLastArgValue(OPT_orphan_handling, "place"); 821 if (s == "warn") 822 return OrphanHandlingPolicy::Warn; 823 if (s == "error") 824 return OrphanHandlingPolicy::Error; 825 if (s != "place") 826 error("unknown --orphan-handling mode: " + s); 827 return OrphanHandlingPolicy::Place; 828 } 829 830 // Parse --build-id or --build-id=<style>. We handle "tree" as a 831 // synonym for "sha1" because all our hash functions including 832 // --build-id=sha1 are actually tree hashes for performance reasons. 833 static std::pair<BuildIdKind, SmallVector<uint8_t, 0>> 834 getBuildId(opt::InputArgList &args) { 835 auto *arg = args.getLastArg(OPT_build_id); 836 if (!arg) 837 return {BuildIdKind::None, {}}; 838 839 StringRef s = arg->getValue(); 840 if (s == "fast") 841 return {BuildIdKind::Fast, {}}; 842 if (s == "md5") 843 return {BuildIdKind::Md5, {}}; 844 if (s == "sha1" || s == "tree") 845 return {BuildIdKind::Sha1, {}}; 846 if (s == "uuid") 847 return {BuildIdKind::Uuid, {}}; 848 if (s.startswith("0x")) 849 return {BuildIdKind::Hexstring, parseHex(s.substr(2))}; 850 851 if (s != "none") 852 error("unknown --build-id style: " + s); 853 return {BuildIdKind::None, {}}; 854 } 855 856 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) { 857 StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none"); 858 if (s == "android") 859 return {true, false}; 860 if (s == "relr") 861 return {false, true}; 862 if (s == "android+relr") 863 return {true, true}; 864 865 if (s != "none") 866 error("unknown --pack-dyn-relocs format: " + s); 867 return {false, false}; 868 } 869 870 static void readCallGraph(MemoryBufferRef mb) { 871 // Build a map from symbol name to section 872 DenseMap<StringRef, Symbol *> map; 873 for (ELFFileBase *file : ctx.objectFiles) 874 for (Symbol *sym : file->getSymbols()) 875 map[sym->getName()] = sym; 876 877 auto findSection = [&](StringRef name) -> InputSectionBase * { 878 Symbol *sym = map.lookup(name); 879 if (!sym) { 880 if (config->warnSymbolOrdering) 881 warn(mb.getBufferIdentifier() + ": no such symbol: " + name); 882 return nullptr; 883 } 884 maybeWarnUnorderableSymbol(sym); 885 886 if (Defined *dr = dyn_cast_or_null<Defined>(sym)) 887 return dyn_cast_or_null<InputSectionBase>(dr->section); 888 return nullptr; 889 }; 890 891 for (StringRef line : args::getLines(mb)) { 892 SmallVector<StringRef, 3> fields; 893 line.split(fields, ' '); 894 uint64_t count; 895 896 if (fields.size() != 3 || !to_integer(fields[2], count)) { 897 error(mb.getBufferIdentifier() + ": parse error"); 898 return; 899 } 900 901 if (InputSectionBase *from = findSection(fields[0])) 902 if (InputSectionBase *to = findSection(fields[1])) 903 config->callGraphProfile[std::make_pair(from, to)] += count; 904 } 905 } 906 907 // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns 908 // true and populates cgProfile and symbolIndices. 909 template <class ELFT> 910 static bool 911 processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices, 912 ArrayRef<typename ELFT::CGProfile> &cgProfile, 913 ObjFile<ELFT> *inputObj) { 914 if (inputObj->cgProfileSectionIndex == SHN_UNDEF) 915 return false; 916 917 ArrayRef<Elf_Shdr_Impl<ELFT>> objSections = 918 inputObj->template getELFShdrs<ELFT>(); 919 symbolIndices.clear(); 920 const ELFFile<ELFT> &obj = inputObj->getObj(); 921 cgProfile = 922 check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>( 923 objSections[inputObj->cgProfileSectionIndex])); 924 925 for (size_t i = 0, e = objSections.size(); i < e; ++i) { 926 const Elf_Shdr_Impl<ELFT> &sec = objSections[i]; 927 if (sec.sh_info == inputObj->cgProfileSectionIndex) { 928 if (sec.sh_type == SHT_RELA) { 929 ArrayRef<typename ELFT::Rela> relas = 930 CHECK(obj.relas(sec), "could not retrieve cg profile rela section"); 931 for (const typename ELFT::Rela &rel : relas) 932 symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 933 break; 934 } 935 if (sec.sh_type == SHT_REL) { 936 ArrayRef<typename ELFT::Rel> rels = 937 CHECK(obj.rels(sec), "could not retrieve cg profile rel section"); 938 for (const typename ELFT::Rel &rel : rels) 939 symbolIndices.push_back(rel.getSymbol(config->isMips64EL)); 940 break; 941 } 942 } 943 } 944 if (symbolIndices.empty()) 945 warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't"); 946 return !symbolIndices.empty(); 947 } 948 949 template <class ELFT> static void readCallGraphsFromObjectFiles() { 950 SmallVector<uint32_t, 32> symbolIndices; 951 ArrayRef<typename ELFT::CGProfile> cgProfile; 952 for (auto file : ctx.objectFiles) { 953 auto *obj = cast<ObjFile<ELFT>>(file); 954 if (!processCallGraphRelocations(symbolIndices, cgProfile, obj)) 955 continue; 956 957 if (symbolIndices.size() != cgProfile.size() * 2) 958 fatal("number of relocations doesn't match Weights"); 959 960 for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) { 961 const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i]; 962 uint32_t fromIndex = symbolIndices[i * 2]; 963 uint32_t toIndex = symbolIndices[i * 2 + 1]; 964 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex)); 965 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex)); 966 if (!fromSym || !toSym) 967 continue; 968 969 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section); 970 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section); 971 if (from && to) 972 config->callGraphProfile[{from, to}] += cgpe.cgp_weight; 973 } 974 } 975 } 976 977 static DebugCompressionType getCompressDebugSections(opt::InputArgList &args) { 978 StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none"); 979 if (s == "zlib") { 980 if (!compression::zlib::isAvailable()) 981 error("--compress-debug-sections: zlib is not available"); 982 return DebugCompressionType::Zlib; 983 } 984 if (s == "zstd") { 985 if (!compression::zstd::isAvailable()) 986 error("--compress-debug-sections: zstd is not available"); 987 return DebugCompressionType::Zstd; 988 } 989 if (s != "none") 990 error("unknown --compress-debug-sections value: " + s); 991 return DebugCompressionType::None; 992 } 993 994 static StringRef getAliasSpelling(opt::Arg *arg) { 995 if (const opt::Arg *alias = arg->getAlias()) 996 return alias->getSpelling(); 997 return arg->getSpelling(); 998 } 999 1000 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 1001 unsigned id) { 1002 auto *arg = args.getLastArg(id); 1003 if (!arg) 1004 return {"", ""}; 1005 1006 StringRef s = arg->getValue(); 1007 std::pair<StringRef, StringRef> ret = s.split(';'); 1008 if (ret.second.empty()) 1009 error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s); 1010 return ret; 1011 } 1012 1013 // Parse the symbol ordering file and warn for any duplicate entries. 1014 static SmallVector<StringRef, 0> getSymbolOrderingFile(MemoryBufferRef mb) { 1015 SetVector<StringRef, SmallVector<StringRef, 0>> names; 1016 for (StringRef s : args::getLines(mb)) 1017 if (!names.insert(s) && config->warnSymbolOrdering) 1018 warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s); 1019 1020 return names.takeVector(); 1021 } 1022 1023 static bool getIsRela(opt::InputArgList &args) { 1024 // If -z rel or -z rela is specified, use the last option. 1025 for (auto *arg : args.filtered_reverse(OPT_z)) { 1026 StringRef s(arg->getValue()); 1027 if (s == "rel") 1028 return false; 1029 if (s == "rela") 1030 return true; 1031 } 1032 1033 // Otherwise use the psABI defined relocation entry format. 1034 uint16_t m = config->emachine; 1035 return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC || 1036 m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64; 1037 } 1038 1039 static void parseClangOption(StringRef opt, const Twine &msg) { 1040 std::string err; 1041 raw_string_ostream os(err); 1042 1043 const char *argv[] = {config->progName.data(), opt.data()}; 1044 if (cl::ParseCommandLineOptions(2, argv, "", &os)) 1045 return; 1046 os.flush(); 1047 error(msg + ": " + StringRef(err).trim()); 1048 } 1049 1050 // Checks the parameter of the bti-report and cet-report options. 1051 static bool isValidReportString(StringRef arg) { 1052 return arg == "none" || arg == "warning" || arg == "error"; 1053 } 1054 1055 // Initializes Config members by the command line options. 1056 static void readConfigs(opt::InputArgList &args) { 1057 errorHandler().verbose = args.hasArg(OPT_verbose); 1058 errorHandler().vsDiagnostics = 1059 args.hasArg(OPT_visual_studio_diagnostics_format, false); 1060 1061 config->allowMultipleDefinition = 1062 args.hasFlag(OPT_allow_multiple_definition, 1063 OPT_no_allow_multiple_definition, false) || 1064 hasZOption(args, "muldefs"); 1065 config->androidMemtagHeap = 1066 args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false); 1067 config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack, 1068 OPT_no_android_memtag_stack, false); 1069 config->androidMemtagMode = getMemtagMode(args); 1070 config->auxiliaryList = args::getStrings(args, OPT_auxiliary); 1071 if (opt::Arg *arg = 1072 args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions, 1073 OPT_Bsymbolic_functions, OPT_Bsymbolic)) { 1074 if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions)) 1075 config->bsymbolic = BsymbolicKind::NonWeakFunctions; 1076 else if (arg->getOption().matches(OPT_Bsymbolic_functions)) 1077 config->bsymbolic = BsymbolicKind::Functions; 1078 else if (arg->getOption().matches(OPT_Bsymbolic)) 1079 config->bsymbolic = BsymbolicKind::All; 1080 } 1081 config->checkSections = 1082 args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 1083 config->chroot = args.getLastArgValue(OPT_chroot); 1084 config->compressDebugSections = getCompressDebugSections(args); 1085 config->cref = args.hasArg(OPT_cref); 1086 config->optimizeBBJumps = 1087 args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false); 1088 config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true); 1089 config->dependencyFile = args.getLastArgValue(OPT_dependency_file); 1090 config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true); 1091 config->disableVerify = args.hasArg(OPT_disable_verify); 1092 config->discard = getDiscard(args); 1093 config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq); 1094 config->dynamicLinker = getDynamicLinker(args); 1095 config->ehFrameHdr = 1096 args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 1097 config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false); 1098 config->emitRelocs = args.hasArg(OPT_emit_relocs); 1099 config->callGraphProfileSort = args.hasFlag( 1100 OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true); 1101 config->enableNewDtags = 1102 args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 1103 config->entry = args.getLastArgValue(OPT_entry); 1104 1105 errorHandler().errorHandlingScript = 1106 args.getLastArgValue(OPT_error_handling_script); 1107 1108 config->executeOnly = 1109 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 1110 config->exportDynamic = 1111 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) || 1112 args.hasArg(OPT_shared); 1113 config->filterList = args::getStrings(args, OPT_filter); 1114 config->fini = args.getLastArgValue(OPT_fini, "_fini"); 1115 config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) && 1116 !args.hasArg(OPT_relocatable); 1117 config->fixCortexA8 = 1118 args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable); 1119 config->fortranCommon = 1120 args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false); 1121 config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 1122 config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 1123 config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 1124 config->icf = getICF(args); 1125 config->ignoreDataAddressEquality = 1126 args.hasArg(OPT_ignore_data_address_equality); 1127 config->ignoreFunctionAddressEquality = 1128 args.hasArg(OPT_ignore_function_address_equality); 1129 config->init = args.getLastArgValue(OPT_init, "_init"); 1130 config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline); 1131 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1132 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 1133 config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1134 OPT_no_lto_pgo_warn_mismatch, true); 1135 config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager); 1136 config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm); 1137 config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes); 1138 config->ltoWholeProgramVisibility = 1139 args.hasFlag(OPT_lto_whole_program_visibility, 1140 OPT_no_lto_whole_program_visibility, false); 1141 config->ltoo = args::getInteger(args, OPT_lto_O, 2); 1142 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq); 1143 config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1); 1144 config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 1145 config->ltoBasicBlockSections = 1146 args.getLastArgValue(OPT_lto_basic_block_sections); 1147 config->ltoUniqueBasicBlockSectionNames = 1148 args.hasFlag(OPT_lto_unique_basic_block_section_names, 1149 OPT_no_lto_unique_basic_block_section_names, false); 1150 config->mapFile = args.getLastArgValue(OPT_Map); 1151 config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0); 1152 config->mergeArmExidx = 1153 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 1154 config->mmapOutputFile = 1155 args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true); 1156 config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 1157 config->noinhibitExec = args.hasArg(OPT_noinhibit_exec); 1158 config->nostdlib = args.hasArg(OPT_nostdlib); 1159 config->oFormatBinary = isOutputFormatBinary(args); 1160 config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false); 1161 config->opaquePointers = args.hasFlag( 1162 OPT_plugin_opt_opaque_pointers, OPT_plugin_opt_no_opaque_pointers, true); 1163 config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename); 1164 config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file); 1165 1166 // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 1167 if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) { 1168 auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue()); 1169 if (!resultOrErr) 1170 error(arg->getSpelling() + ": invalid argument '" + arg->getValue() + 1171 "', only integer or 'auto' is supported"); 1172 else 1173 config->optRemarksHotnessThreshold = *resultOrErr; 1174 } 1175 1176 config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes); 1177 config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness); 1178 config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format); 1179 config->optimize = args::getInteger(args, OPT_O, 1); 1180 config->orphanHandling = getOrphanHandling(args); 1181 config->outputFile = args.getLastArgValue(OPT_o); 1182 config->packageMetadata = args.getLastArgValue(OPT_package_metadata); 1183 config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false); 1184 config->printIcfSections = 1185 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 1186 config->printGcSections = 1187 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 1188 config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats); 1189 config->printSymbolOrder = 1190 args.getLastArgValue(OPT_print_symbol_order); 1191 config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true); 1192 config->rpath = getRpath(args); 1193 config->relocatable = args.hasArg(OPT_relocatable); 1194 1195 if (args.hasArg(OPT_save_temps)) { 1196 // --save-temps implies saving all temps. 1197 for (const char *s : saveTempsValues) 1198 config->saveTempsArgs.insert(s); 1199 } else { 1200 for (auto *arg : args.filtered(OPT_save_temps_eq)) { 1201 StringRef s = arg->getValue(); 1202 if (llvm::is_contained(saveTempsValues, s)) 1203 config->saveTempsArgs.insert(s); 1204 else 1205 error("unknown --save-temps value: " + s); 1206 } 1207 } 1208 1209 config->searchPaths = args::getStrings(args, OPT_library_path); 1210 config->sectionStartMap = getSectionStartMap(args); 1211 config->shared = args.hasArg(OPT_shared); 1212 config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true); 1213 config->soName = args.getLastArgValue(OPT_soname); 1214 config->sortSection = getSortSection(args); 1215 config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384); 1216 config->strip = getStrip(args); 1217 config->sysroot = args.getLastArgValue(OPT_sysroot); 1218 config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 1219 config->target2 = getTarget2(args); 1220 config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir); 1221 config->thinLTOCachePolicy = CHECK( 1222 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)), 1223 "--thinlto-cache-policy: invalid cache policy"); 1224 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 1225 config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) || 1226 args.hasArg(OPT_thinlto_index_only) || 1227 args.hasArg(OPT_thinlto_index_only_eq); 1228 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 1229 args.hasArg(OPT_thinlto_index_only_eq); 1230 config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq); 1231 config->thinLTOObjectSuffixReplace = 1232 getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq); 1233 config->thinLTOPrefixReplace = 1234 getOldNewOptions(args, OPT_thinlto_prefix_replace_eq); 1235 if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) { 1236 if (args.hasArg(OPT_thinlto_object_suffix_replace_eq)) 1237 error("--thinlto-object-suffix-replace is not supported with " 1238 "--thinlto-emit-index-files"); 1239 else if (args.hasArg(OPT_thinlto_prefix_replace_eq)) 1240 error("--thinlto-prefix-replace is not supported with " 1241 "--thinlto-emit-index-files"); 1242 } 1243 config->thinLTOModulesToCompile = 1244 args::getStrings(args, OPT_thinlto_single_module_eq); 1245 config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq); 1246 config->timeTraceGranularity = 1247 args::getInteger(args, OPT_time_trace_granularity, 500); 1248 config->trace = args.hasArg(OPT_trace); 1249 config->undefined = args::getStrings(args, OPT_undefined); 1250 config->undefinedVersion = 1251 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false); 1252 config->unique = args.hasArg(OPT_unique); 1253 config->useAndroidRelrTags = args.hasFlag( 1254 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 1255 config->warnBackrefs = 1256 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 1257 config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 1258 config->warnSymbolOrdering = 1259 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 1260 config->whyExtract = args.getLastArgValue(OPT_why_extract); 1261 config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true); 1262 config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true); 1263 config->zForceBti = hasZOption(args, "force-bti"); 1264 config->zForceIbt = hasZOption(args, "force-ibt"); 1265 config->zGlobal = hasZOption(args, "global"); 1266 config->zGnustack = getZGnuStack(args); 1267 config->zHazardplt = hasZOption(args, "hazardplt"); 1268 config->zIfuncNoplt = hasZOption(args, "ifunc-noplt"); 1269 config->zInitfirst = hasZOption(args, "initfirst"); 1270 config->zInterpose = hasZOption(args, "interpose"); 1271 config->zKeepTextSectionPrefix = getZFlag( 1272 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 1273 config->zNodefaultlib = hasZOption(args, "nodefaultlib"); 1274 config->zNodelete = hasZOption(args, "nodelete"); 1275 config->zNodlopen = hasZOption(args, "nodlopen"); 1276 config->zNow = getZFlag(args, "now", "lazy", false); 1277 config->zOrigin = hasZOption(args, "origin"); 1278 config->zPacPlt = hasZOption(args, "pac-plt"); 1279 config->zRelro = getZFlag(args, "relro", "norelro", true); 1280 config->zRetpolineplt = hasZOption(args, "retpolineplt"); 1281 config->zRodynamic = hasZOption(args, "rodynamic"); 1282 config->zSeparate = getZSeparate(args); 1283 config->zShstk = hasZOption(args, "shstk"); 1284 config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0); 1285 config->zStartStopGC = 1286 getZFlag(args, "start-stop-gc", "nostart-stop-gc", true); 1287 config->zStartStopVisibility = getZStartStopVisibility(args); 1288 config->zText = getZFlag(args, "text", "notext", true); 1289 config->zWxneeded = hasZOption(args, "wxneeded"); 1290 setUnresolvedSymbolPolicy(args); 1291 config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no"; 1292 1293 if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) { 1294 if (arg->getOption().matches(OPT_eb)) 1295 config->optEB = true; 1296 else 1297 config->optEL = true; 1298 } 1299 1300 for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) { 1301 constexpr StringRef errPrefix = "--shuffle-sections=: "; 1302 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 1303 if (kv.first.empty() || kv.second.empty()) { 1304 error(errPrefix + "expected <section_glob>=<seed>, but got '" + 1305 arg->getValue() + "'"); 1306 continue; 1307 } 1308 // Signed so that <section_glob>=-1 is allowed. 1309 int64_t v; 1310 if (!to_integer(kv.second, v)) 1311 error(errPrefix + "expected an integer, but got '" + kv.second + "'"); 1312 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1313 config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v)); 1314 else 1315 error(errPrefix + toString(pat.takeError())); 1316 } 1317 1318 auto reports = {std::make_pair("bti-report", &config->zBtiReport), 1319 std::make_pair("cet-report", &config->zCetReport)}; 1320 for (opt::Arg *arg : args.filtered(OPT_z)) { 1321 std::pair<StringRef, StringRef> option = 1322 StringRef(arg->getValue()).split('='); 1323 for (auto reportArg : reports) { 1324 if (option.first != reportArg.first) 1325 continue; 1326 if (!isValidReportString(option.second)) { 1327 error(Twine("-z ") + reportArg.first + "= parameter " + option.second + 1328 " is not recognized"); 1329 continue; 1330 } 1331 *reportArg.second = option.second; 1332 } 1333 } 1334 1335 for (opt::Arg *arg : args.filtered(OPT_z)) { 1336 std::pair<StringRef, StringRef> option = 1337 StringRef(arg->getValue()).split('='); 1338 if (option.first != "dead-reloc-in-nonalloc") 1339 continue; 1340 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: "; 1341 std::pair<StringRef, StringRef> kv = option.second.split('='); 1342 if (kv.first.empty() || kv.second.empty()) { 1343 error(errPrefix + "expected <section_glob>=<value>"); 1344 continue; 1345 } 1346 uint64_t v; 1347 if (!to_integer(kv.second, v)) 1348 error(errPrefix + "expected a non-negative integer, but got '" + 1349 kv.second + "'"); 1350 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1351 config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v); 1352 else 1353 error(errPrefix + toString(pat.takeError())); 1354 } 1355 1356 cl::ResetAllOptionOccurrences(); 1357 1358 // Parse LTO options. 1359 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq)) 1360 parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())), 1361 arg->getSpelling()); 1362 1363 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus)) 1364 parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling()); 1365 1366 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or 1367 // relative path. Just ignore. If not ended with "lto-wrapper" (or 1368 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an 1369 // unsupported LLVMgold.so option and error. 1370 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) { 1371 StringRef v(arg->getValue()); 1372 if (!v.endswith("lto-wrapper") && !v.endswith("lto-wrapper.exe")) 1373 error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() + 1374 "'"); 1375 } 1376 1377 config->passPlugins = args::getStrings(args, OPT_load_pass_plugins); 1378 1379 // Parse -mllvm options. 1380 for (const auto *arg : args.filtered(OPT_mllvm)) { 1381 parseClangOption(arg->getValue(), arg->getSpelling()); 1382 config->mllvmOpts.emplace_back(arg->getValue()); 1383 } 1384 1385 // --threads= takes a positive integer and provides the default value for 1386 // --thinlto-jobs=. 1387 if (auto *arg = args.getLastArg(OPT_threads)) { 1388 StringRef v(arg->getValue()); 1389 unsigned threads = 0; 1390 if (!llvm::to_integer(v, threads, 0) || threads == 0) 1391 error(arg->getSpelling() + ": expected a positive integer, but got '" + 1392 arg->getValue() + "'"); 1393 parallel::strategy = hardware_concurrency(threads); 1394 config->thinLTOJobs = v; 1395 } 1396 if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq)) 1397 config->thinLTOJobs = arg->getValue(); 1398 config->threadCount = parallel::strategy.compute_thread_count(); 1399 1400 if (config->ltoo > 3) 1401 error("invalid optimization level for LTO: " + Twine(config->ltoo)); 1402 if (config->ltoPartitions == 0) 1403 error("--lto-partitions: number of threads must be > 0"); 1404 if (!get_threadpool_strategy(config->thinLTOJobs)) 1405 error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 1406 1407 if (config->splitStackAdjustSize < 0) 1408 error("--split-stack-adjust-size: size must be >= 0"); 1409 1410 // The text segment is traditionally the first segment, whose address equals 1411 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment 1412 // is an old-fashioned option that does not play well with lld's layout. 1413 // Suggest --image-base as a likely alternative. 1414 if (args.hasArg(OPT_Ttext_segment)) 1415 error("-Ttext-segment is not supported. Use --image-base if you " 1416 "intend to set the base address"); 1417 1418 // Parse ELF{32,64}{LE,BE} and CPU type. 1419 if (auto *arg = args.getLastArg(OPT_m)) { 1420 StringRef s = arg->getValue(); 1421 std::tie(config->ekind, config->emachine, config->osabi) = 1422 parseEmulation(s); 1423 config->mipsN32Abi = 1424 (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32")); 1425 config->emulation = s; 1426 } 1427 1428 // Parse --hash-style={sysv,gnu,both}. 1429 if (auto *arg = args.getLastArg(OPT_hash_style)) { 1430 StringRef s = arg->getValue(); 1431 if (s == "sysv") 1432 config->sysvHash = true; 1433 else if (s == "gnu") 1434 config->gnuHash = true; 1435 else if (s == "both") 1436 config->sysvHash = config->gnuHash = true; 1437 else 1438 error("unknown --hash-style: " + s); 1439 } 1440 1441 if (args.hasArg(OPT_print_map)) 1442 config->mapFile = "-"; 1443 1444 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 1445 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 1446 // it. 1447 if (config->nmagic || config->omagic) 1448 config->zRelro = false; 1449 1450 std::tie(config->buildId, config->buildIdVector) = getBuildId(args); 1451 1452 if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) { 1453 config->relrGlibc = true; 1454 config->relrPackDynRelocs = true; 1455 } else { 1456 std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) = 1457 getPackDynRelocs(args); 1458 } 1459 1460 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){ 1461 if (args.hasArg(OPT_call_graph_ordering_file)) 1462 error("--symbol-ordering-file and --call-graph-order-file " 1463 "may not be used together"); 1464 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) { 1465 config->symbolOrderingFile = getSymbolOrderingFile(*buffer); 1466 // Also need to disable CallGraphProfileSort to prevent 1467 // LLD order symbols with CGProfile 1468 config->callGraphProfileSort = false; 1469 } 1470 } 1471 1472 assert(config->versionDefinitions.empty()); 1473 config->versionDefinitions.push_back( 1474 {"local", (uint16_t)VER_NDX_LOCAL, {}, {}}); 1475 config->versionDefinitions.push_back( 1476 {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}}); 1477 1478 // If --retain-symbol-file is used, we'll keep only the symbols listed in 1479 // the file and discard all others. 1480 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) { 1481 config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back( 1482 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true}); 1483 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1484 for (StringRef s : args::getLines(*buffer)) 1485 config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back( 1486 {s, /*isExternCpp=*/false, /*hasWildcard=*/false}); 1487 } 1488 1489 for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) { 1490 StringRef pattern(arg->getValue()); 1491 if (Expected<GlobPattern> pat = GlobPattern::create(pattern)) 1492 config->warnBackrefsExclude.push_back(std::move(*pat)); 1493 else 1494 error(arg->getSpelling() + ": " + toString(pat.takeError())); 1495 } 1496 1497 // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols 1498 // which should be exported. For -shared, references to matched non-local 1499 // STV_DEFAULT symbols are not bound to definitions within the shared object, 1500 // even if other options express a symbolic intention: -Bsymbolic, 1501 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list. 1502 for (auto *arg : args.filtered(OPT_export_dynamic_symbol)) 1503 config->dynamicList.push_back( 1504 {arg->getValue(), /*isExternCpp=*/false, 1505 /*hasWildcard=*/hasWildcard(arg->getValue())}); 1506 1507 // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol 1508 // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic 1509 // like semantics. 1510 config->symbolic = 1511 config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list); 1512 for (auto *arg : 1513 args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list)) 1514 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1515 readDynamicList(*buffer); 1516 1517 for (auto *arg : args.filtered(OPT_version_script)) 1518 if (std::optional<std::string> path = searchScript(arg->getValue())) { 1519 if (std::optional<MemoryBufferRef> buffer = readFile(*path)) 1520 readVersionScript(*buffer); 1521 } else { 1522 error(Twine("cannot find version script ") + arg->getValue()); 1523 } 1524 } 1525 1526 // Some Config members do not directly correspond to any particular 1527 // command line options, but computed based on other Config values. 1528 // This function initialize such members. See Config.h for the details 1529 // of these values. 1530 static void setConfigs(opt::InputArgList &args) { 1531 ELFKind k = config->ekind; 1532 uint16_t m = config->emachine; 1533 1534 config->copyRelocs = (config->relocatable || config->emitRelocs); 1535 config->is64 = (k == ELF64LEKind || k == ELF64BEKind); 1536 config->isLE = (k == ELF32LEKind || k == ELF64LEKind); 1537 config->endianness = config->isLE ? endianness::little : endianness::big; 1538 config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS); 1539 config->isPic = config->pie || config->shared; 1540 config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic); 1541 config->wordsize = config->is64 ? 8 : 4; 1542 1543 // ELF defines two different ways to store relocation addends as shown below: 1544 // 1545 // Rel: Addends are stored to the location where relocations are applied. It 1546 // cannot pack the full range of addend values for all relocation types, but 1547 // this only affects relocation types that we don't support emitting as 1548 // dynamic relocations (see getDynRel). 1549 // Rela: Addends are stored as part of relocation entry. 1550 // 1551 // In other words, Rela makes it easy to read addends at the price of extra 1552 // 4 or 8 byte for each relocation entry. 1553 // 1554 // We pick the format for dynamic relocations according to the psABI for each 1555 // processor, but a contrary choice can be made if the dynamic loader 1556 // supports. 1557 config->isRela = getIsRela(args); 1558 1559 // If the output uses REL relocations we must store the dynamic relocation 1560 // addends to the output sections. We also store addends for RELA relocations 1561 // if --apply-dynamic-relocs is used. 1562 // We default to not writing the addends when using RELA relocations since 1563 // any standard conforming tool can find it in r_addend. 1564 config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs, 1565 OPT_no_apply_dynamic_relocs, false) || 1566 !config->isRela; 1567 // Validation of dynamic relocation addends is on by default for assertions 1568 // builds (for supported targets) and disabled otherwise. Ideally we would 1569 // enable the debug checks for all targets, but currently not all targets 1570 // have support for reading Elf_Rel addends, so we only enable for a subset. 1571 #ifndef NDEBUG 1572 bool checkDynamicRelocsDefault = m == EM_AARCH64 || m == EM_ARM || 1573 m == EM_386 || m == EM_MIPS || 1574 m == EM_X86_64 || m == EM_RISCV; 1575 #else 1576 bool checkDynamicRelocsDefault = false; 1577 #endif 1578 config->checkDynamicRelocs = 1579 args.hasFlag(OPT_check_dynamic_relocations, 1580 OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault); 1581 config->tocOptimize = 1582 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64); 1583 config->pcRelOptimize = 1584 args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64); 1585 } 1586 1587 static bool isFormatBinary(StringRef s) { 1588 if (s == "binary") 1589 return true; 1590 if (s == "elf" || s == "default") 1591 return false; 1592 error("unknown --format value: " + s + 1593 " (supported formats: elf, default, binary)"); 1594 return false; 1595 } 1596 1597 void LinkerDriver::createFiles(opt::InputArgList &args) { 1598 llvm::TimeTraceScope timeScope("Load input files"); 1599 // For --{push,pop}-state. 1600 std::vector<std::tuple<bool, bool, bool>> stack; 1601 1602 // Iterate over argv to process input files and positional arguments. 1603 InputFile::isInGroup = false; 1604 bool hasInput = false; 1605 for (auto *arg : args) { 1606 switch (arg->getOption().getID()) { 1607 case OPT_library: 1608 addLibrary(arg->getValue()); 1609 hasInput = true; 1610 break; 1611 case OPT_INPUT: 1612 addFile(arg->getValue(), /*withLOption=*/false); 1613 hasInput = true; 1614 break; 1615 case OPT_defsym: { 1616 StringRef from; 1617 StringRef to; 1618 std::tie(from, to) = StringRef(arg->getValue()).split('='); 1619 if (from.empty() || to.empty()) 1620 error("--defsym: syntax error: " + StringRef(arg->getValue())); 1621 else 1622 readDefsym(from, MemoryBufferRef(to, "--defsym")); 1623 break; 1624 } 1625 case OPT_script: 1626 if (std::optional<std::string> path = searchScript(arg->getValue())) { 1627 if (std::optional<MemoryBufferRef> mb = readFile(*path)) 1628 readLinkerScript(*mb); 1629 break; 1630 } 1631 error(Twine("cannot find linker script ") + arg->getValue()); 1632 break; 1633 case OPT_as_needed: 1634 config->asNeeded = true; 1635 break; 1636 case OPT_format: 1637 config->formatBinary = isFormatBinary(arg->getValue()); 1638 break; 1639 case OPT_no_as_needed: 1640 config->asNeeded = false; 1641 break; 1642 case OPT_Bstatic: 1643 case OPT_omagic: 1644 case OPT_nmagic: 1645 config->isStatic = true; 1646 break; 1647 case OPT_Bdynamic: 1648 config->isStatic = false; 1649 break; 1650 case OPT_whole_archive: 1651 inWholeArchive = true; 1652 break; 1653 case OPT_no_whole_archive: 1654 inWholeArchive = false; 1655 break; 1656 case OPT_just_symbols: 1657 if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) { 1658 files.push_back(createObjFile(*mb)); 1659 files.back()->justSymbols = true; 1660 } 1661 break; 1662 case OPT_start_group: 1663 if (InputFile::isInGroup) 1664 error("nested --start-group"); 1665 InputFile::isInGroup = true; 1666 break; 1667 case OPT_end_group: 1668 if (!InputFile::isInGroup) 1669 error("stray --end-group"); 1670 InputFile::isInGroup = false; 1671 ++InputFile::nextGroupId; 1672 break; 1673 case OPT_start_lib: 1674 if (inLib) 1675 error("nested --start-lib"); 1676 if (InputFile::isInGroup) 1677 error("may not nest --start-lib in --start-group"); 1678 inLib = true; 1679 InputFile::isInGroup = true; 1680 break; 1681 case OPT_end_lib: 1682 if (!inLib) 1683 error("stray --end-lib"); 1684 inLib = false; 1685 InputFile::isInGroup = false; 1686 ++InputFile::nextGroupId; 1687 break; 1688 case OPT_push_state: 1689 stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive); 1690 break; 1691 case OPT_pop_state: 1692 if (stack.empty()) { 1693 error("unbalanced --push-state/--pop-state"); 1694 break; 1695 } 1696 std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back(); 1697 stack.pop_back(); 1698 break; 1699 } 1700 } 1701 1702 if (files.empty() && !hasInput && errorCount() == 0) 1703 error("no input files"); 1704 } 1705 1706 // If -m <machine_type> was not given, infer it from object files. 1707 void LinkerDriver::inferMachineType() { 1708 if (config->ekind != ELFNoneKind) 1709 return; 1710 1711 for (InputFile *f : files) { 1712 if (f->ekind == ELFNoneKind) 1713 continue; 1714 config->ekind = f->ekind; 1715 config->emachine = f->emachine; 1716 config->osabi = f->osabi; 1717 config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f); 1718 return; 1719 } 1720 error("target emulation unknown: -m or at least one .o file required"); 1721 } 1722 1723 // Parse -z max-page-size=<value>. The default value is defined by 1724 // each target. 1725 static uint64_t getMaxPageSize(opt::InputArgList &args) { 1726 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size", 1727 target->defaultMaxPageSize); 1728 if (!isPowerOf2_64(val)) { 1729 error("max-page-size: value isn't a power of 2"); 1730 return target->defaultMaxPageSize; 1731 } 1732 if (config->nmagic || config->omagic) { 1733 if (val != target->defaultMaxPageSize) 1734 warn("-z max-page-size set, but paging disabled by omagic or nmagic"); 1735 return 1; 1736 } 1737 return val; 1738 } 1739 1740 // Parse -z common-page-size=<value>. The default value is defined by 1741 // each target. 1742 static uint64_t getCommonPageSize(opt::InputArgList &args) { 1743 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size", 1744 target->defaultCommonPageSize); 1745 if (!isPowerOf2_64(val)) { 1746 error("common-page-size: value isn't a power of 2"); 1747 return target->defaultCommonPageSize; 1748 } 1749 if (config->nmagic || config->omagic) { 1750 if (val != target->defaultCommonPageSize) 1751 warn("-z common-page-size set, but paging disabled by omagic or nmagic"); 1752 return 1; 1753 } 1754 // commonPageSize can't be larger than maxPageSize. 1755 if (val > config->maxPageSize) 1756 val = config->maxPageSize; 1757 return val; 1758 } 1759 1760 // Parses --image-base option. 1761 static std::optional<uint64_t> getImageBase(opt::InputArgList &args) { 1762 // Because we are using "Config->maxPageSize" here, this function has to be 1763 // called after the variable is initialized. 1764 auto *arg = args.getLastArg(OPT_image_base); 1765 if (!arg) 1766 return std::nullopt; 1767 1768 StringRef s = arg->getValue(); 1769 uint64_t v; 1770 if (!to_integer(s, v)) { 1771 error("--image-base: number expected, but got " + s); 1772 return 0; 1773 } 1774 if ((v % config->maxPageSize) != 0) 1775 warn("--image-base: address isn't multiple of page size: " + s); 1776 return v; 1777 } 1778 1779 // Parses `--exclude-libs=lib,lib,...`. 1780 // The library names may be delimited by commas or colons. 1781 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) { 1782 DenseSet<StringRef> ret; 1783 for (auto *arg : args.filtered(OPT_exclude_libs)) { 1784 StringRef s = arg->getValue(); 1785 for (;;) { 1786 size_t pos = s.find_first_of(",:"); 1787 if (pos == StringRef::npos) 1788 break; 1789 ret.insert(s.substr(0, pos)); 1790 s = s.substr(pos + 1); 1791 } 1792 ret.insert(s); 1793 } 1794 return ret; 1795 } 1796 1797 // Handles the --exclude-libs option. If a static library file is specified 1798 // by the --exclude-libs option, all public symbols from the archive become 1799 // private unless otherwise specified by version scripts or something. 1800 // A special library name "ALL" means all archive files. 1801 // 1802 // This is not a popular option, but some programs such as bionic libc use it. 1803 static void excludeLibs(opt::InputArgList &args) { 1804 DenseSet<StringRef> libs = getExcludeLibs(args); 1805 bool all = libs.count("ALL"); 1806 1807 auto visit = [&](InputFile *file) { 1808 if (file->archiveName.empty() || 1809 !(all || libs.count(path::filename(file->archiveName)))) 1810 return; 1811 ArrayRef<Symbol *> symbols = file->getSymbols(); 1812 if (isa<ELFFileBase>(file)) 1813 symbols = cast<ELFFileBase>(file)->getGlobalSymbols(); 1814 for (Symbol *sym : symbols) 1815 if (!sym->isUndefined() && sym->file == file) 1816 sym->versionId = VER_NDX_LOCAL; 1817 }; 1818 1819 for (ELFFileBase *file : ctx.objectFiles) 1820 visit(file); 1821 1822 for (BitcodeFile *file : ctx.bitcodeFiles) 1823 visit(file); 1824 } 1825 1826 // Force Sym to be entered in the output. 1827 static void handleUndefined(Symbol *sym, const char *option) { 1828 // Since a symbol may not be used inside the program, LTO may 1829 // eliminate it. Mark the symbol as "used" to prevent it. 1830 sym->isUsedInRegularObj = true; 1831 1832 if (!sym->isLazy()) 1833 return; 1834 sym->extract(); 1835 if (!config->whyExtract.empty()) 1836 ctx.whyExtractRecords.emplace_back(option, sym->file, *sym); 1837 } 1838 1839 // As an extension to GNU linkers, lld supports a variant of `-u` 1840 // which accepts wildcard patterns. All symbols that match a given 1841 // pattern are handled as if they were given by `-u`. 1842 static void handleUndefinedGlob(StringRef arg) { 1843 Expected<GlobPattern> pat = GlobPattern::create(arg); 1844 if (!pat) { 1845 error("--undefined-glob: " + toString(pat.takeError())); 1846 return; 1847 } 1848 1849 // Calling sym->extract() in the loop is not safe because it may add new 1850 // symbols to the symbol table, invalidating the current iterator. 1851 SmallVector<Symbol *, 0> syms; 1852 for (Symbol *sym : symtab.getSymbols()) 1853 if (!sym->isPlaceholder() && pat->match(sym->getName())) 1854 syms.push_back(sym); 1855 1856 for (Symbol *sym : syms) 1857 handleUndefined(sym, "--undefined-glob"); 1858 } 1859 1860 static void handleLibcall(StringRef name) { 1861 Symbol *sym = symtab.find(name); 1862 if (!sym || !sym->isLazy()) 1863 return; 1864 1865 MemoryBufferRef mb; 1866 mb = cast<LazyObject>(sym)->file->mb; 1867 1868 if (isBitcode(mb)) 1869 sym->extract(); 1870 } 1871 1872 static void writeArchiveStats() { 1873 if (config->printArchiveStats.empty()) 1874 return; 1875 1876 std::error_code ec; 1877 raw_fd_ostream os(config->printArchiveStats, ec, sys::fs::OF_None); 1878 if (ec) { 1879 error("--print-archive-stats=: cannot open " + config->printArchiveStats + 1880 ": " + ec.message()); 1881 return; 1882 } 1883 1884 os << "members\textracted\tarchive\n"; 1885 1886 SmallVector<StringRef, 0> archives; 1887 DenseMap<CachedHashStringRef, unsigned> all, extracted; 1888 for (ELFFileBase *file : ctx.objectFiles) 1889 if (file->archiveName.size()) 1890 ++extracted[CachedHashStringRef(file->archiveName)]; 1891 for (BitcodeFile *file : ctx.bitcodeFiles) 1892 if (file->archiveName.size()) 1893 ++extracted[CachedHashStringRef(file->archiveName)]; 1894 for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) { 1895 unsigned &v = extracted[CachedHashString(f.first)]; 1896 os << f.second << '\t' << v << '\t' << f.first << '\n'; 1897 // If the archive occurs multiple times, other instances have a count of 0. 1898 v = 0; 1899 } 1900 } 1901 1902 static void writeWhyExtract() { 1903 if (config->whyExtract.empty()) 1904 return; 1905 1906 std::error_code ec; 1907 raw_fd_ostream os(config->whyExtract, ec, sys::fs::OF_None); 1908 if (ec) { 1909 error("cannot open --why-extract= file " + config->whyExtract + ": " + 1910 ec.message()); 1911 return; 1912 } 1913 1914 os << "reference\textracted\tsymbol\n"; 1915 for (auto &entry : ctx.whyExtractRecords) { 1916 os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t' 1917 << toString(std::get<2>(entry)) << '\n'; 1918 } 1919 } 1920 1921 static void reportBackrefs() { 1922 for (auto &ref : ctx.backwardReferences) { 1923 const Symbol &sym = *ref.first; 1924 std::string to = toString(ref.second.second); 1925 // Some libraries have known problems and can cause noise. Filter them out 1926 // with --warn-backrefs-exclude=. The value may look like (for --start-lib) 1927 // *.o or (archive member) *.a(*.o). 1928 bool exclude = false; 1929 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude) 1930 if (pat.match(to)) { 1931 exclude = true; 1932 break; 1933 } 1934 if (!exclude) 1935 warn("backward reference detected: " + sym.getName() + " in " + 1936 toString(ref.second.first) + " refers to " + to); 1937 } 1938 } 1939 1940 // Handle --dependency-file=<path>. If that option is given, lld creates a 1941 // file at a given path with the following contents: 1942 // 1943 // <output-file>: <input-file> ... 1944 // 1945 // <input-file>: 1946 // 1947 // where <output-file> is a pathname of an output file and <input-file> 1948 // ... is a list of pathnames of all input files. `make` command can read a 1949 // file in the above format and interpret it as a dependency info. We write 1950 // phony targets for every <input-file> to avoid an error when that file is 1951 // removed. 1952 // 1953 // This option is useful if you want to make your final executable to depend 1954 // on all input files including system libraries. Here is why. 1955 // 1956 // When you write a Makefile, you usually write it so that the final 1957 // executable depends on all user-generated object files. Normally, you 1958 // don't make your executable to depend on system libraries (such as libc) 1959 // because you don't know the exact paths of libraries, even though system 1960 // libraries that are linked to your executable statically are technically a 1961 // part of your program. By using --dependency-file option, you can make 1962 // lld to dump dependency info so that you can maintain exact dependencies 1963 // easily. 1964 static void writeDependencyFile() { 1965 std::error_code ec; 1966 raw_fd_ostream os(config->dependencyFile, ec, sys::fs::OF_None); 1967 if (ec) { 1968 error("cannot open " + config->dependencyFile + ": " + ec.message()); 1969 return; 1970 } 1971 1972 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja: 1973 // * A space is escaped by a backslash which itself must be escaped. 1974 // * A hash sign is escaped by a single backslash. 1975 // * $ is escapes as $$. 1976 auto printFilename = [](raw_fd_ostream &os, StringRef filename) { 1977 llvm::SmallString<256> nativePath; 1978 llvm::sys::path::native(filename.str(), nativePath); 1979 llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true); 1980 for (unsigned i = 0, e = nativePath.size(); i != e; ++i) { 1981 if (nativePath[i] == '#') { 1982 os << '\\'; 1983 } else if (nativePath[i] == ' ') { 1984 os << '\\'; 1985 unsigned j = i; 1986 while (j > 0 && nativePath[--j] == '\\') 1987 os << '\\'; 1988 } else if (nativePath[i] == '$') { 1989 os << '$'; 1990 } 1991 os << nativePath[i]; 1992 } 1993 }; 1994 1995 os << config->outputFile << ":"; 1996 for (StringRef path : config->dependencyFiles) { 1997 os << " \\\n "; 1998 printFilename(os, path); 1999 } 2000 os << "\n"; 2001 2002 for (StringRef path : config->dependencyFiles) { 2003 os << "\n"; 2004 printFilename(os, path); 2005 os << ":\n"; 2006 } 2007 } 2008 2009 // Replaces common symbols with defined symbols reside in .bss sections. 2010 // This function is called after all symbol names are resolved. As a 2011 // result, the passes after the symbol resolution won't see any 2012 // symbols of type CommonSymbol. 2013 static void replaceCommonSymbols() { 2014 llvm::TimeTraceScope timeScope("Replace common symbols"); 2015 for (ELFFileBase *file : ctx.objectFiles) { 2016 if (!file->hasCommonSyms) 2017 continue; 2018 for (Symbol *sym : file->getGlobalSymbols()) { 2019 auto *s = dyn_cast<CommonSymbol>(sym); 2020 if (!s) 2021 continue; 2022 2023 auto *bss = make<BssSection>("COMMON", s->size, s->alignment); 2024 bss->file = s->file; 2025 ctx.inputSections.push_back(bss); 2026 Defined(s->file, StringRef(), s->binding, s->stOther, s->type, 2027 /*value=*/0, s->size, bss) 2028 .overwrite(*s); 2029 } 2030 } 2031 } 2032 2033 // If all references to a DSO happen to be weak, the DSO is not added to 2034 // DT_NEEDED. If that happens, replace ShardSymbol with Undefined to avoid 2035 // dangling references to an unneeded DSO. Use a weak binding to avoid 2036 // --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols. 2037 static void demoteSharedAndLazySymbols() { 2038 llvm::TimeTraceScope timeScope("Demote shared and lazy symbols"); 2039 for (Symbol *sym : symtab.getSymbols()) { 2040 auto *s = dyn_cast<SharedSymbol>(sym); 2041 if (!(s && !cast<SharedFile>(s->file)->isNeeded) && !sym->isLazy()) 2042 continue; 2043 2044 uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK); 2045 Undefined(nullptr, sym->getName(), binding, sym->stOther, sym->type) 2046 .overwrite(*sym); 2047 sym->versionId = VER_NDX_GLOBAL; 2048 } 2049 } 2050 2051 // The section referred to by `s` is considered address-significant. Set the 2052 // keepUnique flag on the section if appropriate. 2053 static void markAddrsig(Symbol *s) { 2054 if (auto *d = dyn_cast_or_null<Defined>(s)) 2055 if (d->section) 2056 // We don't need to keep text sections unique under --icf=all even if they 2057 // are address-significant. 2058 if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR)) 2059 d->section->keepUnique = true; 2060 } 2061 2062 // Record sections that define symbols mentioned in --keep-unique <symbol> 2063 // and symbols referred to by address-significance tables. These sections are 2064 // ineligible for ICF. 2065 template <class ELFT> 2066 static void findKeepUniqueSections(opt::InputArgList &args) { 2067 for (auto *arg : args.filtered(OPT_keep_unique)) { 2068 StringRef name = arg->getValue(); 2069 auto *d = dyn_cast_or_null<Defined>(symtab.find(name)); 2070 if (!d || !d->section) { 2071 warn("could not find symbol " + name + " to keep unique"); 2072 continue; 2073 } 2074 d->section->keepUnique = true; 2075 } 2076 2077 // --icf=all --ignore-data-address-equality means that we can ignore 2078 // the dynsym and address-significance tables entirely. 2079 if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality) 2080 return; 2081 2082 // Symbols in the dynsym could be address-significant in other executables 2083 // or DSOs, so we conservatively mark them as address-significant. 2084 for (Symbol *sym : symtab.getSymbols()) 2085 if (sym->includeInDynsym()) 2086 markAddrsig(sym); 2087 2088 // Visit the address-significance table in each object file and mark each 2089 // referenced symbol as address-significant. 2090 for (InputFile *f : ctx.objectFiles) { 2091 auto *obj = cast<ObjFile<ELFT>>(f); 2092 ArrayRef<Symbol *> syms = obj->getSymbols(); 2093 if (obj->addrsigSec) { 2094 ArrayRef<uint8_t> contents = 2095 check(obj->getObj().getSectionContents(*obj->addrsigSec)); 2096 const uint8_t *cur = contents.begin(); 2097 while (cur != contents.end()) { 2098 unsigned size; 2099 const char *err; 2100 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 2101 if (err) 2102 fatal(toString(f) + ": could not decode addrsig section: " + err); 2103 markAddrsig(syms[symIndex]); 2104 cur += size; 2105 } 2106 } else { 2107 // If an object file does not have an address-significance table, 2108 // conservatively mark all of its symbols as address-significant. 2109 for (Symbol *s : syms) 2110 markAddrsig(s); 2111 } 2112 } 2113 } 2114 2115 // This function reads a symbol partition specification section. These sections 2116 // are used to control which partition a symbol is allocated to. See 2117 // https://lld.llvm.org/Partitions.html for more details on partitions. 2118 template <typename ELFT> 2119 static void readSymbolPartitionSection(InputSectionBase *s) { 2120 // Read the relocation that refers to the partition's entry point symbol. 2121 Symbol *sym; 2122 const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>(); 2123 if (rels.areRelocsRel()) 2124 sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]); 2125 else 2126 sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]); 2127 if (!isa<Defined>(sym) || !sym->includeInDynsym()) 2128 return; 2129 2130 StringRef partName = reinterpret_cast<const char *>(s->content().data()); 2131 for (Partition &part : partitions) { 2132 if (part.name == partName) { 2133 sym->partition = part.getNumber(); 2134 return; 2135 } 2136 } 2137 2138 // Forbid partitions from being used on incompatible targets, and forbid them 2139 // from being used together with various linker features that assume a single 2140 // set of output sections. 2141 if (script->hasSectionsCommand) 2142 error(toString(s->file) + 2143 ": partitions cannot be used with the SECTIONS command"); 2144 if (script->hasPhdrsCommands()) 2145 error(toString(s->file) + 2146 ": partitions cannot be used with the PHDRS command"); 2147 if (!config->sectionStartMap.empty()) 2148 error(toString(s->file) + ": partitions cannot be used with " 2149 "--section-start, -Ttext, -Tdata or -Tbss"); 2150 if (config->emachine == EM_MIPS) 2151 error(toString(s->file) + ": partitions cannot be used on this target"); 2152 2153 // Impose a limit of no more than 254 partitions. This limit comes from the 2154 // sizes of the Partition fields in InputSectionBase and Symbol, as well as 2155 // the amount of space devoted to the partition number in RankFlags. 2156 if (partitions.size() == 254) 2157 fatal("may not have more than 254 partitions"); 2158 2159 partitions.emplace_back(); 2160 Partition &newPart = partitions.back(); 2161 newPart.name = partName; 2162 sym->partition = newPart.getNumber(); 2163 } 2164 2165 static Symbol *addUnusedUndefined(StringRef name, 2166 uint8_t binding = STB_GLOBAL) { 2167 return symtab.addSymbol(Undefined{nullptr, name, binding, STV_DEFAULT, 0}); 2168 } 2169 2170 static void markBuffersAsDontNeed(bool skipLinkedOutput) { 2171 // With --thinlto-index-only, all buffers are nearly unused from now on 2172 // (except symbol/section names used by infrequent passes). Mark input file 2173 // buffers as MADV_DONTNEED so that these pages can be reused by the expensive 2174 // thin link, saving memory. 2175 if (skipLinkedOutput) { 2176 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers)) 2177 mb.dontNeedIfMmap(); 2178 return; 2179 } 2180 2181 // Otherwise, just mark MemoryBuffers backing BitcodeFiles. 2182 DenseSet<const char *> bufs; 2183 for (BitcodeFile *file : ctx.bitcodeFiles) 2184 bufs.insert(file->mb.getBufferStart()); 2185 for (BitcodeFile *file : ctx.lazyBitcodeFiles) 2186 bufs.insert(file->mb.getBufferStart()); 2187 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers)) 2188 if (bufs.count(mb.getBufferStart())) 2189 mb.dontNeedIfMmap(); 2190 } 2191 2192 // This function is where all the optimizations of link-time 2193 // optimization takes place. When LTO is in use, some input files are 2194 // not in native object file format but in the LLVM bitcode format. 2195 // This function compiles bitcode files into a few big native files 2196 // using LLVM functions and replaces bitcode symbols with the results. 2197 // Because all bitcode files that the program consists of are passed to 2198 // the compiler at once, it can do a whole-program optimization. 2199 template <class ELFT> 2200 void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) { 2201 llvm::TimeTraceScope timeScope("LTO"); 2202 // Compile bitcode files and replace bitcode symbols. 2203 lto.reset(new BitcodeCompiler); 2204 for (BitcodeFile *file : ctx.bitcodeFiles) 2205 lto->add(*file); 2206 2207 if (!ctx.bitcodeFiles.empty()) 2208 markBuffersAsDontNeed(skipLinkedOutput); 2209 2210 for (InputFile *file : lto->compile()) { 2211 auto *obj = cast<ObjFile<ELFT>>(file); 2212 obj->parse(/*ignoreComdats=*/true); 2213 2214 // Parse '@' in symbol names for non-relocatable output. 2215 if (!config->relocatable) 2216 for (Symbol *sym : obj->getGlobalSymbols()) 2217 if (sym->hasVersionSuffix) 2218 sym->parseSymbolVersion(); 2219 ctx.objectFiles.push_back(obj); 2220 } 2221 } 2222 2223 // The --wrap option is a feature to rename symbols so that you can write 2224 // wrappers for existing functions. If you pass `--wrap=foo`, all 2225 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are 2226 // expected to write `__wrap_foo` function as a wrapper). The original 2227 // symbol becomes accessible as `__real_foo`, so you can call that from your 2228 // wrapper. 2229 // 2230 // This data structure is instantiated for each --wrap option. 2231 struct WrappedSymbol { 2232 Symbol *sym; 2233 Symbol *real; 2234 Symbol *wrap; 2235 }; 2236 2237 // Handles --wrap option. 2238 // 2239 // This function instantiates wrapper symbols. At this point, they seem 2240 // like they are not being used at all, so we explicitly set some flags so 2241 // that LTO won't eliminate them. 2242 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) { 2243 std::vector<WrappedSymbol> v; 2244 DenseSet<StringRef> seen; 2245 2246 for (auto *arg : args.filtered(OPT_wrap)) { 2247 StringRef name = arg->getValue(); 2248 if (!seen.insert(name).second) 2249 continue; 2250 2251 Symbol *sym = symtab.find(name); 2252 if (!sym) 2253 continue; 2254 2255 Symbol *wrap = 2256 addUnusedUndefined(saver().save("__wrap_" + name), sym->binding); 2257 2258 // If __real_ is referenced, pull in the symbol if it is lazy. Do this after 2259 // processing __wrap_ as that may have referenced __real_. 2260 StringRef realName = saver().save("__real_" + name); 2261 if (symtab.find(realName)) 2262 addUnusedUndefined(name, sym->binding); 2263 2264 Symbol *real = addUnusedUndefined(realName); 2265 v.push_back({sym, real, wrap}); 2266 2267 // We want to tell LTO not to inline symbols to be overwritten 2268 // because LTO doesn't know the final symbol contents after renaming. 2269 real->scriptDefined = true; 2270 sym->scriptDefined = true; 2271 2272 // If a symbol is referenced in any object file, bitcode file or shared 2273 // object, mark its redirection target (foo for __real_foo and __wrap_foo 2274 // for foo) as referenced after redirection, which will be used to tell LTO 2275 // to not eliminate the redirection target. If the object file defining the 2276 // symbol also references it, we cannot easily distinguish the case from 2277 // cases where the symbol is not referenced. Retain the redirection target 2278 // in this case because we choose to wrap symbol references regardless of 2279 // whether the symbol is defined 2280 // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358). 2281 if (real->referenced || real->isDefined()) 2282 sym->referencedAfterWrap = true; 2283 if (sym->referenced || sym->isDefined()) 2284 wrap->referencedAfterWrap = true; 2285 } 2286 return v; 2287 } 2288 2289 static void combineVersionedSymbol(Symbol &sym, 2290 DenseMap<Symbol *, Symbol *> &map) { 2291 const char *suffix1 = sym.getVersionSuffix(); 2292 if (suffix1[0] != '@' || suffix1[1] == '@') 2293 return; 2294 2295 // Check the existing symbol foo. We have two special cases to handle: 2296 // 2297 // * There is a definition of foo@v1 and foo@@v1. 2298 // * There is a definition of foo@v1 and foo. 2299 Defined *sym2 = dyn_cast_or_null<Defined>(symtab.find(sym.getName())); 2300 if (!sym2) 2301 return; 2302 const char *suffix2 = sym2->getVersionSuffix(); 2303 if (suffix2[0] == '@' && suffix2[1] == '@' && 2304 strcmp(suffix1 + 1, suffix2 + 2) == 0) { 2305 // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1. 2306 map.try_emplace(&sym, sym2); 2307 // If both foo@v1 and foo@@v1 are defined and non-weak, report a 2308 // duplicate definition error. 2309 if (sym.isDefined()) { 2310 sym2->checkDuplicate(cast<Defined>(sym)); 2311 sym2->resolve(cast<Defined>(sym)); 2312 } else if (sym.isUndefined()) { 2313 sym2->resolve(cast<Undefined>(sym)); 2314 } else { 2315 sym2->resolve(cast<SharedSymbol>(sym)); 2316 } 2317 // Eliminate foo@v1 from the symbol table. 2318 sym.symbolKind = Symbol::PlaceholderKind; 2319 sym.isUsedInRegularObj = false; 2320 } else if (auto *sym1 = dyn_cast<Defined>(&sym)) { 2321 if (sym2->versionId > VER_NDX_GLOBAL 2322 ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1 2323 : sym1->section == sym2->section && sym1->value == sym2->value) { 2324 // Due to an assembler design flaw, if foo is defined, .symver foo, 2325 // foo@v1 defines both foo and foo@v1. Unless foo is bound to a 2326 // different version, GNU ld makes foo@v1 canonical and eliminates 2327 // foo. Emulate its behavior, otherwise we would have foo or foo@@v1 2328 // beside foo@v1. foo@v1 and foo combining does not apply if they are 2329 // not defined in the same place. 2330 map.try_emplace(sym2, &sym); 2331 sym2->symbolKind = Symbol::PlaceholderKind; 2332 sym2->isUsedInRegularObj = false; 2333 } 2334 } 2335 } 2336 2337 // Do renaming for --wrap and foo@v1 by updating pointers to symbols. 2338 // 2339 // When this function is executed, only InputFiles and symbol table 2340 // contain pointers to symbol objects. We visit them to replace pointers, 2341 // so that wrapped symbols are swapped as instructed by the command line. 2342 static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) { 2343 llvm::TimeTraceScope timeScope("Redirect symbols"); 2344 DenseMap<Symbol *, Symbol *> map; 2345 for (const WrappedSymbol &w : wrapped) { 2346 map[w.sym] = w.wrap; 2347 map[w.real] = w.sym; 2348 } 2349 2350 // If there are version definitions (versionDefinitions.size() > 2), enumerate 2351 // symbols with a non-default version (foo@v1) and check whether it should be 2352 // combined with foo or foo@@v1. 2353 if (config->versionDefinitions.size() > 2) 2354 for (Symbol *sym : symtab.getSymbols()) 2355 if (sym->hasVersionSuffix) 2356 combineVersionedSymbol(*sym, map); 2357 2358 if (map.empty()) 2359 return; 2360 2361 // Update pointers in input files. 2362 parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) { 2363 for (Symbol *&sym : file->getMutableGlobalSymbols()) 2364 if (Symbol *s = map.lookup(sym)) 2365 sym = s; 2366 }); 2367 2368 // Update pointers in the symbol table. 2369 for (const WrappedSymbol &w : wrapped) 2370 symtab.wrap(w.sym, w.real, w.wrap); 2371 } 2372 2373 static void checkAndReportMissingFeature(StringRef config, uint32_t features, 2374 uint32_t mask, const Twine &report) { 2375 if (!(features & mask)) { 2376 if (config == "error") 2377 error(report); 2378 else if (config == "warning") 2379 warn(report); 2380 } 2381 } 2382 2383 // To enable CET (x86's hardware-assisted control flow enforcement), each 2384 // source file must be compiled with -fcf-protection. Object files compiled 2385 // with the flag contain feature flags indicating that they are compatible 2386 // with CET. We enable the feature only when all object files are compatible 2387 // with CET. 2388 // 2389 // This is also the case with AARCH64's BTI and PAC which use the similar 2390 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism. 2391 static uint32_t getAndFeatures() { 2392 if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 2393 config->emachine != EM_AARCH64) 2394 return 0; 2395 2396 uint32_t ret = -1; 2397 for (ELFFileBase *f : ctx.objectFiles) { 2398 uint32_t features = f->andFeatures; 2399 2400 checkAndReportMissingFeature( 2401 config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI, 2402 toString(f) + ": -z bti-report: file does not have " 2403 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 2404 2405 checkAndReportMissingFeature( 2406 config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT, 2407 toString(f) + ": -z cet-report: file does not have " 2408 "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 2409 2410 checkAndReportMissingFeature( 2411 config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK, 2412 toString(f) + ": -z cet-report: file does not have " 2413 "GNU_PROPERTY_X86_FEATURE_1_SHSTK property"); 2414 2415 if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) { 2416 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI; 2417 if (config->zBtiReport == "none") 2418 warn(toString(f) + ": -z force-bti: file does not have " 2419 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 2420 } else if (config->zForceIbt && 2421 !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) { 2422 if (config->zCetReport == "none") 2423 warn(toString(f) + ": -z force-ibt: file does not have " 2424 "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 2425 features |= GNU_PROPERTY_X86_FEATURE_1_IBT; 2426 } 2427 if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) { 2428 warn(toString(f) + ": -z pac-plt: file does not have " 2429 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property"); 2430 features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC; 2431 } 2432 ret &= features; 2433 } 2434 2435 // Force enable Shadow Stack. 2436 if (config->zShstk) 2437 ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK; 2438 2439 return ret; 2440 } 2441 2442 static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) { 2443 switch (file->ekind) { 2444 case ELF32LEKind: 2445 cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 2446 break; 2447 case ELF32BEKind: 2448 cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 2449 break; 2450 case ELF64LEKind: 2451 cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 2452 break; 2453 case ELF64BEKind: 2454 cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats); 2455 break; 2456 default: 2457 llvm_unreachable(""); 2458 } 2459 } 2460 2461 static void postParseObjectFile(ELFFileBase *file) { 2462 switch (file->ekind) { 2463 case ELF32LEKind: 2464 cast<ObjFile<ELF32LE>>(file)->postParse(); 2465 break; 2466 case ELF32BEKind: 2467 cast<ObjFile<ELF32BE>>(file)->postParse(); 2468 break; 2469 case ELF64LEKind: 2470 cast<ObjFile<ELF64LE>>(file)->postParse(); 2471 break; 2472 case ELF64BEKind: 2473 cast<ObjFile<ELF64BE>>(file)->postParse(); 2474 break; 2475 default: 2476 llvm_unreachable(""); 2477 } 2478 } 2479 2480 // Do actual linking. Note that when this function is called, 2481 // all linker scripts have already been parsed. 2482 void LinkerDriver::link(opt::InputArgList &args) { 2483 llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link")); 2484 // If a --hash-style option was not given, set to a default value, 2485 // which varies depending on the target. 2486 if (!args.hasArg(OPT_hash_style)) { 2487 if (config->emachine == EM_MIPS) 2488 config->sysvHash = true; 2489 else 2490 config->sysvHash = config->gnuHash = true; 2491 } 2492 2493 // Default output filename is "a.out" by the Unix tradition. 2494 if (config->outputFile.empty()) 2495 config->outputFile = "a.out"; 2496 2497 // Fail early if the output file or map file is not writable. If a user has a 2498 // long link, e.g. due to a large LTO link, they do not wish to run it and 2499 // find that it failed because there was a mistake in their command-line. 2500 { 2501 llvm::TimeTraceScope timeScope("Create output files"); 2502 if (auto e = tryCreateFile(config->outputFile)) 2503 error("cannot open output file " + config->outputFile + ": " + 2504 e.message()); 2505 if (auto e = tryCreateFile(config->mapFile)) 2506 error("cannot open map file " + config->mapFile + ": " + e.message()); 2507 if (auto e = tryCreateFile(config->whyExtract)) 2508 error("cannot open --why-extract= file " + config->whyExtract + ": " + 2509 e.message()); 2510 } 2511 if (errorCount()) 2512 return; 2513 2514 // Use default entry point name if no name was given via the command 2515 // line nor linker scripts. For some reason, MIPS entry point name is 2516 // different from others. 2517 config->warnMissingEntry = 2518 (!config->entry.empty() || (!config->shared && !config->relocatable)); 2519 if (config->entry.empty() && !config->relocatable) 2520 config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start"; 2521 2522 // Handle --trace-symbol. 2523 for (auto *arg : args.filtered(OPT_trace_symbol)) 2524 symtab.insert(arg->getValue())->traced = true; 2525 2526 // Handle -u/--undefined before input files. If both a.a and b.so define foo, 2527 // -u foo a.a b.so will extract a.a. 2528 for (StringRef name : config->undefined) 2529 addUnusedUndefined(name)->referenced = true; 2530 2531 // Add all files to the symbol table. This will add almost all 2532 // symbols that we need to the symbol table. This process might 2533 // add files to the link, via autolinking, these files are always 2534 // appended to the Files vector. 2535 { 2536 llvm::TimeTraceScope timeScope("Parse input files"); 2537 for (size_t i = 0; i < files.size(); ++i) { 2538 llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName()); 2539 parseFile(files[i]); 2540 } 2541 } 2542 2543 // Now that we have every file, we can decide if we will need a 2544 // dynamic symbol table. 2545 // We need one if we were asked to export dynamic symbols or if we are 2546 // producing a shared library. 2547 // We also need one if any shared libraries are used and for pie executables 2548 // (probably because the dynamic linker needs it). 2549 config->hasDynSymTab = 2550 !ctx.sharedFiles.empty() || config->isPic || config->exportDynamic; 2551 2552 // Some symbols (such as __ehdr_start) are defined lazily only when there 2553 // are undefined symbols for them, so we add these to trigger that logic. 2554 for (StringRef name : script->referencedSymbols) { 2555 Symbol *sym = addUnusedUndefined(name); 2556 sym->isUsedInRegularObj = true; 2557 sym->referenced = true; 2558 } 2559 2560 // Prevent LTO from removing any definition referenced by -u. 2561 for (StringRef name : config->undefined) 2562 if (Defined *sym = dyn_cast_or_null<Defined>(symtab.find(name))) 2563 sym->isUsedInRegularObj = true; 2564 2565 // If an entry symbol is in a static archive, pull out that file now. 2566 if (Symbol *sym = symtab.find(config->entry)) 2567 handleUndefined(sym, "--entry"); 2568 2569 // Handle the `--undefined-glob <pattern>` options. 2570 for (StringRef pat : args::getStrings(args, OPT_undefined_glob)) 2571 handleUndefinedGlob(pat); 2572 2573 // Mark -init and -fini symbols so that the LTO doesn't eliminate them. 2574 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->init))) 2575 sym->isUsedInRegularObj = true; 2576 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->fini))) 2577 sym->isUsedInRegularObj = true; 2578 2579 // If any of our inputs are bitcode files, the LTO code generator may create 2580 // references to certain library functions that might not be explicit in the 2581 // bitcode file's symbol table. If any of those library functions are defined 2582 // in a bitcode file in an archive member, we need to arrange to use LTO to 2583 // compile those archive members by adding them to the link beforehand. 2584 // 2585 // However, adding all libcall symbols to the link can have undesired 2586 // consequences. For example, the libgcc implementation of 2587 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 2588 // that aborts the program if the Linux kernel does not support 64-bit 2589 // atomics, which would prevent the program from running even if it does not 2590 // use 64-bit atomics. 2591 // 2592 // Therefore, we only add libcall symbols to the link before LTO if we have 2593 // to, i.e. if the symbol's definition is in bitcode. Any other required 2594 // libcall symbols will be added to the link after LTO when we add the LTO 2595 // object file to the link. 2596 if (!ctx.bitcodeFiles.empty()) 2597 for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2598 handleLibcall(s); 2599 2600 // Archive members defining __wrap symbols may be extracted. 2601 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 2602 2603 // No more lazy bitcode can be extracted at this point. Do post parse work 2604 // like checking duplicate symbols. 2605 parallelForEach(ctx.objectFiles, [](ELFFileBase *file) { 2606 initSectionsAndLocalSyms(file, /*ignoreComdats=*/false); 2607 }); 2608 parallelForEach(ctx.objectFiles, postParseObjectFile); 2609 parallelForEach(ctx.bitcodeFiles, 2610 [](BitcodeFile *file) { file->postParse(); }); 2611 for (auto &it : ctx.nonPrevailingSyms) { 2612 Symbol &sym = *it.first; 2613 Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type, 2614 it.second) 2615 .overwrite(sym); 2616 cast<Undefined>(sym).nonPrevailing = true; 2617 } 2618 ctx.nonPrevailingSyms.clear(); 2619 for (const DuplicateSymbol &d : ctx.duplicates) 2620 reportDuplicate(*d.sym, d.file, d.section, d.value); 2621 ctx.duplicates.clear(); 2622 2623 // Return if there were name resolution errors. 2624 if (errorCount()) 2625 return; 2626 2627 // We want to declare linker script's symbols early, 2628 // so that we can version them. 2629 // They also might be exported if referenced by DSOs. 2630 script->declareSymbols(); 2631 2632 // Handle --exclude-libs. This is before scanVersionScript() due to a 2633 // workaround for Android ndk: for a defined versioned symbol in an archive 2634 // without a version node in the version script, Android does not expect a 2635 // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295). 2636 // GNU ld errors in this case. 2637 if (args.hasArg(OPT_exclude_libs)) 2638 excludeLibs(args); 2639 2640 // Create elfHeader early. We need a dummy section in 2641 // addReservedSymbols to mark the created symbols as not absolute. 2642 Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC); 2643 2644 // We need to create some reserved symbols such as _end. Create them. 2645 if (!config->relocatable) 2646 addReservedSymbols(); 2647 2648 // Apply version scripts. 2649 // 2650 // For a relocatable output, version scripts don't make sense, and 2651 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 2652 // name "foo@ver1") rather do harm, so we don't call this if -r is given. 2653 if (!config->relocatable) { 2654 llvm::TimeTraceScope timeScope("Process symbol versions"); 2655 symtab.scanVersionScript(); 2656 } 2657 2658 // Skip the normal linked output if some LTO options are specified. 2659 // 2660 // For --thinlto-index-only, index file creation is performed in 2661 // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and 2662 // --plugin-opt=emit-asm create output files in bitcode or assembly code, 2663 // respectively. When only certain thinLTO modules are specified for 2664 // compilation, the intermediate object file are the expected output. 2665 const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM || 2666 config->ltoEmitAsm || 2667 !config->thinLTOModulesToCompile.empty(); 2668 2669 // Do link-time optimization if given files are LLVM bitcode files. 2670 // This compiles bitcode files into real object files. 2671 // 2672 // With this the symbol table should be complete. After this, no new names 2673 // except a few linker-synthesized ones will be added to the symbol table. 2674 const size_t numObjsBeforeLTO = ctx.objectFiles.size(); 2675 invokeELFT(compileBitcodeFiles, skipLinkedOutput); 2676 2677 // Symbol resolution finished. Report backward reference problems, 2678 // --print-archive-stats=, and --why-extract=. 2679 reportBackrefs(); 2680 writeArchiveStats(); 2681 writeWhyExtract(); 2682 if (errorCount()) 2683 return; 2684 2685 // Bail out if normal linked output is skipped due to LTO. 2686 if (skipLinkedOutput) 2687 return; 2688 2689 // compileBitcodeFiles may have produced lto.tmp object files. After this, no 2690 // more file will be added. 2691 auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO); 2692 parallelForEach(newObjectFiles, [](ELFFileBase *file) { 2693 initSectionsAndLocalSyms(file, /*ignoreComdats=*/true); 2694 }); 2695 parallelForEach(newObjectFiles, postParseObjectFile); 2696 for (const DuplicateSymbol &d : ctx.duplicates) 2697 reportDuplicate(*d.sym, d.file, d.section, d.value); 2698 2699 // Handle --exclude-libs again because lto.tmp may reference additional 2700 // libcalls symbols defined in an excluded archive. This may override 2701 // versionId set by scanVersionScript(). 2702 if (args.hasArg(OPT_exclude_libs)) 2703 excludeLibs(args); 2704 2705 // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1. 2706 redirectSymbols(wrapped); 2707 2708 // Replace common symbols with regular symbols. 2709 replaceCommonSymbols(); 2710 2711 { 2712 llvm::TimeTraceScope timeScope("Aggregate sections"); 2713 // Now that we have a complete list of input files. 2714 // Beyond this point, no new files are added. 2715 // Aggregate all input sections into one place. 2716 for (InputFile *f : ctx.objectFiles) { 2717 for (InputSectionBase *s : f->getSections()) { 2718 if (!s || s == &InputSection::discarded) 2719 continue; 2720 if (LLVM_UNLIKELY(isa<EhInputSection>(s))) 2721 ctx.ehInputSections.push_back(cast<EhInputSection>(s)); 2722 else 2723 ctx.inputSections.push_back(s); 2724 } 2725 } 2726 for (BinaryFile *f : ctx.binaryFiles) 2727 for (InputSectionBase *s : f->getSections()) 2728 ctx.inputSections.push_back(cast<InputSection>(s)); 2729 } 2730 2731 { 2732 llvm::TimeTraceScope timeScope("Strip sections"); 2733 if (ctx.hasSympart.load(std::memory_order_relaxed)) { 2734 llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) { 2735 if (s->type != SHT_LLVM_SYMPART) 2736 return false; 2737 invokeELFT(readSymbolPartitionSection, s); 2738 return true; 2739 }); 2740 } 2741 // We do not want to emit debug sections if --strip-all 2742 // or --strip-debug are given. 2743 if (config->strip != StripPolicy::None) { 2744 llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) { 2745 if (isDebugSection(*s)) 2746 return true; 2747 if (auto *isec = dyn_cast<InputSection>(s)) 2748 if (InputSectionBase *rel = isec->getRelocatedSection()) 2749 if (isDebugSection(*rel)) 2750 return true; 2751 2752 return false; 2753 }); 2754 } 2755 } 2756 2757 // Since we now have a complete set of input files, we can create 2758 // a .d file to record build dependencies. 2759 if (!config->dependencyFile.empty()) 2760 writeDependencyFile(); 2761 2762 // Now that the number of partitions is fixed, save a pointer to the main 2763 // partition. 2764 mainPart = &partitions[0]; 2765 2766 // Read .note.gnu.property sections from input object files which 2767 // contain a hint to tweak linker's and loader's behaviors. 2768 config->andFeatures = getAndFeatures(); 2769 2770 // The Target instance handles target-specific stuff, such as applying 2771 // relocations or writing a PLT section. It also contains target-dependent 2772 // values such as a default image base address. 2773 target = getTarget(); 2774 2775 config->eflags = target->calcEFlags(); 2776 // maxPageSize (sometimes called abi page size) is the maximum page size that 2777 // the output can be run on. For example if the OS can use 4k or 64k page 2778 // sizes then maxPageSize must be 64k for the output to be useable on both. 2779 // All important alignment decisions must use this value. 2780 config->maxPageSize = getMaxPageSize(args); 2781 // commonPageSize is the most common page size that the output will be run on. 2782 // For example if an OS can use 4k or 64k page sizes and 4k is more common 2783 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for 2784 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 2785 // is limited to writing trap instructions on the last executable segment. 2786 config->commonPageSize = getCommonPageSize(args); 2787 2788 config->imageBase = getImageBase(args); 2789 2790 // This adds a .comment section containing a version string. 2791 if (!config->relocatable) 2792 ctx.inputSections.push_back(createCommentSection()); 2793 2794 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection. 2795 invokeELFT(splitSections); 2796 2797 // Garbage collection and removal of shared symbols from unused shared objects. 2798 invokeELFT(markLive); 2799 demoteSharedAndLazySymbols(); 2800 2801 // Make copies of any input sections that need to be copied into each 2802 // partition. 2803 copySectionsIntoPartitions(); 2804 2805 // Create synthesized sections such as .got and .plt. This is called before 2806 // processSectionCommands() so that they can be placed by SECTIONS commands. 2807 invokeELFT(createSyntheticSections); 2808 2809 // Some input sections that are used for exception handling need to be moved 2810 // into synthetic sections. Do that now so that they aren't assigned to 2811 // output sections in the usual way. 2812 if (!config->relocatable) 2813 combineEhSections(); 2814 2815 // Merge .riscv.attributes sections. 2816 if (config->emachine == EM_RISCV) 2817 mergeRISCVAttributesSections(); 2818 2819 { 2820 llvm::TimeTraceScope timeScope("Assign sections"); 2821 2822 // Create output sections described by SECTIONS commands. 2823 script->processSectionCommands(); 2824 2825 // Linker scripts control how input sections are assigned to output 2826 // sections. Input sections that were not handled by scripts are called 2827 // "orphans", and they are assigned to output sections by the default rule. 2828 // Process that. 2829 script->addOrphanSections(); 2830 } 2831 2832 { 2833 llvm::TimeTraceScope timeScope("Merge/finalize input sections"); 2834 2835 // Migrate InputSectionDescription::sectionBases to sections. This includes 2836 // merging MergeInputSections into a single MergeSyntheticSection. From this 2837 // point onwards InputSectionDescription::sections should be used instead of 2838 // sectionBases. 2839 for (SectionCommand *cmd : script->sectionCommands) 2840 if (auto *osd = dyn_cast<OutputDesc>(cmd)) 2841 osd->osec.finalizeInputSections(); 2842 } 2843 2844 // Two input sections with different output sections should not be folded. 2845 // ICF runs after processSectionCommands() so that we know the output sections. 2846 if (config->icf != ICFLevel::None) { 2847 invokeELFT(findKeepUniqueSections, args); 2848 invokeELFT(doIcf); 2849 } 2850 2851 // Read the callgraph now that we know what was gced or icfed 2852 if (config->callGraphProfileSort) { 2853 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) 2854 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 2855 readCallGraph(*buffer); 2856 invokeELFT(readCallGraphsFromObjectFiles); 2857 } 2858 2859 // Write the result to the file. 2860 invokeELFT(writeResult); 2861 } 2862