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