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/LTO/LTO.h" 51 #include "llvm/Support/CommandLine.h" 52 #include "llvm/Support/Compression.h" 53 #include "llvm/Support/GlobPattern.h" 54 #include "llvm/Support/LEB128.h" 55 #include "llvm/Support/Parallel.h" 56 #include "llvm/Support/Path.h" 57 #include "llvm/Support/TarWriter.h" 58 #include "llvm/Support/TargetSelect.h" 59 #include "llvm/Support/TimeProfiler.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include <cstdlib> 62 #include <utility> 63 64 using namespace llvm; 65 using namespace llvm::ELF; 66 using namespace llvm::object; 67 using namespace llvm::sys; 68 using namespace llvm::support; 69 using namespace lld; 70 using namespace lld::elf; 71 72 Configuration *elf::config; 73 LinkerDriver *elf::driver; 74 75 static void setConfigs(opt::InputArgList &args); 76 static void readConfigs(opt::InputArgList &args); 77 78 bool elf::link(ArrayRef<const char *> args, bool canExitEarly, 79 raw_ostream &stdoutOS, raw_ostream &stderrOS) { 80 lld::stdoutOS = &stdoutOS; 81 lld::stderrOS = &stderrOS; 82 83 errorHandler().cleanupCallback = []() { 84 freeArena(); 85 86 inputSections.clear(); 87 outputSections.clear(); 88 archiveFiles.clear(); 89 binaryFiles.clear(); 90 bitcodeFiles.clear(); 91 lazyObjFiles.clear(); 92 objectFiles.clear(); 93 sharedFiles.clear(); 94 backwardReferences.clear(); 95 96 tar = nullptr; 97 memset(&in, 0, sizeof(in)); 98 99 partitions = {Partition()}; 100 101 SharedFile::vernauxNum = 0; 102 }; 103 104 errorHandler().logName = args::getFilenameWithoutExe(args[0]); 105 errorHandler().errorLimitExceededMsg = 106 "too many errors emitted, stopping now (use " 107 "-error-limit=0 to see all errors)"; 108 errorHandler().exitEarly = canExitEarly; 109 stderrOS.enable_colors(stderrOS.has_colors()); 110 111 config = make<Configuration>(); 112 driver = make<LinkerDriver>(); 113 script = make<LinkerScript>(); 114 symtab = make<SymbolTable>(); 115 116 partitions = {Partition()}; 117 118 config->progName = args[0]; 119 120 driver->main(args); 121 122 // Exit immediately if we don't need to return to the caller. 123 // This saves time because the overhead of calling destructors 124 // for all globally-allocated objects is not negligible. 125 if (canExitEarly) 126 exitLld(errorCount() ? 1 : 0); 127 128 bool ret = errorCount() == 0; 129 if (!canExitEarly) 130 errorHandler().reset(); 131 return ret; 132 } 133 134 // Parses a linker -m option. 135 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) { 136 uint8_t osabi = 0; 137 StringRef s = emul; 138 if (s.endswith("_fbsd")) { 139 s = s.drop_back(5); 140 osabi = ELFOSABI_FREEBSD; 141 } 142 143 std::pair<ELFKind, uint16_t> ret = 144 StringSwitch<std::pair<ELFKind, uint16_t>>(s) 145 .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec", 146 {ELF64LEKind, EM_AARCH64}) 147 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 148 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 149 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 150 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 151 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV}) 152 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC}) 153 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 154 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 155 .Case("elf64lriscv", {ELF64LEKind, EM_RISCV}) 156 .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 157 .Case("elf64lppc", {ELF64LEKind, EM_PPC64}) 158 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 159 .Case("elf_i386", {ELF32LEKind, EM_386}) 160 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 161 .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9}) 162 .Default({ELFNoneKind, EM_NONE}); 163 164 if (ret.first == ELFNoneKind) 165 error("unknown emulation: " + emul); 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 for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers()) 195 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); 196 197 return v; 198 } 199 200 // Opens a file and create a file object. Path has to be resolved already. 201 void LinkerDriver::addFile(StringRef path, bool withLOption) { 202 using namespace sys::fs; 203 204 Optional<MemoryBufferRef> buffer = readFile(path); 205 if (!buffer.hasValue()) 206 return; 207 MemoryBufferRef mbref = *buffer; 208 209 if (config->formatBinary) { 210 files.push_back(make<BinaryFile>(mbref)); 211 return; 212 } 213 214 switch (identify_magic(mbref.getBuffer())) { 215 case file_magic::unknown: 216 readLinkerScript(mbref); 217 return; 218 case file_magic::archive: { 219 // Handle -whole-archive. 220 if (inWholeArchive) { 221 for (const auto &p : getArchiveMembers(mbref)) 222 files.push_back(createObjectFile(p.first, path, p.second)); 223 return; 224 } 225 226 std::unique_ptr<Archive> file = 227 CHECK(Archive::create(mbref), path + ": failed to parse archive"); 228 229 // If an archive file has no symbol table, it is likely that a user 230 // is attempting LTO and using a default ar command that doesn't 231 // understand the LLVM bitcode file. It is a pretty common error, so 232 // we'll handle it as if it had a symbol table. 233 if (!file->isEmpty() && !file->hasSymbolTable()) { 234 // Check if all members are bitcode files. If not, ignore, which is the 235 // default action without the LTO hack described above. 236 for (const std::pair<MemoryBufferRef, uint64_t> &p : 237 getArchiveMembers(mbref)) 238 if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) { 239 error(path + ": archive has no index; run ranlib to add one"); 240 return; 241 } 242 243 for (const std::pair<MemoryBufferRef, uint64_t> &p : 244 getArchiveMembers(mbref)) 245 files.push_back(make<LazyObjFile>(p.first, path, p.second)); 246 return; 247 } 248 249 // Handle the regular case. 250 files.push_back(make<ArchiveFile>(std::move(file))); 251 return; 252 } 253 case file_magic::elf_shared_object: 254 if (config->isStatic || config->relocatable) { 255 error("attempted static link of dynamic object " + path); 256 return; 257 } 258 259 // DSOs usually have DT_SONAME tags in their ELF headers, and the 260 // sonames are used to identify DSOs. But if they are missing, 261 // they are identified by filenames. We don't know whether the new 262 // file has a DT_SONAME or not because we haven't parsed it yet. 263 // Here, we set the default soname for the file because we might 264 // need it later. 265 // 266 // If a file was specified by -lfoo, the directory part is not 267 // significant, as a user did not specify it. This behavior is 268 // compatible with GNU. 269 files.push_back( 270 make<SharedFile>(mbref, withLOption ? path::filename(path) : path)); 271 return; 272 case file_magic::bitcode: 273 case file_magic::elf_relocatable: 274 if (inLib) 275 files.push_back(make<LazyObjFile>(mbref, "", 0)); 276 else 277 files.push_back(createObjectFile(mbref)); 278 break; 279 default: 280 error(path + ": unknown file type"); 281 } 282 } 283 284 // Add a given library by searching it from input search paths. 285 void LinkerDriver::addLibrary(StringRef name) { 286 if (Optional<std::string> path = searchLibrary(name)) 287 addFile(*path, /*withLOption=*/true); 288 else 289 error("unable to find library -l" + name); 290 } 291 292 // This function is called on startup. We need this for LTO since 293 // LTO calls LLVM functions to compile bitcode files to native code. 294 // Technically this can be delayed until we read bitcode files, but 295 // we don't bother to do lazily because the initialization is fast. 296 static void initLLVM() { 297 InitializeAllTargets(); 298 InitializeAllTargetMCs(); 299 InitializeAllAsmPrinters(); 300 InitializeAllAsmParsers(); 301 } 302 303 // Some command line options or some combinations of them are not allowed. 304 // This function checks for such errors. 305 static void checkOptions() { 306 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 307 // table which is a relatively new feature. 308 if (config->emachine == EM_MIPS && config->gnuHash) 309 error("the .gnu.hash section is not compatible with the MIPS target"); 310 311 if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64) 312 error("--fix-cortex-a53-843419 is only supported on AArch64 targets"); 313 314 if (config->fixCortexA8 && config->emachine != EM_ARM) 315 error("--fix-cortex-a8 is only supported on ARM targets"); 316 317 if (config->tocOptimize && config->emachine != EM_PPC64) 318 error("--toc-optimize is only supported on the PowerPC64 target"); 319 320 if (config->pcRelOptimize && config->emachine != EM_PPC64) 321 error("--pcrel--optimize is only supported on the PowerPC64 target"); 322 323 if (config->pie && config->shared) 324 error("-shared and -pie may not be used together"); 325 326 if (!config->shared && !config->filterList.empty()) 327 error("-F may not be used without -shared"); 328 329 if (!config->shared && !config->auxiliaryList.empty()) 330 error("-f may not be used without -shared"); 331 332 if (!config->relocatable && !config->defineCommon) 333 error("-no-define-common not supported in non relocatable output"); 334 335 if (config->strip == StripPolicy::All && config->emitRelocs) 336 error("--strip-all and --emit-relocs may not be used together"); 337 338 if (config->zText && config->zIfuncNoplt) 339 error("-z text and -z ifunc-noplt may not be used together"); 340 341 if (config->relocatable) { 342 if (config->shared) 343 error("-r and -shared may not be used together"); 344 if (config->gdbIndex) 345 error("-r and --gdb-index may not be used together"); 346 if (config->icf != ICFLevel::None) 347 error("-r and --icf may not be used together"); 348 if (config->pie) 349 error("-r and -pie may not be used together"); 350 if (config->exportDynamic) 351 error("-r and --export-dynamic may not be used together"); 352 } 353 354 if (config->executeOnly) { 355 if (config->emachine != EM_AARCH64) 356 error("-execute-only is only supported on AArch64 targets"); 357 358 if (config->singleRoRx && !script->hasSectionsCommand) 359 error("-execute-only and -no-rosegment cannot be used together"); 360 } 361 362 if (config->zRetpolineplt && config->zForceIbt) 363 error("-z force-ibt may not be used with -z retpolineplt"); 364 365 if (config->emachine != EM_AARCH64) { 366 if (config->zPacPlt) 367 error("-z pac-plt only supported on AArch64"); 368 if (config->zForceBti) 369 error("-z force-bti only supported on AArch64"); 370 } 371 } 372 373 static const char *getReproduceOption(opt::InputArgList &args) { 374 if (auto *arg = args.getLastArg(OPT_reproduce)) 375 return arg->getValue(); 376 return getenv("LLD_REPRODUCE"); 377 } 378 379 static bool hasZOption(opt::InputArgList &args, StringRef key) { 380 for (auto *arg : args.filtered(OPT_z)) 381 if (key == arg->getValue()) 382 return true; 383 return false; 384 } 385 386 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2, 387 bool Default) { 388 for (auto *arg : args.filtered_reverse(OPT_z)) { 389 if (k1 == arg->getValue()) 390 return true; 391 if (k2 == arg->getValue()) 392 return false; 393 } 394 return Default; 395 } 396 397 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) { 398 for (auto *arg : args.filtered_reverse(OPT_z)) { 399 StringRef v = arg->getValue(); 400 if (v == "noseparate-code") 401 return SeparateSegmentKind::None; 402 if (v == "separate-code") 403 return SeparateSegmentKind::Code; 404 if (v == "separate-loadable-segments") 405 return SeparateSegmentKind::Loadable; 406 } 407 return SeparateSegmentKind::None; 408 } 409 410 static GnuStackKind getZGnuStack(opt::InputArgList &args) { 411 for (auto *arg : args.filtered_reverse(OPT_z)) { 412 if (StringRef("execstack") == arg->getValue()) 413 return GnuStackKind::Exec; 414 if (StringRef("noexecstack") == arg->getValue()) 415 return GnuStackKind::NoExec; 416 if (StringRef("nognustack") == arg->getValue()) 417 return GnuStackKind::None; 418 } 419 420 return GnuStackKind::NoExec; 421 } 422 423 static uint8_t getZStartStopVisibility(opt::InputArgList &args) { 424 for (auto *arg : args.filtered_reverse(OPT_z)) { 425 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('='); 426 if (kv.first == "start-stop-visibility") { 427 if (kv.second == "default") 428 return STV_DEFAULT; 429 else if (kv.second == "internal") 430 return STV_INTERNAL; 431 else if (kv.second == "hidden") 432 return STV_HIDDEN; 433 else if (kv.second == "protected") 434 return STV_PROTECTED; 435 error("unknown -z start-stop-visibility= value: " + StringRef(kv.second)); 436 } 437 } 438 return STV_PROTECTED; 439 } 440 441 static bool isKnownZFlag(StringRef s) { 442 return s == "combreloc" || s == "copyreloc" || s == "defs" || 443 s == "execstack" || s == "force-bti" || s == "force-ibt" || 444 s == "global" || s == "hazardplt" || s == "ifunc-noplt" || 445 s == "initfirst" || s == "interpose" || 446 s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" || 447 s == "separate-code" || s == "separate-loadable-segments" || 448 s == "nocombreloc" || s == "nocopyreloc" || s == "nodefaultlib" || 449 s == "nodelete" || s == "nodlopen" || s == "noexecstack" || 450 s == "nognustack" || s == "nokeep-text-section-prefix" || 451 s == "norelro" || s == "noseparate-code" || s == "notext" || 452 s == "now" || s == "origin" || s == "pac-plt" || s == "rel" || 453 s == "rela" || s == "relro" || s == "retpolineplt" || 454 s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" || 455 s == "wxneeded" || s.startswith("common-page-size=") || 456 s.startswith("dead-reloc-in-nonalloc=") || 457 s.startswith("max-page-size=") || s.startswith("stack-size=") || 458 s.startswith("start-stop-visibility="); 459 } 460 461 // Report an error for an unknown -z option. 462 static void checkZOptions(opt::InputArgList &args) { 463 for (auto *arg : args.filtered(OPT_z)) 464 if (!isKnownZFlag(arg->getValue())) 465 error("unknown -z value: " + StringRef(arg->getValue())); 466 } 467 468 void LinkerDriver::main(ArrayRef<const char *> argsArr) { 469 ELFOptTable parser; 470 opt::InputArgList args = parser.parse(argsArr.slice(1)); 471 472 // Interpret this flag early because error() depends on them. 473 errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20); 474 checkZOptions(args); 475 476 // Handle -help 477 if (args.hasArg(OPT_help)) { 478 printHelp(); 479 return; 480 } 481 482 // Handle -v or -version. 483 // 484 // A note about "compatible with GNU linkers" message: this is a hack for 485 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and 486 // still the newest version in March 2017) or earlier to recognize LLD as 487 // a GNU compatible linker. As long as an output for the -v option 488 // contains "GNU" or "with BFD", they recognize us as GNU-compatible. 489 // 490 // This is somewhat ugly hack, but in reality, we had no choice other 491 // than doing this. Considering the very long release cycle of Libtool, 492 // it is not easy to improve it to recognize LLD as a GNU compatible 493 // linker in a timely manner. Even if we can make it, there are still a 494 // lot of "configure" scripts out there that are generated by old version 495 // of Libtool. We cannot convince every software developer to migrate to 496 // the latest version and re-generate scripts. So we have this hack. 497 if (args.hasArg(OPT_v) || args.hasArg(OPT_version)) 498 message(getLLDVersion() + " (compatible with GNU linkers)"); 499 500 if (const char *path = getReproduceOption(args)) { 501 // Note that --reproduce is a debug option so you can ignore it 502 // if you are trying to understand the whole picture of the code. 503 Expected<std::unique_ptr<TarWriter>> errOrWriter = 504 TarWriter::create(path, path::stem(path)); 505 if (errOrWriter) { 506 tar = std::move(*errOrWriter); 507 tar->append("response.txt", createResponseFile(args)); 508 tar->append("version.txt", getLLDVersion() + "\n"); 509 StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 510 if (!ltoSampleProfile.empty()) 511 readFile(ltoSampleProfile); 512 } else { 513 error("--reproduce: " + toString(errOrWriter.takeError())); 514 } 515 } 516 517 readConfigs(args); 518 519 // The behavior of -v or --version is a bit strange, but this is 520 // needed for compatibility with GNU linkers. 521 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT)) 522 return; 523 if (args.hasArg(OPT_version)) 524 return; 525 526 // Initialize time trace profiler. 527 if (config->timeTraceEnabled) 528 timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName); 529 530 { 531 llvm::TimeTraceScope timeScope("ExecuteLinker"); 532 533 initLLVM(); 534 createFiles(args); 535 if (errorCount()) 536 return; 537 538 inferMachineType(); 539 setConfigs(args); 540 checkOptions(); 541 if (errorCount()) 542 return; 543 544 // The Target instance handles target-specific stuff, such as applying 545 // relocations or writing a PLT section. It also contains target-dependent 546 // values such as a default image base address. 547 target = getTarget(); 548 549 switch (config->ekind) { 550 case ELF32LEKind: 551 link<ELF32LE>(args); 552 break; 553 case ELF32BEKind: 554 link<ELF32BE>(args); 555 break; 556 case ELF64LEKind: 557 link<ELF64LE>(args); 558 break; 559 case ELF64BEKind: 560 link<ELF64BE>(args); 561 break; 562 default: 563 llvm_unreachable("unknown Config->EKind"); 564 } 565 } 566 567 if (config->timeTraceEnabled) { 568 if (auto E = timeTraceProfilerWrite(args.getLastArgValue(OPT_time_trace_file_eq).str(), 569 config->outputFile)) { 570 handleAllErrors(std::move(E), [&](const StringError &SE) { 571 error(SE.getMessage()); 572 }); 573 return; 574 } 575 576 timeTraceProfilerCleanup(); 577 } 578 } 579 580 static std::string getRpath(opt::InputArgList &args) { 581 std::vector<StringRef> v = args::getStrings(args, OPT_rpath); 582 return llvm::join(v.begin(), v.end(), ":"); 583 } 584 585 // Determines what we should do if there are remaining unresolved 586 // symbols after the name resolution. 587 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &args) { 588 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols, 589 OPT_warn_unresolved_symbols, true) 590 ? UnresolvedPolicy::ReportError 591 : UnresolvedPolicy::Warn; 592 593 // Process the last of -unresolved-symbols, -no-undefined or -z defs. 594 for (auto *arg : llvm::reverse(args)) { 595 switch (arg->getOption().getID()) { 596 case OPT_unresolved_symbols: { 597 StringRef s = arg->getValue(); 598 if (s == "ignore-all" || s == "ignore-in-object-files") 599 return UnresolvedPolicy::Ignore; 600 if (s == "ignore-in-shared-libs" || s == "report-all") 601 return errorOrWarn; 602 error("unknown --unresolved-symbols value: " + s); 603 continue; 604 } 605 case OPT_no_undefined: 606 return errorOrWarn; 607 case OPT_z: 608 if (StringRef(arg->getValue()) == "defs") 609 return errorOrWarn; 610 if (StringRef(arg->getValue()) == "undefs") 611 return UnresolvedPolicy::Ignore; 612 continue; 613 } 614 } 615 616 // -shared implies -unresolved-symbols=ignore-all because missing 617 // symbols are likely to be resolved at runtime using other DSOs. 618 if (config->shared) 619 return UnresolvedPolicy::Ignore; 620 return errorOrWarn; 621 } 622 623 static Target2Policy getTarget2(opt::InputArgList &args) { 624 StringRef s = args.getLastArgValue(OPT_target2, "got-rel"); 625 if (s == "rel") 626 return Target2Policy::Rel; 627 if (s == "abs") 628 return Target2Policy::Abs; 629 if (s == "got-rel") 630 return Target2Policy::GotRel; 631 error("unknown --target2 option: " + s); 632 return Target2Policy::GotRel; 633 } 634 635 static bool isOutputFormatBinary(opt::InputArgList &args) { 636 StringRef s = args.getLastArgValue(OPT_oformat, "elf"); 637 if (s == "binary") 638 return true; 639 if (!s.startswith("elf")) 640 error("unknown --oformat value: " + s); 641 return false; 642 } 643 644 static DiscardPolicy getDiscard(opt::InputArgList &args) { 645 auto *arg = 646 args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 647 if (!arg) 648 return DiscardPolicy::Default; 649 if (arg->getOption().getID() == OPT_discard_all) 650 return DiscardPolicy::All; 651 if (arg->getOption().getID() == OPT_discard_locals) 652 return DiscardPolicy::Locals; 653 return DiscardPolicy::None; 654 } 655 656 static StringRef getDynamicLinker(opt::InputArgList &args) { 657 auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 658 if (!arg) 659 return ""; 660 if (arg->getOption().getID() == OPT_no_dynamic_linker) { 661 // --no-dynamic-linker suppresses undefined weak symbols in .dynsym 662 config->noDynamicLinker = true; 663 return ""; 664 } 665 return arg->getValue(); 666 } 667 668 static ICFLevel getICF(opt::InputArgList &args) { 669 auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all); 670 if (!arg || arg->getOption().getID() == OPT_icf_none) 671 return ICFLevel::None; 672 if (arg->getOption().getID() == OPT_icf_safe) 673 return ICFLevel::Safe; 674 return ICFLevel::All; 675 } 676 677 static StripPolicy getStrip(opt::InputArgList &args) { 678 if (args.hasArg(OPT_relocatable)) 679 return StripPolicy::None; 680 681 auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug); 682 if (!arg) 683 return StripPolicy::None; 684 if (arg->getOption().getID() == OPT_strip_all) 685 return StripPolicy::All; 686 return StripPolicy::Debug; 687 } 688 689 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args, 690 const opt::Arg &arg) { 691 uint64_t va = 0; 692 if (s.startswith("0x")) 693 s = s.drop_front(2); 694 if (!to_integer(s, va, 16)) 695 error("invalid argument: " + arg.getAsString(args)); 696 return va; 697 } 698 699 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) { 700 StringMap<uint64_t> ret; 701 for (auto *arg : args.filtered(OPT_section_start)) { 702 StringRef name; 703 StringRef addr; 704 std::tie(name, addr) = StringRef(arg->getValue()).split('='); 705 ret[name] = parseSectionAddress(addr, args, *arg); 706 } 707 708 if (auto *arg = args.getLastArg(OPT_Ttext)) 709 ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg); 710 if (auto *arg = args.getLastArg(OPT_Tdata)) 711 ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg); 712 if (auto *arg = args.getLastArg(OPT_Tbss)) 713 ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg); 714 return ret; 715 } 716 717 static SortSectionPolicy getSortSection(opt::InputArgList &args) { 718 StringRef s = args.getLastArgValue(OPT_sort_section); 719 if (s == "alignment") 720 return SortSectionPolicy::Alignment; 721 if (s == "name") 722 return SortSectionPolicy::Name; 723 if (!s.empty()) 724 error("unknown --sort-section rule: " + s); 725 return SortSectionPolicy::Default; 726 } 727 728 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) { 729 StringRef s = args.getLastArgValue(OPT_orphan_handling, "place"); 730 if (s == "warn") 731 return OrphanHandlingPolicy::Warn; 732 if (s == "error") 733 return OrphanHandlingPolicy::Error; 734 if (s != "place") 735 error("unknown --orphan-handling mode: " + s); 736 return OrphanHandlingPolicy::Place; 737 } 738 739 // Parse --build-id or --build-id=<style>. We handle "tree" as a 740 // synonym for "sha1" because all our hash functions including 741 // -build-id=sha1 are actually tree hashes for performance reasons. 742 static std::pair<BuildIdKind, std::vector<uint8_t>> 743 getBuildId(opt::InputArgList &args) { 744 auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq); 745 if (!arg) 746 return {BuildIdKind::None, {}}; 747 748 if (arg->getOption().getID() == OPT_build_id) 749 return {BuildIdKind::Fast, {}}; 750 751 StringRef s = arg->getValue(); 752 if (s == "fast") 753 return {BuildIdKind::Fast, {}}; 754 if (s == "md5") 755 return {BuildIdKind::Md5, {}}; 756 if (s == "sha1" || s == "tree") 757 return {BuildIdKind::Sha1, {}}; 758 if (s == "uuid") 759 return {BuildIdKind::Uuid, {}}; 760 if (s.startswith("0x")) 761 return {BuildIdKind::Hexstring, parseHex(s.substr(2))}; 762 763 if (s != "none") 764 error("unknown --build-id style: " + s); 765 return {BuildIdKind::None, {}}; 766 } 767 768 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) { 769 StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none"); 770 if (s == "android") 771 return {true, false}; 772 if (s == "relr") 773 return {false, true}; 774 if (s == "android+relr") 775 return {true, true}; 776 777 if (s != "none") 778 error("unknown -pack-dyn-relocs format: " + s); 779 return {false, false}; 780 } 781 782 static void readCallGraph(MemoryBufferRef mb) { 783 // Build a map from symbol name to section 784 DenseMap<StringRef, Symbol *> map; 785 for (InputFile *file : objectFiles) 786 for (Symbol *sym : file->getSymbols()) 787 map[sym->getName()] = sym; 788 789 auto findSection = [&](StringRef name) -> InputSectionBase * { 790 Symbol *sym = map.lookup(name); 791 if (!sym) { 792 if (config->warnSymbolOrdering) 793 warn(mb.getBufferIdentifier() + ": no such symbol: " + name); 794 return nullptr; 795 } 796 maybeWarnUnorderableSymbol(sym); 797 798 if (Defined *dr = dyn_cast_or_null<Defined>(sym)) 799 return dyn_cast_or_null<InputSectionBase>(dr->section); 800 return nullptr; 801 }; 802 803 for (StringRef line : args::getLines(mb)) { 804 SmallVector<StringRef, 3> fields; 805 line.split(fields, ' '); 806 uint64_t count; 807 808 if (fields.size() != 3 || !to_integer(fields[2], count)) { 809 error(mb.getBufferIdentifier() + ": parse error"); 810 return; 811 } 812 813 if (InputSectionBase *from = findSection(fields[0])) 814 if (InputSectionBase *to = findSection(fields[1])) 815 config->callGraphProfile[std::make_pair(from, to)] += count; 816 } 817 } 818 819 template <class ELFT> static void readCallGraphsFromObjectFiles() { 820 for (auto file : objectFiles) { 821 auto *obj = cast<ObjFile<ELFT>>(file); 822 823 for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) { 824 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from)); 825 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to)); 826 if (!fromSym || !toSym) 827 continue; 828 829 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section); 830 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section); 831 if (from && to) 832 config->callGraphProfile[{from, to}] += cgpe.cgp_weight; 833 } 834 } 835 } 836 837 static bool getCompressDebugSections(opt::InputArgList &args) { 838 StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none"); 839 if (s == "none") 840 return false; 841 if (s != "zlib") 842 error("unknown --compress-debug-sections value: " + s); 843 if (!zlib::isAvailable()) 844 error("--compress-debug-sections: zlib is not available"); 845 return true; 846 } 847 848 static StringRef getAliasSpelling(opt::Arg *arg) { 849 if (const opt::Arg *alias = arg->getAlias()) 850 return alias->getSpelling(); 851 return arg->getSpelling(); 852 } 853 854 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 855 unsigned id) { 856 auto *arg = args.getLastArg(id); 857 if (!arg) 858 return {"", ""}; 859 860 StringRef s = arg->getValue(); 861 std::pair<StringRef, StringRef> ret = s.split(';'); 862 if (ret.second.empty()) 863 error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s); 864 return ret; 865 } 866 867 // Parse the symbol ordering file and warn for any duplicate entries. 868 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) { 869 SetVector<StringRef> names; 870 for (StringRef s : args::getLines(mb)) 871 if (!names.insert(s) && config->warnSymbolOrdering) 872 warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s); 873 874 return names.takeVector(); 875 } 876 877 static bool getIsRela(opt::InputArgList &args) { 878 // If -z rel or -z rela is specified, use the last option. 879 for (auto *arg : args.filtered_reverse(OPT_z)) { 880 StringRef s(arg->getValue()); 881 if (s == "rel") 882 return false; 883 if (s == "rela") 884 return true; 885 } 886 887 // Otherwise use the psABI defined relocation entry format. 888 uint16_t m = config->emachine; 889 return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC || 890 m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64; 891 } 892 893 static void parseClangOption(StringRef opt, const Twine &msg) { 894 std::string err; 895 raw_string_ostream os(err); 896 897 const char *argv[] = {config->progName.data(), opt.data()}; 898 if (cl::ParseCommandLineOptions(2, argv, "", &os)) 899 return; 900 os.flush(); 901 error(msg + ": " + StringRef(err).trim()); 902 } 903 904 // Initializes Config members by the command line options. 905 static void readConfigs(opt::InputArgList &args) { 906 errorHandler().verbose = args.hasArg(OPT_verbose); 907 errorHandler().fatalWarnings = 908 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false); 909 errorHandler().vsDiagnostics = 910 args.hasArg(OPT_visual_studio_diagnostics_format, false); 911 912 config->allowMultipleDefinition = 913 args.hasFlag(OPT_allow_multiple_definition, 914 OPT_no_allow_multiple_definition, false) || 915 hasZOption(args, "muldefs"); 916 config->allowShlibUndefined = 917 args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined, 918 args.hasArg(OPT_shared)); 919 config->auxiliaryList = args::getStrings(args, OPT_auxiliary); 920 config->bsymbolic = args.hasArg(OPT_Bsymbolic); 921 config->bsymbolicFunctions = args.hasArg(OPT_Bsymbolic_functions); 922 config->checkSections = 923 args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 924 config->chroot = args.getLastArgValue(OPT_chroot); 925 config->compressDebugSections = getCompressDebugSections(args); 926 config->cref = args.hasFlag(OPT_cref, OPT_no_cref, false); 927 config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common, 928 !args.hasArg(OPT_relocatable)); 929 config->optimizeBBJumps = 930 args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false); 931 config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true); 932 config->dependencyFile = args.getLastArgValue(OPT_dependency_file); 933 config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true); 934 config->disableVerify = args.hasArg(OPT_disable_verify); 935 config->discard = getDiscard(args); 936 config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq); 937 config->dynamicLinker = getDynamicLinker(args); 938 config->ehFrameHdr = 939 args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 940 config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false); 941 config->emitRelocs = args.hasArg(OPT_emit_relocs); 942 config->callGraphProfileSort = args.hasFlag( 943 OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true); 944 config->enableNewDtags = 945 args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 946 config->entry = args.getLastArgValue(OPT_entry); 947 config->executeOnly = 948 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 949 config->exportDynamic = 950 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 951 config->filterList = args::getStrings(args, OPT_filter); 952 config->fini = args.getLastArgValue(OPT_fini, "_fini"); 953 config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) && 954 !args.hasArg(OPT_relocatable); 955 config->fixCortexA8 = 956 args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable); 957 config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 958 config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 959 config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 960 config->icf = getICF(args); 961 config->ignoreDataAddressEquality = 962 args.hasArg(OPT_ignore_data_address_equality); 963 config->ignoreFunctionAddressEquality = 964 args.hasArg(OPT_ignore_function_address_equality); 965 config->init = args.getLastArgValue(OPT_init, "_init"); 966 config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline); 967 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 968 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 969 config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager); 970 config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm); 971 config->ltoNewPassManager = args.hasArg(OPT_lto_new_pass_manager); 972 config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes); 973 config->ltoWholeProgramVisibility = 974 args.hasArg(OPT_lto_whole_program_visibility); 975 config->ltoo = args::getInteger(args, OPT_lto_O, 2); 976 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq); 977 config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1); 978 config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 979 config->ltoBasicBlockSections = 980 args.getLastArgValue(OPT_lto_basic_block_sections); 981 config->ltoUniqueBasicBlockSectionNames = 982 args.hasFlag(OPT_lto_unique_basic_block_section_names, 983 OPT_no_lto_unique_basic_block_section_names, false); 984 config->mapFile = args.getLastArgValue(OPT_Map); 985 config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0); 986 config->mergeArmExidx = 987 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 988 config->mmapOutputFile = 989 args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true); 990 config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 991 config->noinhibitExec = args.hasArg(OPT_noinhibit_exec); 992 config->nostdlib = args.hasArg(OPT_nostdlib); 993 config->oFormatBinary = isOutputFormatBinary(args); 994 config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false); 995 config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename); 996 config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes); 997 config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness); 998 config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format); 999 config->optimize = args::getInteger(args, OPT_O, 1); 1000 config->orphanHandling = getOrphanHandling(args); 1001 config->outputFile = args.getLastArgValue(OPT_o); 1002 config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false); 1003 config->printIcfSections = 1004 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 1005 config->printGcSections = 1006 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 1007 config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats); 1008 config->printSymbolOrder = 1009 args.getLastArgValue(OPT_print_symbol_order); 1010 config->rpath = getRpath(args); 1011 config->relocatable = args.hasArg(OPT_relocatable); 1012 config->saveTemps = args.hasArg(OPT_save_temps); 1013 if (args.hasArg(OPT_shuffle_sections)) 1014 config->shuffleSectionSeed = args::getInteger(args, OPT_shuffle_sections, 0); 1015 config->searchPaths = args::getStrings(args, OPT_library_path); 1016 config->sectionStartMap = getSectionStartMap(args); 1017 config->shared = args.hasArg(OPT_shared); 1018 config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true); 1019 config->soName = args.getLastArgValue(OPT_soname); 1020 config->sortSection = getSortSection(args); 1021 config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384); 1022 config->strip = getStrip(args); 1023 config->sysroot = args.getLastArgValue(OPT_sysroot); 1024 config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 1025 config->target2 = getTarget2(args); 1026 config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir); 1027 config->thinLTOCachePolicy = CHECK( 1028 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)), 1029 "--thinlto-cache-policy: invalid cache policy"); 1030 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 1031 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 1032 args.hasArg(OPT_thinlto_index_only_eq); 1033 config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq); 1034 config->thinLTOObjectSuffixReplace = 1035 getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq); 1036 config->thinLTOPrefixReplace = 1037 getOldNewOptions(args, OPT_thinlto_prefix_replace_eq); 1038 config->thinLTOModulesToCompile = 1039 args::getStrings(args, OPT_thinlto_single_module_eq); 1040 config->timeTraceEnabled = args.hasArg(OPT_time_trace); 1041 config->timeTraceGranularity = 1042 args::getInteger(args, OPT_time_trace_granularity, 500); 1043 config->trace = args.hasArg(OPT_trace); 1044 config->undefined = args::getStrings(args, OPT_undefined); 1045 config->undefinedVersion = 1046 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true); 1047 config->unique = args.hasArg(OPT_unique); 1048 config->useAndroidRelrTags = args.hasFlag( 1049 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 1050 config->unresolvedSymbols = getUnresolvedSymbolPolicy(args); 1051 config->warnBackrefs = 1052 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 1053 config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 1054 config->warnIfuncTextrel = 1055 args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false); 1056 config->warnSymbolOrdering = 1057 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 1058 config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true); 1059 config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true); 1060 config->zForceBti = hasZOption(args, "force-bti"); 1061 config->zForceIbt = hasZOption(args, "force-ibt"); 1062 config->zGlobal = hasZOption(args, "global"); 1063 config->zGnustack = getZGnuStack(args); 1064 config->zHazardplt = hasZOption(args, "hazardplt"); 1065 config->zIfuncNoplt = hasZOption(args, "ifunc-noplt"); 1066 config->zInitfirst = hasZOption(args, "initfirst"); 1067 config->zInterpose = hasZOption(args, "interpose"); 1068 config->zKeepTextSectionPrefix = getZFlag( 1069 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 1070 config->zNodefaultlib = hasZOption(args, "nodefaultlib"); 1071 config->zNodelete = hasZOption(args, "nodelete"); 1072 config->zNodlopen = hasZOption(args, "nodlopen"); 1073 config->zNow = getZFlag(args, "now", "lazy", false); 1074 config->zOrigin = hasZOption(args, "origin"); 1075 config->zPacPlt = hasZOption(args, "pac-plt"); 1076 config->zRelro = getZFlag(args, "relro", "norelro", true); 1077 config->zRetpolineplt = hasZOption(args, "retpolineplt"); 1078 config->zRodynamic = hasZOption(args, "rodynamic"); 1079 config->zSeparate = getZSeparate(args); 1080 config->zShstk = hasZOption(args, "shstk"); 1081 config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0); 1082 config->zStartStopVisibility = getZStartStopVisibility(args); 1083 config->zText = getZFlag(args, "text", "notext", true); 1084 config->zWxneeded = hasZOption(args, "wxneeded"); 1085 1086 for (opt::Arg *arg : args.filtered(OPT_z)) { 1087 std::pair<StringRef, StringRef> option = 1088 StringRef(arg->getValue()).split('='); 1089 if (option.first != "dead-reloc-in-nonalloc") 1090 continue; 1091 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: "; 1092 std::pair<StringRef, StringRef> kv = option.second.split('='); 1093 if (kv.first.empty() || kv.second.empty()) { 1094 error(errPrefix + "expected <section_glob>=<value>"); 1095 continue; 1096 } 1097 uint64_t v; 1098 if (!to_integer(kv.second, v)) 1099 error(errPrefix + "expected a non-negative integer, but got '" + 1100 kv.second + "'"); 1101 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1102 config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v); 1103 else 1104 error(errPrefix + toString(pat.takeError())); 1105 } 1106 1107 cl::ResetAllOptionOccurrences(); 1108 1109 // Parse LTO options. 1110 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq)) 1111 parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())), 1112 arg->getSpelling()); 1113 1114 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus)) 1115 parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling()); 1116 1117 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or 1118 // relative path. Just ignore. If not ended with "lto-wrapper", consider it an 1119 // unsupported LLVMgold.so option and error. 1120 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) 1121 if (!StringRef(arg->getValue()).endswith("lto-wrapper")) 1122 error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() + 1123 "'"); 1124 1125 // Parse -mllvm options. 1126 for (auto *arg : args.filtered(OPT_mllvm)) 1127 parseClangOption(arg->getValue(), arg->getSpelling()); 1128 1129 // --threads= takes a positive integer and provides the default value for 1130 // --thinlto-jobs=. 1131 if (auto *arg = args.getLastArg(OPT_threads)) { 1132 StringRef v(arg->getValue()); 1133 unsigned threads = 0; 1134 if (!llvm::to_integer(v, threads, 0) || threads == 0) 1135 error(arg->getSpelling() + ": expected a positive integer, but got '" + 1136 arg->getValue() + "'"); 1137 parallel::strategy = hardware_concurrency(threads); 1138 config->thinLTOJobs = v; 1139 } 1140 if (auto *arg = args.getLastArg(OPT_thinlto_jobs)) 1141 config->thinLTOJobs = arg->getValue(); 1142 1143 if (config->ltoo > 3) 1144 error("invalid optimization level for LTO: " + Twine(config->ltoo)); 1145 if (config->ltoPartitions == 0) 1146 error("--lto-partitions: number of threads must be > 0"); 1147 if (!get_threadpool_strategy(config->thinLTOJobs)) 1148 error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 1149 1150 if (config->splitStackAdjustSize < 0) 1151 error("--split-stack-adjust-size: size must be >= 0"); 1152 1153 // The text segment is traditionally the first segment, whose address equals 1154 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment 1155 // is an old-fashioned option that does not play well with lld's layout. 1156 // Suggest --image-base as a likely alternative. 1157 if (args.hasArg(OPT_Ttext_segment)) 1158 error("-Ttext-segment is not supported. Use --image-base if you " 1159 "intend to set the base address"); 1160 1161 // Parse ELF{32,64}{LE,BE} and CPU type. 1162 if (auto *arg = args.getLastArg(OPT_m)) { 1163 StringRef s = arg->getValue(); 1164 std::tie(config->ekind, config->emachine, config->osabi) = 1165 parseEmulation(s); 1166 config->mipsN32Abi = 1167 (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32")); 1168 config->emulation = s; 1169 } 1170 1171 // Parse -hash-style={sysv,gnu,both}. 1172 if (auto *arg = args.getLastArg(OPT_hash_style)) { 1173 StringRef s = arg->getValue(); 1174 if (s == "sysv") 1175 config->sysvHash = true; 1176 else if (s == "gnu") 1177 config->gnuHash = true; 1178 else if (s == "both") 1179 config->sysvHash = config->gnuHash = true; 1180 else 1181 error("unknown -hash-style: " + s); 1182 } 1183 1184 if (args.hasArg(OPT_print_map)) 1185 config->mapFile = "-"; 1186 1187 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 1188 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 1189 // it. 1190 if (config->nmagic || config->omagic) 1191 config->zRelro = false; 1192 1193 std::tie(config->buildId, config->buildIdVector) = getBuildId(args); 1194 1195 std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) = 1196 getPackDynRelocs(args); 1197 1198 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){ 1199 if (args.hasArg(OPT_call_graph_ordering_file)) 1200 error("--symbol-ordering-file and --call-graph-order-file " 1201 "may not be used together"); 1202 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){ 1203 config->symbolOrderingFile = getSymbolOrderingFile(*buffer); 1204 // Also need to disable CallGraphProfileSort to prevent 1205 // LLD order symbols with CGProfile 1206 config->callGraphProfileSort = false; 1207 } 1208 } 1209 1210 assert(config->versionDefinitions.empty()); 1211 config->versionDefinitions.push_back({"local", (uint16_t)VER_NDX_LOCAL, {}}); 1212 config->versionDefinitions.push_back( 1213 {"global", (uint16_t)VER_NDX_GLOBAL, {}}); 1214 1215 // If --retain-symbol-file is used, we'll keep only the symbols listed in 1216 // the file and discard all others. 1217 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) { 1218 config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back( 1219 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true}); 1220 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1221 for (StringRef s : args::getLines(*buffer)) 1222 config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back( 1223 {s, /*isExternCpp=*/false, /*hasWildcard=*/false}); 1224 } 1225 1226 for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) { 1227 StringRef pattern(arg->getValue()); 1228 if (Expected<GlobPattern> pat = GlobPattern::create(pattern)) 1229 config->warnBackrefsExclude.push_back(std::move(*pat)); 1230 else 1231 error(arg->getSpelling() + ": " + toString(pat.takeError())); 1232 } 1233 1234 // When producing an executable, --dynamic-list specifies non-local defined 1235 // symbols whith are required to be exported. When producing a shared object, 1236 // symbols not specified by --dynamic-list are non-preemptible. 1237 config->symbolic = 1238 args.hasArg(OPT_Bsymbolic) || args.hasArg(OPT_dynamic_list); 1239 for (auto *arg : args.filtered(OPT_dynamic_list)) 1240 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1241 readDynamicList(*buffer); 1242 1243 // --export-dynamic-symbol specifies additional --dynamic-list symbols if any 1244 // other option expresses a symbolic intention: -no-pie, -pie, -Bsymbolic, 1245 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list. 1246 for (auto *arg : args.filtered(OPT_export_dynamic_symbol)) 1247 config->dynamicList.push_back( 1248 {arg->getValue(), /*isExternCpp=*/false, 1249 /*hasWildcard=*/hasWildcard(arg->getValue())}); 1250 1251 for (auto *arg : args.filtered(OPT_version_script)) 1252 if (Optional<std::string> path = searchScript(arg->getValue())) { 1253 if (Optional<MemoryBufferRef> buffer = readFile(*path)) 1254 readVersionScript(*buffer); 1255 } else { 1256 error(Twine("cannot find version script ") + arg->getValue()); 1257 } 1258 } 1259 1260 // Some Config members do not directly correspond to any particular 1261 // command line options, but computed based on other Config values. 1262 // This function initialize such members. See Config.h for the details 1263 // of these values. 1264 static void setConfigs(opt::InputArgList &args) { 1265 ELFKind k = config->ekind; 1266 uint16_t m = config->emachine; 1267 1268 config->copyRelocs = (config->relocatable || config->emitRelocs); 1269 config->is64 = (k == ELF64LEKind || k == ELF64BEKind); 1270 config->isLE = (k == ELF32LEKind || k == ELF64LEKind); 1271 config->endianness = config->isLE ? endianness::little : endianness::big; 1272 config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS); 1273 config->isPic = config->pie || config->shared; 1274 config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic); 1275 config->wordsize = config->is64 ? 8 : 4; 1276 1277 // ELF defines two different ways to store relocation addends as shown below: 1278 // 1279 // Rel: Addends are stored to the location where relocations are applied. It 1280 // cannot pack the full range of addend values for all relocation types, but 1281 // this only affects relocation types that we don't support emitting as 1282 // dynamic relocations (see getDynRel). 1283 // Rela: Addends are stored as part of relocation entry. 1284 // 1285 // In other words, Rela makes it easy to read addends at the price of extra 1286 // 4 or 8 byte for each relocation entry. 1287 // 1288 // We pick the format for dynamic relocations according to the psABI for each 1289 // processor, but a contrary choice can be made if the dynamic loader 1290 // supports. 1291 config->isRela = getIsRela(args); 1292 1293 // If the output uses REL relocations we must store the dynamic relocation 1294 // addends to the output sections. We also store addends for RELA relocations 1295 // if --apply-dynamic-relocs is used. 1296 // We default to not writing the addends when using RELA relocations since 1297 // any standard conforming tool can find it in r_addend. 1298 config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs, 1299 OPT_no_apply_dynamic_relocs, false) || 1300 !config->isRela; 1301 1302 config->tocOptimize = 1303 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64); 1304 config->pcRelOptimize = 1305 args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64); 1306 } 1307 1308 // Returns a value of "-format" option. 1309 static bool isFormatBinary(StringRef s) { 1310 if (s == "binary") 1311 return true; 1312 if (s == "elf" || s == "default") 1313 return false; 1314 error("unknown -format value: " + s + 1315 " (supported formats: elf, default, binary)"); 1316 return false; 1317 } 1318 1319 void LinkerDriver::createFiles(opt::InputArgList &args) { 1320 // For --{push,pop}-state. 1321 std::vector<std::tuple<bool, bool, bool>> stack; 1322 1323 // Iterate over argv to process input files and positional arguments. 1324 InputFile::isInGroup = false; 1325 for (auto *arg : args) { 1326 switch (arg->getOption().getID()) { 1327 case OPT_library: 1328 addLibrary(arg->getValue()); 1329 break; 1330 case OPT_INPUT: 1331 addFile(arg->getValue(), /*withLOption=*/false); 1332 break; 1333 case OPT_defsym: { 1334 StringRef from; 1335 StringRef to; 1336 std::tie(from, to) = StringRef(arg->getValue()).split('='); 1337 if (from.empty() || to.empty()) 1338 error("-defsym: syntax error: " + StringRef(arg->getValue())); 1339 else 1340 readDefsym(from, MemoryBufferRef(to, "-defsym")); 1341 break; 1342 } 1343 case OPT_script: 1344 if (Optional<std::string> path = searchScript(arg->getValue())) { 1345 if (Optional<MemoryBufferRef> mb = readFile(*path)) 1346 readLinkerScript(*mb); 1347 break; 1348 } 1349 error(Twine("cannot find linker script ") + arg->getValue()); 1350 break; 1351 case OPT_as_needed: 1352 config->asNeeded = true; 1353 break; 1354 case OPT_format: 1355 config->formatBinary = isFormatBinary(arg->getValue()); 1356 break; 1357 case OPT_no_as_needed: 1358 config->asNeeded = false; 1359 break; 1360 case OPT_Bstatic: 1361 case OPT_omagic: 1362 case OPT_nmagic: 1363 config->isStatic = true; 1364 break; 1365 case OPT_Bdynamic: 1366 config->isStatic = false; 1367 break; 1368 case OPT_whole_archive: 1369 inWholeArchive = true; 1370 break; 1371 case OPT_no_whole_archive: 1372 inWholeArchive = false; 1373 break; 1374 case OPT_just_symbols: 1375 if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) { 1376 files.push_back(createObjectFile(*mb)); 1377 files.back()->justSymbols = true; 1378 } 1379 break; 1380 case OPT_start_group: 1381 if (InputFile::isInGroup) 1382 error("nested --start-group"); 1383 InputFile::isInGroup = true; 1384 break; 1385 case OPT_end_group: 1386 if (!InputFile::isInGroup) 1387 error("stray --end-group"); 1388 InputFile::isInGroup = false; 1389 ++InputFile::nextGroupId; 1390 break; 1391 case OPT_start_lib: 1392 if (inLib) 1393 error("nested --start-lib"); 1394 if (InputFile::isInGroup) 1395 error("may not nest --start-lib in --start-group"); 1396 inLib = true; 1397 InputFile::isInGroup = true; 1398 break; 1399 case OPT_end_lib: 1400 if (!inLib) 1401 error("stray --end-lib"); 1402 inLib = false; 1403 InputFile::isInGroup = false; 1404 ++InputFile::nextGroupId; 1405 break; 1406 case OPT_push_state: 1407 stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive); 1408 break; 1409 case OPT_pop_state: 1410 if (stack.empty()) { 1411 error("unbalanced --push-state/--pop-state"); 1412 break; 1413 } 1414 std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back(); 1415 stack.pop_back(); 1416 break; 1417 } 1418 } 1419 1420 if (files.empty() && errorCount() == 0) 1421 error("no input files"); 1422 } 1423 1424 // If -m <machine_type> was not given, infer it from object files. 1425 void LinkerDriver::inferMachineType() { 1426 if (config->ekind != ELFNoneKind) 1427 return; 1428 1429 for (InputFile *f : files) { 1430 if (f->ekind == ELFNoneKind) 1431 continue; 1432 config->ekind = f->ekind; 1433 config->emachine = f->emachine; 1434 config->osabi = f->osabi; 1435 config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f); 1436 return; 1437 } 1438 error("target emulation unknown: -m or at least one .o file required"); 1439 } 1440 1441 // Parse -z max-page-size=<value>. The default value is defined by 1442 // each target. 1443 static uint64_t getMaxPageSize(opt::InputArgList &args) { 1444 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size", 1445 target->defaultMaxPageSize); 1446 if (!isPowerOf2_64(val)) 1447 error("max-page-size: value isn't a power of 2"); 1448 if (config->nmagic || config->omagic) { 1449 if (val != target->defaultMaxPageSize) 1450 warn("-z max-page-size set, but paging disabled by omagic or nmagic"); 1451 return 1; 1452 } 1453 return val; 1454 } 1455 1456 // Parse -z common-page-size=<value>. The default value is defined by 1457 // each target. 1458 static uint64_t getCommonPageSize(opt::InputArgList &args) { 1459 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size", 1460 target->defaultCommonPageSize); 1461 if (!isPowerOf2_64(val)) 1462 error("common-page-size: value isn't a power of 2"); 1463 if (config->nmagic || config->omagic) { 1464 if (val != target->defaultCommonPageSize) 1465 warn("-z common-page-size set, but paging disabled by omagic or nmagic"); 1466 return 1; 1467 } 1468 // commonPageSize can't be larger than maxPageSize. 1469 if (val > config->maxPageSize) 1470 val = config->maxPageSize; 1471 return val; 1472 } 1473 1474 // Parses -image-base option. 1475 static Optional<uint64_t> getImageBase(opt::InputArgList &args) { 1476 // Because we are using "Config->maxPageSize" here, this function has to be 1477 // called after the variable is initialized. 1478 auto *arg = args.getLastArg(OPT_image_base); 1479 if (!arg) 1480 return None; 1481 1482 StringRef s = arg->getValue(); 1483 uint64_t v; 1484 if (!to_integer(s, v)) { 1485 error("-image-base: number expected, but got " + s); 1486 return 0; 1487 } 1488 if ((v % config->maxPageSize) != 0) 1489 warn("-image-base: address isn't multiple of page size: " + s); 1490 return v; 1491 } 1492 1493 // Parses `--exclude-libs=lib,lib,...`. 1494 // The library names may be delimited by commas or colons. 1495 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) { 1496 DenseSet<StringRef> ret; 1497 for (auto *arg : args.filtered(OPT_exclude_libs)) { 1498 StringRef s = arg->getValue(); 1499 for (;;) { 1500 size_t pos = s.find_first_of(",:"); 1501 if (pos == StringRef::npos) 1502 break; 1503 ret.insert(s.substr(0, pos)); 1504 s = s.substr(pos + 1); 1505 } 1506 ret.insert(s); 1507 } 1508 return ret; 1509 } 1510 1511 // Handles the -exclude-libs option. If a static library file is specified 1512 // by the -exclude-libs option, all public symbols from the archive become 1513 // private unless otherwise specified by version scripts or something. 1514 // A special library name "ALL" means all archive files. 1515 // 1516 // This is not a popular option, but some programs such as bionic libc use it. 1517 static void excludeLibs(opt::InputArgList &args) { 1518 DenseSet<StringRef> libs = getExcludeLibs(args); 1519 bool all = libs.count("ALL"); 1520 1521 auto visit = [&](InputFile *file) { 1522 if (!file->archiveName.empty()) 1523 if (all || libs.count(path::filename(file->archiveName))) 1524 for (Symbol *sym : file->getSymbols()) 1525 if (!sym->isUndefined() && !sym->isLocal() && sym->file == file) 1526 sym->versionId = VER_NDX_LOCAL; 1527 }; 1528 1529 for (InputFile *file : objectFiles) 1530 visit(file); 1531 1532 for (BitcodeFile *file : bitcodeFiles) 1533 visit(file); 1534 } 1535 1536 // Force Sym to be entered in the output. 1537 static void handleUndefined(Symbol *sym) { 1538 // Since a symbol may not be used inside the program, LTO may 1539 // eliminate it. Mark the symbol as "used" to prevent it. 1540 sym->isUsedInRegularObj = true; 1541 1542 if (sym->isLazy()) 1543 sym->fetch(); 1544 } 1545 1546 // As an extension to GNU linkers, lld supports a variant of `-u` 1547 // which accepts wildcard patterns. All symbols that match a given 1548 // pattern are handled as if they were given by `-u`. 1549 static void handleUndefinedGlob(StringRef arg) { 1550 Expected<GlobPattern> pat = GlobPattern::create(arg); 1551 if (!pat) { 1552 error("--undefined-glob: " + toString(pat.takeError())); 1553 return; 1554 } 1555 1556 std::vector<Symbol *> syms; 1557 for (Symbol *sym : symtab->symbols()) { 1558 // Calling Sym->fetch() from here is not safe because it may 1559 // add new symbols to the symbol table, invalidating the 1560 // current iterator. So we just keep a note. 1561 if (pat->match(sym->getName())) 1562 syms.push_back(sym); 1563 } 1564 1565 for (Symbol *sym : syms) 1566 handleUndefined(sym); 1567 } 1568 1569 static void handleLibcall(StringRef name) { 1570 Symbol *sym = symtab->find(name); 1571 if (!sym || !sym->isLazy()) 1572 return; 1573 1574 MemoryBufferRef mb; 1575 if (auto *lo = dyn_cast<LazyObject>(sym)) 1576 mb = lo->file->mb; 1577 else 1578 mb = cast<LazyArchive>(sym)->getMemberBuffer(); 1579 1580 if (isBitcode(mb)) 1581 sym->fetch(); 1582 } 1583 1584 // Handle --dependency-file=<path>. If that option is given, lld creates a 1585 // file at a given path with the following contents: 1586 // 1587 // <output-file>: <input-file> ... 1588 // 1589 // <input-file>: 1590 // 1591 // where <output-file> is a pathname of an output file and <input-file> 1592 // ... is a list of pathnames of all input files. `make` command can read a 1593 // file in the above format and interpret it as a dependency info. We write 1594 // phony targets for every <input-file> to avoid an error when that file is 1595 // removed. 1596 // 1597 // This option is useful if you want to make your final executable to depend 1598 // on all input files including system libraries. Here is why. 1599 // 1600 // When you write a Makefile, you usually write it so that the final 1601 // executable depends on all user-generated object files. Normally, you 1602 // don't make your executable to depend on system libraries (such as libc) 1603 // because you don't know the exact paths of libraries, even though system 1604 // libraries that are linked to your executable statically are technically a 1605 // part of your program. By using --dependency-file option, you can make 1606 // lld to dump dependency info so that you can maintain exact dependencies 1607 // easily. 1608 static void writeDependencyFile() { 1609 std::error_code ec; 1610 raw_fd_ostream os(config->dependencyFile, ec, sys::fs::F_None); 1611 if (ec) { 1612 error("cannot open " + config->dependencyFile + ": " + ec.message()); 1613 return; 1614 } 1615 1616 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja: 1617 // * A space is escaped by a backslash which itself must be escaped. 1618 // * A hash sign is escaped by a single backslash. 1619 // * $ is escapes as $$. 1620 auto printFilename = [](raw_fd_ostream &os, StringRef filename) { 1621 llvm::SmallString<256> nativePath; 1622 llvm::sys::path::native(filename.str(), nativePath); 1623 llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true); 1624 for (unsigned i = 0, e = nativePath.size(); i != e; ++i) { 1625 if (nativePath[i] == '#') { 1626 os << '\\'; 1627 } else if (nativePath[i] == ' ') { 1628 os << '\\'; 1629 unsigned j = i; 1630 while (j > 0 && nativePath[--j] == '\\') 1631 os << '\\'; 1632 } else if (nativePath[i] == '$') { 1633 os << '$'; 1634 } 1635 os << nativePath[i]; 1636 } 1637 }; 1638 1639 os << config->outputFile << ":"; 1640 for (StringRef path : config->dependencyFiles) { 1641 os << " \\\n "; 1642 printFilename(os, path); 1643 } 1644 os << "\n"; 1645 1646 for (StringRef path : config->dependencyFiles) { 1647 os << "\n"; 1648 printFilename(os, path); 1649 os << ":\n"; 1650 } 1651 } 1652 1653 // Replaces common symbols with defined symbols reside in .bss sections. 1654 // This function is called after all symbol names are resolved. As a 1655 // result, the passes after the symbol resolution won't see any 1656 // symbols of type CommonSymbol. 1657 static void replaceCommonSymbols() { 1658 for (Symbol *sym : symtab->symbols()) { 1659 auto *s = dyn_cast<CommonSymbol>(sym); 1660 if (!s) 1661 continue; 1662 1663 auto *bss = make<BssSection>("COMMON", s->size, s->alignment); 1664 bss->file = s->file; 1665 bss->markDead(); 1666 inputSections.push_back(bss); 1667 s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type, 1668 /*value=*/0, s->size, bss}); 1669 } 1670 } 1671 1672 // If all references to a DSO happen to be weak, the DSO is not added 1673 // to DT_NEEDED. If that happens, we need to eliminate shared symbols 1674 // created from the DSO. Otherwise, they become dangling references 1675 // that point to a non-existent DSO. 1676 static void demoteSharedSymbols() { 1677 for (Symbol *sym : symtab->symbols()) { 1678 auto *s = dyn_cast<SharedSymbol>(sym); 1679 if (!s || s->getFile().isNeeded) 1680 continue; 1681 1682 bool used = s->used; 1683 s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type}); 1684 s->used = used; 1685 } 1686 } 1687 1688 // The section referred to by `s` is considered address-significant. Set the 1689 // keepUnique flag on the section if appropriate. 1690 static void markAddrsig(Symbol *s) { 1691 if (auto *d = dyn_cast_or_null<Defined>(s)) 1692 if (d->section) 1693 // We don't need to keep text sections unique under --icf=all even if they 1694 // are address-significant. 1695 if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR)) 1696 d->section->keepUnique = true; 1697 } 1698 1699 // Record sections that define symbols mentioned in --keep-unique <symbol> 1700 // and symbols referred to by address-significance tables. These sections are 1701 // ineligible for ICF. 1702 template <class ELFT> 1703 static void findKeepUniqueSections(opt::InputArgList &args) { 1704 for (auto *arg : args.filtered(OPT_keep_unique)) { 1705 StringRef name = arg->getValue(); 1706 auto *d = dyn_cast_or_null<Defined>(symtab->find(name)); 1707 if (!d || !d->section) { 1708 warn("could not find symbol " + name + " to keep unique"); 1709 continue; 1710 } 1711 d->section->keepUnique = true; 1712 } 1713 1714 // --icf=all --ignore-data-address-equality means that we can ignore 1715 // the dynsym and address-significance tables entirely. 1716 if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality) 1717 return; 1718 1719 // Symbols in the dynsym could be address-significant in other executables 1720 // or DSOs, so we conservatively mark them as address-significant. 1721 for (Symbol *sym : symtab->symbols()) 1722 if (sym->includeInDynsym()) 1723 markAddrsig(sym); 1724 1725 // Visit the address-significance table in each object file and mark each 1726 // referenced symbol as address-significant. 1727 for (InputFile *f : objectFiles) { 1728 auto *obj = cast<ObjFile<ELFT>>(f); 1729 ArrayRef<Symbol *> syms = obj->getSymbols(); 1730 if (obj->addrsigSec) { 1731 ArrayRef<uint8_t> contents = 1732 check(obj->getObj().getSectionContents(*obj->addrsigSec)); 1733 const uint8_t *cur = contents.begin(); 1734 while (cur != contents.end()) { 1735 unsigned size; 1736 const char *err; 1737 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 1738 if (err) 1739 fatal(toString(f) + ": could not decode addrsig section: " + err); 1740 markAddrsig(syms[symIndex]); 1741 cur += size; 1742 } 1743 } else { 1744 // If an object file does not have an address-significance table, 1745 // conservatively mark all of its symbols as address-significant. 1746 for (Symbol *s : syms) 1747 markAddrsig(s); 1748 } 1749 } 1750 } 1751 1752 // This function reads a symbol partition specification section. These sections 1753 // are used to control which partition a symbol is allocated to. See 1754 // https://lld.llvm.org/Partitions.html for more details on partitions. 1755 template <typename ELFT> 1756 static void readSymbolPartitionSection(InputSectionBase *s) { 1757 // Read the relocation that refers to the partition's entry point symbol. 1758 Symbol *sym; 1759 if (s->areRelocsRela) 1760 sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]); 1761 else 1762 sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]); 1763 if (!isa<Defined>(sym) || !sym->includeInDynsym()) 1764 return; 1765 1766 StringRef partName = reinterpret_cast<const char *>(s->data().data()); 1767 for (Partition &part : partitions) { 1768 if (part.name == partName) { 1769 sym->partition = part.getNumber(); 1770 return; 1771 } 1772 } 1773 1774 // Forbid partitions from being used on incompatible targets, and forbid them 1775 // from being used together with various linker features that assume a single 1776 // set of output sections. 1777 if (script->hasSectionsCommand) 1778 error(toString(s->file) + 1779 ": partitions cannot be used with the SECTIONS command"); 1780 if (script->hasPhdrsCommands()) 1781 error(toString(s->file) + 1782 ": partitions cannot be used with the PHDRS command"); 1783 if (!config->sectionStartMap.empty()) 1784 error(toString(s->file) + ": partitions cannot be used with " 1785 "--section-start, -Ttext, -Tdata or -Tbss"); 1786 if (config->emachine == EM_MIPS) 1787 error(toString(s->file) + ": partitions cannot be used on this target"); 1788 1789 // Impose a limit of no more than 254 partitions. This limit comes from the 1790 // sizes of the Partition fields in InputSectionBase and Symbol, as well as 1791 // the amount of space devoted to the partition number in RankFlags. 1792 if (partitions.size() == 254) 1793 fatal("may not have more than 254 partitions"); 1794 1795 partitions.emplace_back(); 1796 Partition &newPart = partitions.back(); 1797 newPart.name = partName; 1798 sym->partition = newPart.getNumber(); 1799 } 1800 1801 static Symbol *addUndefined(StringRef name) { 1802 return symtab->addSymbol( 1803 Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0}); 1804 } 1805 1806 static Symbol *addUnusedUndefined(StringRef name) { 1807 Undefined sym{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0}; 1808 sym.isUsedInRegularObj = false; 1809 return symtab->addSymbol(sym); 1810 } 1811 1812 // This function is where all the optimizations of link-time 1813 // optimization takes place. When LTO is in use, some input files are 1814 // not in native object file format but in the LLVM bitcode format. 1815 // This function compiles bitcode files into a few big native files 1816 // using LLVM functions and replaces bitcode symbols with the results. 1817 // Because all bitcode files that the program consists of are passed to 1818 // the compiler at once, it can do a whole-program optimization. 1819 template <class ELFT> void LinkerDriver::compileBitcodeFiles() { 1820 llvm::TimeTraceScope timeScope("LTO"); 1821 // Compile bitcode files and replace bitcode symbols. 1822 lto.reset(new BitcodeCompiler); 1823 for (BitcodeFile *file : bitcodeFiles) 1824 lto->add(*file); 1825 1826 for (InputFile *file : lto->compile()) { 1827 auto *obj = cast<ObjFile<ELFT>>(file); 1828 obj->parse(/*ignoreComdats=*/true); 1829 1830 // Parse '@' in symbol names for non-relocatable output. 1831 if (!config->relocatable) 1832 for (Symbol *sym : obj->getGlobalSymbols()) 1833 sym->parseSymbolVersion(); 1834 objectFiles.push_back(file); 1835 } 1836 } 1837 1838 // The --wrap option is a feature to rename symbols so that you can write 1839 // wrappers for existing functions. If you pass `-wrap=foo`, all 1840 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are 1841 // expected to write `__wrap_foo` function as a wrapper). The original 1842 // symbol becomes accessible as `__real_foo`, so you can call that from your 1843 // wrapper. 1844 // 1845 // This data structure is instantiated for each -wrap option. 1846 struct WrappedSymbol { 1847 Symbol *sym; 1848 Symbol *real; 1849 Symbol *wrap; 1850 }; 1851 1852 // Handles -wrap option. 1853 // 1854 // This function instantiates wrapper symbols. At this point, they seem 1855 // like they are not being used at all, so we explicitly set some flags so 1856 // that LTO won't eliminate them. 1857 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) { 1858 std::vector<WrappedSymbol> v; 1859 DenseSet<StringRef> seen; 1860 1861 for (auto *arg : args.filtered(OPT_wrap)) { 1862 StringRef name = arg->getValue(); 1863 if (!seen.insert(name).second) 1864 continue; 1865 1866 Symbol *sym = symtab->find(name); 1867 if (!sym) 1868 continue; 1869 1870 Symbol *real = addUnusedUndefined(saver.save("__real_" + name)); 1871 Symbol *wrap = addUnusedUndefined(saver.save("__wrap_" + name)); 1872 v.push_back({sym, real, wrap}); 1873 1874 // We want to tell LTO not to inline symbols to be overwritten 1875 // because LTO doesn't know the final symbol contents after renaming. 1876 real->canInline = false; 1877 sym->canInline = false; 1878 1879 // Tell LTO not to eliminate these symbols. 1880 sym->isUsedInRegularObj = true; 1881 if (!wrap->isUndefined()) 1882 wrap->isUsedInRegularObj = true; 1883 } 1884 return v; 1885 } 1886 1887 // Do renaming for -wrap by updating pointers to symbols. 1888 // 1889 // When this function is executed, only InputFiles and symbol table 1890 // contain pointers to symbol objects. We visit them to replace pointers, 1891 // so that wrapped symbols are swapped as instructed by the command line. 1892 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) { 1893 DenseMap<Symbol *, Symbol *> map; 1894 for (const WrappedSymbol &w : wrapped) { 1895 map[w.sym] = w.wrap; 1896 map[w.real] = w.sym; 1897 } 1898 1899 // Update pointers in input files. 1900 parallelForEach(objectFiles, [&](InputFile *file) { 1901 MutableArrayRef<Symbol *> syms = file->getMutableSymbols(); 1902 for (size_t i = 0, e = syms.size(); i != e; ++i) 1903 if (Symbol *s = map.lookup(syms[i])) 1904 syms[i] = s; 1905 }); 1906 1907 // Update pointers in the symbol table. 1908 for (const WrappedSymbol &w : wrapped) 1909 symtab->wrap(w.sym, w.real, w.wrap); 1910 } 1911 1912 // To enable CET (x86's hardware-assited control flow enforcement), each 1913 // source file must be compiled with -fcf-protection. Object files compiled 1914 // with the flag contain feature flags indicating that they are compatible 1915 // with CET. We enable the feature only when all object files are compatible 1916 // with CET. 1917 // 1918 // This is also the case with AARCH64's BTI and PAC which use the similar 1919 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism. 1920 template <class ELFT> static uint32_t getAndFeatures() { 1921 if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 1922 config->emachine != EM_AARCH64) 1923 return 0; 1924 1925 uint32_t ret = -1; 1926 for (InputFile *f : objectFiles) { 1927 uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures; 1928 if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) { 1929 warn(toString(f) + ": -z force-bti: file does not have " 1930 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 1931 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI; 1932 } else if (config->zForceIbt && 1933 !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) { 1934 warn(toString(f) + ": -z force-ibt: file does not have " 1935 "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 1936 features |= GNU_PROPERTY_X86_FEATURE_1_IBT; 1937 } 1938 if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) { 1939 warn(toString(f) + ": -z pac-plt: file does not have " 1940 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property"); 1941 features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC; 1942 } 1943 ret &= features; 1944 } 1945 1946 // Force enable Shadow Stack. 1947 if (config->zShstk) 1948 ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK; 1949 1950 return ret; 1951 } 1952 1953 // Do actual linking. Note that when this function is called, 1954 // all linker scripts have already been parsed. 1955 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) { 1956 llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link")); 1957 // If a -hash-style option was not given, set to a default value, 1958 // which varies depending on the target. 1959 if (!args.hasArg(OPT_hash_style)) { 1960 if (config->emachine == EM_MIPS) 1961 config->sysvHash = true; 1962 else 1963 config->sysvHash = config->gnuHash = true; 1964 } 1965 1966 // Default output filename is "a.out" by the Unix tradition. 1967 if (config->outputFile.empty()) 1968 config->outputFile = "a.out"; 1969 1970 // Fail early if the output file or map file is not writable. If a user has a 1971 // long link, e.g. due to a large LTO link, they do not wish to run it and 1972 // find that it failed because there was a mistake in their command-line. 1973 if (auto e = tryCreateFile(config->outputFile)) 1974 error("cannot open output file " + config->outputFile + ": " + e.message()); 1975 if (auto e = tryCreateFile(config->mapFile)) 1976 error("cannot open map file " + config->mapFile + ": " + e.message()); 1977 if (errorCount()) 1978 return; 1979 1980 // Use default entry point name if no name was given via the command 1981 // line nor linker scripts. For some reason, MIPS entry point name is 1982 // different from others. 1983 config->warnMissingEntry = 1984 (!config->entry.empty() || (!config->shared && !config->relocatable)); 1985 if (config->entry.empty() && !config->relocatable) 1986 config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start"; 1987 1988 // Handle --trace-symbol. 1989 for (auto *arg : args.filtered(OPT_trace_symbol)) 1990 symtab->insert(arg->getValue())->traced = true; 1991 1992 // Handle -u/--undefined before input files. If both a.a and b.so define foo, 1993 // -u foo a.a b.so will fetch a.a. 1994 for (StringRef name : config->undefined) 1995 addUnusedUndefined(name)->referenced = true; 1996 1997 // Add all files to the symbol table. This will add almost all 1998 // symbols that we need to the symbol table. This process might 1999 // add files to the link, via autolinking, these files are always 2000 // appended to the Files vector. 2001 { 2002 llvm::TimeTraceScope timeScope("Parse input files"); 2003 for (size_t i = 0; i < files.size(); ++i) 2004 parseFile(files[i]); 2005 } 2006 2007 // Now that we have every file, we can decide if we will need a 2008 // dynamic symbol table. 2009 // We need one if we were asked to export dynamic symbols or if we are 2010 // producing a shared library. 2011 // We also need one if any shared libraries are used and for pie executables 2012 // (probably because the dynamic linker needs it). 2013 config->hasDynSymTab = 2014 !sharedFiles.empty() || config->isPic || config->exportDynamic; 2015 2016 // Some symbols (such as __ehdr_start) are defined lazily only when there 2017 // are undefined symbols for them, so we add these to trigger that logic. 2018 for (StringRef name : script->referencedSymbols) 2019 addUndefined(name); 2020 2021 // Prevent LTO from removing any definition referenced by -u. 2022 for (StringRef name : config->undefined) 2023 if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name))) 2024 sym->isUsedInRegularObj = true; 2025 2026 // If an entry symbol is in a static archive, pull out that file now. 2027 if (Symbol *sym = symtab->find(config->entry)) 2028 handleUndefined(sym); 2029 2030 // Handle the `--undefined-glob <pattern>` options. 2031 for (StringRef pat : args::getStrings(args, OPT_undefined_glob)) 2032 handleUndefinedGlob(pat); 2033 2034 // Mark -init and -fini symbols so that the LTO doesn't eliminate them. 2035 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init))) 2036 sym->isUsedInRegularObj = true; 2037 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini))) 2038 sym->isUsedInRegularObj = true; 2039 2040 // If any of our inputs are bitcode files, the LTO code generator may create 2041 // references to certain library functions that might not be explicit in the 2042 // bitcode file's symbol table. If any of those library functions are defined 2043 // in a bitcode file in an archive member, we need to arrange to use LTO to 2044 // compile those archive members by adding them to the link beforehand. 2045 // 2046 // However, adding all libcall symbols to the link can have undesired 2047 // consequences. For example, the libgcc implementation of 2048 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 2049 // that aborts the program if the Linux kernel does not support 64-bit 2050 // atomics, which would prevent the program from running even if it does not 2051 // use 64-bit atomics. 2052 // 2053 // Therefore, we only add libcall symbols to the link before LTO if we have 2054 // to, i.e. if the symbol's definition is in bitcode. Any other required 2055 // libcall symbols will be added to the link after LTO when we add the LTO 2056 // object file to the link. 2057 if (!bitcodeFiles.empty()) 2058 for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2059 handleLibcall(s); 2060 2061 // Return if there were name resolution errors. 2062 if (errorCount()) 2063 return; 2064 2065 // We want to declare linker script's symbols early, 2066 // so that we can version them. 2067 // They also might be exported if referenced by DSOs. 2068 script->declareSymbols(); 2069 2070 // Handle the -exclude-libs option. 2071 if (args.hasArg(OPT_exclude_libs)) 2072 excludeLibs(args); 2073 2074 // Create elfHeader early. We need a dummy section in 2075 // addReservedSymbols to mark the created symbols as not absolute. 2076 Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC); 2077 Out::elfHeader->size = sizeof(typename ELFT::Ehdr); 2078 2079 // Create wrapped symbols for -wrap option. 2080 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 2081 2082 // We need to create some reserved symbols such as _end. Create them. 2083 if (!config->relocatable) 2084 addReservedSymbols(); 2085 2086 // Apply version scripts. 2087 // 2088 // For a relocatable output, version scripts don't make sense, and 2089 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 2090 // name "foo@ver1") rather do harm, so we don't call this if -r is given. 2091 if (!config->relocatable) 2092 symtab->scanVersionScript(); 2093 2094 // Do link-time optimization if given files are LLVM bitcode files. 2095 // This compiles bitcode files into real object files. 2096 // 2097 // With this the symbol table should be complete. After this, no new names 2098 // except a few linker-synthesized ones will be added to the symbol table. 2099 compileBitcodeFiles<ELFT>(); 2100 2101 // Symbol resolution finished. Report backward reference problems. 2102 reportBackrefs(); 2103 if (errorCount()) 2104 return; 2105 2106 // If -thinlto-index-only is given, we should create only "index 2107 // files" and not object files. Index file creation is already done 2108 // in addCombinedLTOObject, so we are done if that's the case. 2109 // Likewise, --plugin-opt=emit-llvm and --plugin-opt=emit-asm are the 2110 // options to create output files in bitcode or assembly code 2111 // repsectively. No object files are generated. 2112 // Also bail out here when only certain thinLTO modules are specified for 2113 // compilation. The intermediate object file are the expected output. 2114 if (config->thinLTOIndexOnly || config->emitLLVM || config->ltoEmitAsm || 2115 !config->thinLTOModulesToCompile.empty()) 2116 return; 2117 2118 // Apply symbol renames for -wrap. 2119 if (!wrapped.empty()) 2120 wrapSymbols(wrapped); 2121 2122 // Now that we have a complete list of input files. 2123 // Beyond this point, no new files are added. 2124 // Aggregate all input sections into one place. 2125 for (InputFile *f : objectFiles) 2126 for (InputSectionBase *s : f->getSections()) 2127 if (s && s != &InputSection::discarded) 2128 inputSections.push_back(s); 2129 for (BinaryFile *f : binaryFiles) 2130 for (InputSectionBase *s : f->getSections()) 2131 inputSections.push_back(cast<InputSection>(s)); 2132 2133 llvm::erase_if(inputSections, [](InputSectionBase *s) { 2134 if (s->type == SHT_LLVM_SYMPART) { 2135 readSymbolPartitionSection<ELFT>(s); 2136 return true; 2137 } 2138 2139 // We do not want to emit debug sections if --strip-all 2140 // or -strip-debug are given. 2141 if (config->strip == StripPolicy::None) 2142 return false; 2143 2144 if (isDebugSection(*s)) 2145 return true; 2146 if (auto *isec = dyn_cast<InputSection>(s)) 2147 if (InputSectionBase *rel = isec->getRelocatedSection()) 2148 if (isDebugSection(*rel)) 2149 return true; 2150 2151 return false; 2152 }); 2153 2154 // Since we now have a complete set of input files, we can create 2155 // a .d file to record build dependencies. 2156 if (!config->dependencyFile.empty()) 2157 writeDependencyFile(); 2158 2159 // Now that the number of partitions is fixed, save a pointer to the main 2160 // partition. 2161 mainPart = &partitions[0]; 2162 2163 // Read .note.gnu.property sections from input object files which 2164 // contain a hint to tweak linker's and loader's behaviors. 2165 config->andFeatures = getAndFeatures<ELFT>(); 2166 2167 // The Target instance handles target-specific stuff, such as applying 2168 // relocations or writing a PLT section. It also contains target-dependent 2169 // values such as a default image base address. 2170 target = getTarget(); 2171 2172 config->eflags = target->calcEFlags(); 2173 // maxPageSize (sometimes called abi page size) is the maximum page size that 2174 // the output can be run on. For example if the OS can use 4k or 64k page 2175 // sizes then maxPageSize must be 64k for the output to be useable on both. 2176 // All important alignment decisions must use this value. 2177 config->maxPageSize = getMaxPageSize(args); 2178 // commonPageSize is the most common page size that the output will be run on. 2179 // For example if an OS can use 4k or 64k page sizes and 4k is more common 2180 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for 2181 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 2182 // is limited to writing trap instructions on the last executable segment. 2183 config->commonPageSize = getCommonPageSize(args); 2184 2185 config->imageBase = getImageBase(args); 2186 2187 if (config->emachine == EM_ARM) { 2188 // FIXME: These warnings can be removed when lld only uses these features 2189 // when the input objects have been compiled with an architecture that 2190 // supports them. 2191 if (config->armHasBlx == false) 2192 warn("lld uses blx instruction, no object with architecture supporting " 2193 "feature detected"); 2194 } 2195 2196 // This adds a .comment section containing a version string. 2197 if (!config->relocatable) 2198 inputSections.push_back(createCommentSection()); 2199 2200 // Replace common symbols with regular symbols. 2201 replaceCommonSymbols(); 2202 2203 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection. 2204 splitSections<ELFT>(); 2205 2206 // Garbage collection and removal of shared symbols from unused shared objects. 2207 markLive<ELFT>(); 2208 demoteSharedSymbols(); 2209 2210 // Make copies of any input sections that need to be copied into each 2211 // partition. 2212 copySectionsIntoPartitions(); 2213 2214 // Create synthesized sections such as .got and .plt. This is called before 2215 // processSectionCommands() so that they can be placed by SECTIONS commands. 2216 createSyntheticSections<ELFT>(); 2217 2218 // Some input sections that are used for exception handling need to be moved 2219 // into synthetic sections. Do that now so that they aren't assigned to 2220 // output sections in the usual way. 2221 if (!config->relocatable) 2222 combineEhSections(); 2223 2224 // Create output sections described by SECTIONS commands. 2225 script->processSectionCommands(); 2226 2227 // Linker scripts control how input sections are assigned to output sections. 2228 // Input sections that were not handled by scripts are called "orphans", and 2229 // they are assigned to output sections by the default rule. Process that. 2230 script->addOrphanSections(); 2231 2232 // Migrate InputSectionDescription::sectionBases to sections. This includes 2233 // merging MergeInputSections into a single MergeSyntheticSection. From this 2234 // point onwards InputSectionDescription::sections should be used instead of 2235 // sectionBases. 2236 for (BaseCommand *base : script->sectionCommands) 2237 if (auto *sec = dyn_cast<OutputSection>(base)) 2238 sec->finalizeInputSections(); 2239 llvm::erase_if(inputSections, 2240 [](InputSectionBase *s) { return isa<MergeInputSection>(s); }); 2241 2242 // Two input sections with different output sections should not be folded. 2243 // ICF runs after processSectionCommands() so that we know the output sections. 2244 if (config->icf != ICFLevel::None) { 2245 findKeepUniqueSections<ELFT>(args); 2246 doIcf<ELFT>(); 2247 } 2248 2249 // Read the callgraph now that we know what was gced or icfed 2250 if (config->callGraphProfileSort) { 2251 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) 2252 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 2253 readCallGraph(*buffer); 2254 readCallGraphsFromObjectFiles<ELFT>(); 2255 } 2256 2257 // Write the result to the file. 2258 writeResult<ELFT>(); 2259 } 2260