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, ErrorTag::LibNotFound, {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 948 errorHandler().errorHandlingScript = 949 args.getLastArgValue(OPT_error_handling_script); 950 951 config->executeOnly = 952 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 953 config->exportDynamic = 954 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 955 config->filterList = args::getStrings(args, OPT_filter); 956 config->fini = args.getLastArgValue(OPT_fini, "_fini"); 957 config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) && 958 !args.hasArg(OPT_relocatable); 959 config->fixCortexA8 = 960 args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable); 961 config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 962 config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 963 config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 964 config->icf = getICF(args); 965 config->ignoreDataAddressEquality = 966 args.hasArg(OPT_ignore_data_address_equality); 967 config->ignoreFunctionAddressEquality = 968 args.hasArg(OPT_ignore_function_address_equality); 969 config->init = args.getLastArgValue(OPT_init, "_init"); 970 config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline); 971 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 972 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 973 config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager); 974 config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm); 975 config->ltoNewPassManager = args.hasArg(OPT_lto_new_pass_manager); 976 config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes); 977 config->ltoWholeProgramVisibility = 978 args.hasArg(OPT_lto_whole_program_visibility); 979 config->ltoo = args::getInteger(args, OPT_lto_O, 2); 980 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq); 981 config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1); 982 config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile); 983 config->ltoBasicBlockSections = 984 args.getLastArgValue(OPT_lto_basic_block_sections); 985 config->ltoUniqueBasicBlockSectionNames = 986 args.hasFlag(OPT_lto_unique_basic_block_section_names, 987 OPT_no_lto_unique_basic_block_section_names, false); 988 config->mapFile = args.getLastArgValue(OPT_Map); 989 config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0); 990 config->mergeArmExidx = 991 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 992 config->mmapOutputFile = 993 args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true); 994 config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 995 config->noinhibitExec = args.hasArg(OPT_noinhibit_exec); 996 config->nostdlib = args.hasArg(OPT_nostdlib); 997 config->oFormatBinary = isOutputFormatBinary(args); 998 config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false); 999 config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename); 1000 config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes); 1001 config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness); 1002 config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format); 1003 config->optimize = args::getInteger(args, OPT_O, 1); 1004 config->orphanHandling = getOrphanHandling(args); 1005 config->outputFile = args.getLastArgValue(OPT_o); 1006 config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false); 1007 config->printIcfSections = 1008 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 1009 config->printGcSections = 1010 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 1011 config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats); 1012 config->printSymbolOrder = 1013 args.getLastArgValue(OPT_print_symbol_order); 1014 config->rpath = getRpath(args); 1015 config->relocatable = args.hasArg(OPT_relocatable); 1016 config->saveTemps = args.hasArg(OPT_save_temps); 1017 if (args.hasArg(OPT_shuffle_sections)) 1018 config->shuffleSectionSeed = args::getInteger(args, OPT_shuffle_sections, 0); 1019 config->searchPaths = args::getStrings(args, OPT_library_path); 1020 config->sectionStartMap = getSectionStartMap(args); 1021 config->shared = args.hasArg(OPT_shared); 1022 config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true); 1023 config->soName = args.getLastArgValue(OPT_soname); 1024 config->sortSection = getSortSection(args); 1025 config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384); 1026 config->strip = getStrip(args); 1027 config->sysroot = args.getLastArgValue(OPT_sysroot); 1028 config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 1029 config->target2 = getTarget2(args); 1030 config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir); 1031 config->thinLTOCachePolicy = CHECK( 1032 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)), 1033 "--thinlto-cache-policy: invalid cache policy"); 1034 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 1035 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 1036 args.hasArg(OPT_thinlto_index_only_eq); 1037 config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq); 1038 config->thinLTOObjectSuffixReplace = 1039 getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq); 1040 config->thinLTOPrefixReplace = 1041 getOldNewOptions(args, OPT_thinlto_prefix_replace_eq); 1042 config->thinLTOModulesToCompile = 1043 args::getStrings(args, OPT_thinlto_single_module_eq); 1044 config->timeTraceEnabled = args.hasArg(OPT_time_trace); 1045 config->timeTraceGranularity = 1046 args::getInteger(args, OPT_time_trace_granularity, 500); 1047 config->trace = args.hasArg(OPT_trace); 1048 config->undefined = args::getStrings(args, OPT_undefined); 1049 config->undefinedVersion = 1050 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true); 1051 config->unique = args.hasArg(OPT_unique); 1052 config->useAndroidRelrTags = args.hasFlag( 1053 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 1054 config->unresolvedSymbols = getUnresolvedSymbolPolicy(args); 1055 config->warnBackrefs = 1056 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 1057 config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 1058 config->warnIfuncTextrel = 1059 args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false); 1060 config->warnSymbolOrdering = 1061 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 1062 config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true); 1063 config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true); 1064 config->zForceBti = hasZOption(args, "force-bti"); 1065 config->zForceIbt = hasZOption(args, "force-ibt"); 1066 config->zGlobal = hasZOption(args, "global"); 1067 config->zGnustack = getZGnuStack(args); 1068 config->zHazardplt = hasZOption(args, "hazardplt"); 1069 config->zIfuncNoplt = hasZOption(args, "ifunc-noplt"); 1070 config->zInitfirst = hasZOption(args, "initfirst"); 1071 config->zInterpose = hasZOption(args, "interpose"); 1072 config->zKeepTextSectionPrefix = getZFlag( 1073 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 1074 config->zNodefaultlib = hasZOption(args, "nodefaultlib"); 1075 config->zNodelete = hasZOption(args, "nodelete"); 1076 config->zNodlopen = hasZOption(args, "nodlopen"); 1077 config->zNow = getZFlag(args, "now", "lazy", false); 1078 config->zOrigin = hasZOption(args, "origin"); 1079 config->zPacPlt = hasZOption(args, "pac-plt"); 1080 config->zRelro = getZFlag(args, "relro", "norelro", true); 1081 config->zRetpolineplt = hasZOption(args, "retpolineplt"); 1082 config->zRodynamic = hasZOption(args, "rodynamic"); 1083 config->zSeparate = getZSeparate(args); 1084 config->zShstk = hasZOption(args, "shstk"); 1085 config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0); 1086 config->zStartStopVisibility = getZStartStopVisibility(args); 1087 config->zText = getZFlag(args, "text", "notext", true); 1088 config->zWxneeded = hasZOption(args, "wxneeded"); 1089 1090 for (opt::Arg *arg : args.filtered(OPT_z)) { 1091 std::pair<StringRef, StringRef> option = 1092 StringRef(arg->getValue()).split('='); 1093 if (option.first != "dead-reloc-in-nonalloc") 1094 continue; 1095 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: "; 1096 std::pair<StringRef, StringRef> kv = option.second.split('='); 1097 if (kv.first.empty() || kv.second.empty()) { 1098 error(errPrefix + "expected <section_glob>=<value>"); 1099 continue; 1100 } 1101 uint64_t v; 1102 if (!to_integer(kv.second, v)) 1103 error(errPrefix + "expected a non-negative integer, but got '" + 1104 kv.second + "'"); 1105 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first)) 1106 config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v); 1107 else 1108 error(errPrefix + toString(pat.takeError())); 1109 } 1110 1111 cl::ResetAllOptionOccurrences(); 1112 1113 // Parse LTO options. 1114 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq)) 1115 parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())), 1116 arg->getSpelling()); 1117 1118 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus)) 1119 parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling()); 1120 1121 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or 1122 // relative path. Just ignore. If not ended with "lto-wrapper", consider it an 1123 // unsupported LLVMgold.so option and error. 1124 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) 1125 if (!StringRef(arg->getValue()).endswith("lto-wrapper")) 1126 error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() + 1127 "'"); 1128 1129 // Parse -mllvm options. 1130 for (auto *arg : args.filtered(OPT_mllvm)) 1131 parseClangOption(arg->getValue(), arg->getSpelling()); 1132 1133 // --threads= takes a positive integer and provides the default value for 1134 // --thinlto-jobs=. 1135 if (auto *arg = args.getLastArg(OPT_threads)) { 1136 StringRef v(arg->getValue()); 1137 unsigned threads = 0; 1138 if (!llvm::to_integer(v, threads, 0) || threads == 0) 1139 error(arg->getSpelling() + ": expected a positive integer, but got '" + 1140 arg->getValue() + "'"); 1141 parallel::strategy = hardware_concurrency(threads); 1142 config->thinLTOJobs = v; 1143 } 1144 if (auto *arg = args.getLastArg(OPT_thinlto_jobs)) 1145 config->thinLTOJobs = arg->getValue(); 1146 1147 if (config->ltoo > 3) 1148 error("invalid optimization level for LTO: " + Twine(config->ltoo)); 1149 if (config->ltoPartitions == 0) 1150 error("--lto-partitions: number of threads must be > 0"); 1151 if (!get_threadpool_strategy(config->thinLTOJobs)) 1152 error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 1153 1154 if (config->splitStackAdjustSize < 0) 1155 error("--split-stack-adjust-size: size must be >= 0"); 1156 1157 // The text segment is traditionally the first segment, whose address equals 1158 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment 1159 // is an old-fashioned option that does not play well with lld's layout. 1160 // Suggest --image-base as a likely alternative. 1161 if (args.hasArg(OPT_Ttext_segment)) 1162 error("-Ttext-segment is not supported. Use --image-base if you " 1163 "intend to set the base address"); 1164 1165 // Parse ELF{32,64}{LE,BE} and CPU type. 1166 if (auto *arg = args.getLastArg(OPT_m)) { 1167 StringRef s = arg->getValue(); 1168 std::tie(config->ekind, config->emachine, config->osabi) = 1169 parseEmulation(s); 1170 config->mipsN32Abi = 1171 (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32")); 1172 config->emulation = s; 1173 } 1174 1175 // Parse -hash-style={sysv,gnu,both}. 1176 if (auto *arg = args.getLastArg(OPT_hash_style)) { 1177 StringRef s = arg->getValue(); 1178 if (s == "sysv") 1179 config->sysvHash = true; 1180 else if (s == "gnu") 1181 config->gnuHash = true; 1182 else if (s == "both") 1183 config->sysvHash = config->gnuHash = true; 1184 else 1185 error("unknown -hash-style: " + s); 1186 } 1187 1188 if (args.hasArg(OPT_print_map)) 1189 config->mapFile = "-"; 1190 1191 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 1192 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 1193 // it. 1194 if (config->nmagic || config->omagic) 1195 config->zRelro = false; 1196 1197 std::tie(config->buildId, config->buildIdVector) = getBuildId(args); 1198 1199 std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) = 1200 getPackDynRelocs(args); 1201 1202 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){ 1203 if (args.hasArg(OPT_call_graph_ordering_file)) 1204 error("--symbol-ordering-file and --call-graph-order-file " 1205 "may not be used together"); 1206 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){ 1207 config->symbolOrderingFile = getSymbolOrderingFile(*buffer); 1208 // Also need to disable CallGraphProfileSort to prevent 1209 // LLD order symbols with CGProfile 1210 config->callGraphProfileSort = false; 1211 } 1212 } 1213 1214 assert(config->versionDefinitions.empty()); 1215 config->versionDefinitions.push_back({"local", (uint16_t)VER_NDX_LOCAL, {}}); 1216 config->versionDefinitions.push_back( 1217 {"global", (uint16_t)VER_NDX_GLOBAL, {}}); 1218 1219 // If --retain-symbol-file is used, we'll keep only the symbols listed in 1220 // the file and discard all others. 1221 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) { 1222 config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back( 1223 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true}); 1224 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1225 for (StringRef s : args::getLines(*buffer)) 1226 config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back( 1227 {s, /*isExternCpp=*/false, /*hasWildcard=*/false}); 1228 } 1229 1230 for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) { 1231 StringRef pattern(arg->getValue()); 1232 if (Expected<GlobPattern> pat = GlobPattern::create(pattern)) 1233 config->warnBackrefsExclude.push_back(std::move(*pat)); 1234 else 1235 error(arg->getSpelling() + ": " + toString(pat.takeError())); 1236 } 1237 1238 // When producing an executable, --dynamic-list specifies non-local defined 1239 // symbols whith are required to be exported. When producing a shared object, 1240 // symbols not specified by --dynamic-list are non-preemptible. 1241 config->symbolic = 1242 args.hasArg(OPT_Bsymbolic) || args.hasArg(OPT_dynamic_list); 1243 for (auto *arg : args.filtered(OPT_dynamic_list)) 1244 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 1245 readDynamicList(*buffer); 1246 1247 // --export-dynamic-symbol specifies additional --dynamic-list symbols if any 1248 // other option expresses a symbolic intention: -no-pie, -pie, -Bsymbolic, 1249 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list. 1250 for (auto *arg : args.filtered(OPT_export_dynamic_symbol)) 1251 config->dynamicList.push_back( 1252 {arg->getValue(), /*isExternCpp=*/false, 1253 /*hasWildcard=*/hasWildcard(arg->getValue())}); 1254 1255 for (auto *arg : args.filtered(OPT_version_script)) 1256 if (Optional<std::string> path = searchScript(arg->getValue())) { 1257 if (Optional<MemoryBufferRef> buffer = readFile(*path)) 1258 readVersionScript(*buffer); 1259 } else { 1260 error(Twine("cannot find version script ") + arg->getValue()); 1261 } 1262 } 1263 1264 // Some Config members do not directly correspond to any particular 1265 // command line options, but computed based on other Config values. 1266 // This function initialize such members. See Config.h for the details 1267 // of these values. 1268 static void setConfigs(opt::InputArgList &args) { 1269 ELFKind k = config->ekind; 1270 uint16_t m = config->emachine; 1271 1272 config->copyRelocs = (config->relocatable || config->emitRelocs); 1273 config->is64 = (k == ELF64LEKind || k == ELF64BEKind); 1274 config->isLE = (k == ELF32LEKind || k == ELF64LEKind); 1275 config->endianness = config->isLE ? endianness::little : endianness::big; 1276 config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS); 1277 config->isPic = config->pie || config->shared; 1278 config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic); 1279 config->wordsize = config->is64 ? 8 : 4; 1280 1281 // ELF defines two different ways to store relocation addends as shown below: 1282 // 1283 // Rel: Addends are stored to the location where relocations are applied. It 1284 // cannot pack the full range of addend values for all relocation types, but 1285 // this only affects relocation types that we don't support emitting as 1286 // dynamic relocations (see getDynRel). 1287 // Rela: Addends are stored as part of relocation entry. 1288 // 1289 // In other words, Rela makes it easy to read addends at the price of extra 1290 // 4 or 8 byte for each relocation entry. 1291 // 1292 // We pick the format for dynamic relocations according to the psABI for each 1293 // processor, but a contrary choice can be made if the dynamic loader 1294 // supports. 1295 config->isRela = getIsRela(args); 1296 1297 // If the output uses REL relocations we must store the dynamic relocation 1298 // addends to the output sections. We also store addends for RELA relocations 1299 // if --apply-dynamic-relocs is used. 1300 // We default to not writing the addends when using RELA relocations since 1301 // any standard conforming tool can find it in r_addend. 1302 config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs, 1303 OPT_no_apply_dynamic_relocs, false) || 1304 !config->isRela; 1305 1306 config->tocOptimize = 1307 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64); 1308 config->pcRelOptimize = 1309 args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64); 1310 } 1311 1312 // Returns a value of "-format" option. 1313 static bool isFormatBinary(StringRef s) { 1314 if (s == "binary") 1315 return true; 1316 if (s == "elf" || s == "default") 1317 return false; 1318 error("unknown -format value: " + s + 1319 " (supported formats: elf, default, binary)"); 1320 return false; 1321 } 1322 1323 void LinkerDriver::createFiles(opt::InputArgList &args) { 1324 // For --{push,pop}-state. 1325 std::vector<std::tuple<bool, bool, bool>> stack; 1326 1327 // Iterate over argv to process input files and positional arguments. 1328 InputFile::isInGroup = false; 1329 for (auto *arg : args) { 1330 switch (arg->getOption().getID()) { 1331 case OPT_library: 1332 addLibrary(arg->getValue()); 1333 break; 1334 case OPT_INPUT: 1335 addFile(arg->getValue(), /*withLOption=*/false); 1336 break; 1337 case OPT_defsym: { 1338 StringRef from; 1339 StringRef to; 1340 std::tie(from, to) = StringRef(arg->getValue()).split('='); 1341 if (from.empty() || to.empty()) 1342 error("-defsym: syntax error: " + StringRef(arg->getValue())); 1343 else 1344 readDefsym(from, MemoryBufferRef(to, "-defsym")); 1345 break; 1346 } 1347 case OPT_script: 1348 if (Optional<std::string> path = searchScript(arg->getValue())) { 1349 if (Optional<MemoryBufferRef> mb = readFile(*path)) 1350 readLinkerScript(*mb); 1351 break; 1352 } 1353 error(Twine("cannot find linker script ") + arg->getValue()); 1354 break; 1355 case OPT_as_needed: 1356 config->asNeeded = true; 1357 break; 1358 case OPT_format: 1359 config->formatBinary = isFormatBinary(arg->getValue()); 1360 break; 1361 case OPT_no_as_needed: 1362 config->asNeeded = false; 1363 break; 1364 case OPT_Bstatic: 1365 case OPT_omagic: 1366 case OPT_nmagic: 1367 config->isStatic = true; 1368 break; 1369 case OPT_Bdynamic: 1370 config->isStatic = false; 1371 break; 1372 case OPT_whole_archive: 1373 inWholeArchive = true; 1374 break; 1375 case OPT_no_whole_archive: 1376 inWholeArchive = false; 1377 break; 1378 case OPT_just_symbols: 1379 if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) { 1380 files.push_back(createObjectFile(*mb)); 1381 files.back()->justSymbols = true; 1382 } 1383 break; 1384 case OPT_start_group: 1385 if (InputFile::isInGroup) 1386 error("nested --start-group"); 1387 InputFile::isInGroup = true; 1388 break; 1389 case OPT_end_group: 1390 if (!InputFile::isInGroup) 1391 error("stray --end-group"); 1392 InputFile::isInGroup = false; 1393 ++InputFile::nextGroupId; 1394 break; 1395 case OPT_start_lib: 1396 if (inLib) 1397 error("nested --start-lib"); 1398 if (InputFile::isInGroup) 1399 error("may not nest --start-lib in --start-group"); 1400 inLib = true; 1401 InputFile::isInGroup = true; 1402 break; 1403 case OPT_end_lib: 1404 if (!inLib) 1405 error("stray --end-lib"); 1406 inLib = false; 1407 InputFile::isInGroup = false; 1408 ++InputFile::nextGroupId; 1409 break; 1410 case OPT_push_state: 1411 stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive); 1412 break; 1413 case OPT_pop_state: 1414 if (stack.empty()) { 1415 error("unbalanced --push-state/--pop-state"); 1416 break; 1417 } 1418 std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back(); 1419 stack.pop_back(); 1420 break; 1421 } 1422 } 1423 1424 if (files.empty() && errorCount() == 0) 1425 error("no input files"); 1426 } 1427 1428 // If -m <machine_type> was not given, infer it from object files. 1429 void LinkerDriver::inferMachineType() { 1430 if (config->ekind != ELFNoneKind) 1431 return; 1432 1433 for (InputFile *f : files) { 1434 if (f->ekind == ELFNoneKind) 1435 continue; 1436 config->ekind = f->ekind; 1437 config->emachine = f->emachine; 1438 config->osabi = f->osabi; 1439 config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f); 1440 return; 1441 } 1442 error("target emulation unknown: -m or at least one .o file required"); 1443 } 1444 1445 // Parse -z max-page-size=<value>. The default value is defined by 1446 // each target. 1447 static uint64_t getMaxPageSize(opt::InputArgList &args) { 1448 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size", 1449 target->defaultMaxPageSize); 1450 if (!isPowerOf2_64(val)) 1451 error("max-page-size: value isn't a power of 2"); 1452 if (config->nmagic || config->omagic) { 1453 if (val != target->defaultMaxPageSize) 1454 warn("-z max-page-size set, but paging disabled by omagic or nmagic"); 1455 return 1; 1456 } 1457 return val; 1458 } 1459 1460 // Parse -z common-page-size=<value>. The default value is defined by 1461 // each target. 1462 static uint64_t getCommonPageSize(opt::InputArgList &args) { 1463 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size", 1464 target->defaultCommonPageSize); 1465 if (!isPowerOf2_64(val)) 1466 error("common-page-size: value isn't a power of 2"); 1467 if (config->nmagic || config->omagic) { 1468 if (val != target->defaultCommonPageSize) 1469 warn("-z common-page-size set, but paging disabled by omagic or nmagic"); 1470 return 1; 1471 } 1472 // commonPageSize can't be larger than maxPageSize. 1473 if (val > config->maxPageSize) 1474 val = config->maxPageSize; 1475 return val; 1476 } 1477 1478 // Parses -image-base option. 1479 static Optional<uint64_t> getImageBase(opt::InputArgList &args) { 1480 // Because we are using "Config->maxPageSize" here, this function has to be 1481 // called after the variable is initialized. 1482 auto *arg = args.getLastArg(OPT_image_base); 1483 if (!arg) 1484 return None; 1485 1486 StringRef s = arg->getValue(); 1487 uint64_t v; 1488 if (!to_integer(s, v)) { 1489 error("-image-base: number expected, but got " + s); 1490 return 0; 1491 } 1492 if ((v % config->maxPageSize) != 0) 1493 warn("-image-base: address isn't multiple of page size: " + s); 1494 return v; 1495 } 1496 1497 // Parses `--exclude-libs=lib,lib,...`. 1498 // The library names may be delimited by commas or colons. 1499 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) { 1500 DenseSet<StringRef> ret; 1501 for (auto *arg : args.filtered(OPT_exclude_libs)) { 1502 StringRef s = arg->getValue(); 1503 for (;;) { 1504 size_t pos = s.find_first_of(",:"); 1505 if (pos == StringRef::npos) 1506 break; 1507 ret.insert(s.substr(0, pos)); 1508 s = s.substr(pos + 1); 1509 } 1510 ret.insert(s); 1511 } 1512 return ret; 1513 } 1514 1515 // Handles the -exclude-libs option. If a static library file is specified 1516 // by the -exclude-libs option, all public symbols from the archive become 1517 // private unless otherwise specified by version scripts or something. 1518 // A special library name "ALL" means all archive files. 1519 // 1520 // This is not a popular option, but some programs such as bionic libc use it. 1521 static void excludeLibs(opt::InputArgList &args) { 1522 DenseSet<StringRef> libs = getExcludeLibs(args); 1523 bool all = libs.count("ALL"); 1524 1525 auto visit = [&](InputFile *file) { 1526 if (!file->archiveName.empty()) 1527 if (all || libs.count(path::filename(file->archiveName))) 1528 for (Symbol *sym : file->getSymbols()) 1529 if (!sym->isUndefined() && !sym->isLocal() && sym->file == file) 1530 sym->versionId = VER_NDX_LOCAL; 1531 }; 1532 1533 for (InputFile *file : objectFiles) 1534 visit(file); 1535 1536 for (BitcodeFile *file : bitcodeFiles) 1537 visit(file); 1538 } 1539 1540 // Force Sym to be entered in the output. 1541 static void handleUndefined(Symbol *sym) { 1542 // Since a symbol may not be used inside the program, LTO may 1543 // eliminate it. Mark the symbol as "used" to prevent it. 1544 sym->isUsedInRegularObj = true; 1545 1546 if (sym->isLazy()) 1547 sym->fetch(); 1548 } 1549 1550 // As an extension to GNU linkers, lld supports a variant of `-u` 1551 // which accepts wildcard patterns. All symbols that match a given 1552 // pattern are handled as if they were given by `-u`. 1553 static void handleUndefinedGlob(StringRef arg) { 1554 Expected<GlobPattern> pat = GlobPattern::create(arg); 1555 if (!pat) { 1556 error("--undefined-glob: " + toString(pat.takeError())); 1557 return; 1558 } 1559 1560 std::vector<Symbol *> syms; 1561 for (Symbol *sym : symtab->symbols()) { 1562 // Calling Sym->fetch() from here is not safe because it may 1563 // add new symbols to the symbol table, invalidating the 1564 // current iterator. So we just keep a note. 1565 if (pat->match(sym->getName())) 1566 syms.push_back(sym); 1567 } 1568 1569 for (Symbol *sym : syms) 1570 handleUndefined(sym); 1571 } 1572 1573 static void handleLibcall(StringRef name) { 1574 Symbol *sym = symtab->find(name); 1575 if (!sym || !sym->isLazy()) 1576 return; 1577 1578 MemoryBufferRef mb; 1579 if (auto *lo = dyn_cast<LazyObject>(sym)) 1580 mb = lo->file->mb; 1581 else 1582 mb = cast<LazyArchive>(sym)->getMemberBuffer(); 1583 1584 if (isBitcode(mb)) 1585 sym->fetch(); 1586 } 1587 1588 // Handle --dependency-file=<path>. If that option is given, lld creates a 1589 // file at a given path with the following contents: 1590 // 1591 // <output-file>: <input-file> ... 1592 // 1593 // <input-file>: 1594 // 1595 // where <output-file> is a pathname of an output file and <input-file> 1596 // ... is a list of pathnames of all input files. `make` command can read a 1597 // file in the above format and interpret it as a dependency info. We write 1598 // phony targets for every <input-file> to avoid an error when that file is 1599 // removed. 1600 // 1601 // This option is useful if you want to make your final executable to depend 1602 // on all input files including system libraries. Here is why. 1603 // 1604 // When you write a Makefile, you usually write it so that the final 1605 // executable depends on all user-generated object files. Normally, you 1606 // don't make your executable to depend on system libraries (such as libc) 1607 // because you don't know the exact paths of libraries, even though system 1608 // libraries that are linked to your executable statically are technically a 1609 // part of your program. By using --dependency-file option, you can make 1610 // lld to dump dependency info so that you can maintain exact dependencies 1611 // easily. 1612 static void writeDependencyFile() { 1613 std::error_code ec; 1614 raw_fd_ostream os(config->dependencyFile, ec, sys::fs::F_None); 1615 if (ec) { 1616 error("cannot open " + config->dependencyFile + ": " + ec.message()); 1617 return; 1618 } 1619 1620 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja: 1621 // * A space is escaped by a backslash which itself must be escaped. 1622 // * A hash sign is escaped by a single backslash. 1623 // * $ is escapes as $$. 1624 auto printFilename = [](raw_fd_ostream &os, StringRef filename) { 1625 llvm::SmallString<256> nativePath; 1626 llvm::sys::path::native(filename.str(), nativePath); 1627 llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true); 1628 for (unsigned i = 0, e = nativePath.size(); i != e; ++i) { 1629 if (nativePath[i] == '#') { 1630 os << '\\'; 1631 } else if (nativePath[i] == ' ') { 1632 os << '\\'; 1633 unsigned j = i; 1634 while (j > 0 && nativePath[--j] == '\\') 1635 os << '\\'; 1636 } else if (nativePath[i] == '$') { 1637 os << '$'; 1638 } 1639 os << nativePath[i]; 1640 } 1641 }; 1642 1643 os << config->outputFile << ":"; 1644 for (StringRef path : config->dependencyFiles) { 1645 os << " \\\n "; 1646 printFilename(os, path); 1647 } 1648 os << "\n"; 1649 1650 for (StringRef path : config->dependencyFiles) { 1651 os << "\n"; 1652 printFilename(os, path); 1653 os << ":\n"; 1654 } 1655 } 1656 1657 // Replaces common symbols with defined symbols reside in .bss sections. 1658 // This function is called after all symbol names are resolved. As a 1659 // result, the passes after the symbol resolution won't see any 1660 // symbols of type CommonSymbol. 1661 static void replaceCommonSymbols() { 1662 for (Symbol *sym : symtab->symbols()) { 1663 auto *s = dyn_cast<CommonSymbol>(sym); 1664 if (!s) 1665 continue; 1666 1667 auto *bss = make<BssSection>("COMMON", s->size, s->alignment); 1668 bss->file = s->file; 1669 bss->markDead(); 1670 inputSections.push_back(bss); 1671 s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type, 1672 /*value=*/0, s->size, bss}); 1673 } 1674 } 1675 1676 // If all references to a DSO happen to be weak, the DSO is not added 1677 // to DT_NEEDED. If that happens, we need to eliminate shared symbols 1678 // created from the DSO. Otherwise, they become dangling references 1679 // that point to a non-existent DSO. 1680 static void demoteSharedSymbols() { 1681 for (Symbol *sym : symtab->symbols()) { 1682 auto *s = dyn_cast<SharedSymbol>(sym); 1683 if (!s || s->getFile().isNeeded) 1684 continue; 1685 1686 bool used = s->used; 1687 s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type}); 1688 s->used = used; 1689 } 1690 } 1691 1692 // The section referred to by `s` is considered address-significant. Set the 1693 // keepUnique flag on the section if appropriate. 1694 static void markAddrsig(Symbol *s) { 1695 if (auto *d = dyn_cast_or_null<Defined>(s)) 1696 if (d->section) 1697 // We don't need to keep text sections unique under --icf=all even if they 1698 // are address-significant. 1699 if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR)) 1700 d->section->keepUnique = true; 1701 } 1702 1703 // Record sections that define symbols mentioned in --keep-unique <symbol> 1704 // and symbols referred to by address-significance tables. These sections are 1705 // ineligible for ICF. 1706 template <class ELFT> 1707 static void findKeepUniqueSections(opt::InputArgList &args) { 1708 for (auto *arg : args.filtered(OPT_keep_unique)) { 1709 StringRef name = arg->getValue(); 1710 auto *d = dyn_cast_or_null<Defined>(symtab->find(name)); 1711 if (!d || !d->section) { 1712 warn("could not find symbol " + name + " to keep unique"); 1713 continue; 1714 } 1715 d->section->keepUnique = true; 1716 } 1717 1718 // --icf=all --ignore-data-address-equality means that we can ignore 1719 // the dynsym and address-significance tables entirely. 1720 if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality) 1721 return; 1722 1723 // Symbols in the dynsym could be address-significant in other executables 1724 // or DSOs, so we conservatively mark them as address-significant. 1725 for (Symbol *sym : symtab->symbols()) 1726 if (sym->includeInDynsym()) 1727 markAddrsig(sym); 1728 1729 // Visit the address-significance table in each object file and mark each 1730 // referenced symbol as address-significant. 1731 for (InputFile *f : objectFiles) { 1732 auto *obj = cast<ObjFile<ELFT>>(f); 1733 ArrayRef<Symbol *> syms = obj->getSymbols(); 1734 if (obj->addrsigSec) { 1735 ArrayRef<uint8_t> contents = 1736 check(obj->getObj().getSectionContents(*obj->addrsigSec)); 1737 const uint8_t *cur = contents.begin(); 1738 while (cur != contents.end()) { 1739 unsigned size; 1740 const char *err; 1741 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 1742 if (err) 1743 fatal(toString(f) + ": could not decode addrsig section: " + err); 1744 markAddrsig(syms[symIndex]); 1745 cur += size; 1746 } 1747 } else { 1748 // If an object file does not have an address-significance table, 1749 // conservatively mark all of its symbols as address-significant. 1750 for (Symbol *s : syms) 1751 markAddrsig(s); 1752 } 1753 } 1754 } 1755 1756 // This function reads a symbol partition specification section. These sections 1757 // are used to control which partition a symbol is allocated to. See 1758 // https://lld.llvm.org/Partitions.html for more details on partitions. 1759 template <typename ELFT> 1760 static void readSymbolPartitionSection(InputSectionBase *s) { 1761 // Read the relocation that refers to the partition's entry point symbol. 1762 Symbol *sym; 1763 if (s->areRelocsRela) 1764 sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]); 1765 else 1766 sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]); 1767 if (!isa<Defined>(sym) || !sym->includeInDynsym()) 1768 return; 1769 1770 StringRef partName = reinterpret_cast<const char *>(s->data().data()); 1771 for (Partition &part : partitions) { 1772 if (part.name == partName) { 1773 sym->partition = part.getNumber(); 1774 return; 1775 } 1776 } 1777 1778 // Forbid partitions from being used on incompatible targets, and forbid them 1779 // from being used together with various linker features that assume a single 1780 // set of output sections. 1781 if (script->hasSectionsCommand) 1782 error(toString(s->file) + 1783 ": partitions cannot be used with the SECTIONS command"); 1784 if (script->hasPhdrsCommands()) 1785 error(toString(s->file) + 1786 ": partitions cannot be used with the PHDRS command"); 1787 if (!config->sectionStartMap.empty()) 1788 error(toString(s->file) + ": partitions cannot be used with " 1789 "--section-start, -Ttext, -Tdata or -Tbss"); 1790 if (config->emachine == EM_MIPS) 1791 error(toString(s->file) + ": partitions cannot be used on this target"); 1792 1793 // Impose a limit of no more than 254 partitions. This limit comes from the 1794 // sizes of the Partition fields in InputSectionBase and Symbol, as well as 1795 // the amount of space devoted to the partition number in RankFlags. 1796 if (partitions.size() == 254) 1797 fatal("may not have more than 254 partitions"); 1798 1799 partitions.emplace_back(); 1800 Partition &newPart = partitions.back(); 1801 newPart.name = partName; 1802 sym->partition = newPart.getNumber(); 1803 } 1804 1805 static Symbol *addUndefined(StringRef name) { 1806 return symtab->addSymbol( 1807 Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0}); 1808 } 1809 1810 static Symbol *addUnusedUndefined(StringRef name) { 1811 Undefined sym{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0}; 1812 sym.isUsedInRegularObj = false; 1813 return symtab->addSymbol(sym); 1814 } 1815 1816 // This function is where all the optimizations of link-time 1817 // optimization takes place. When LTO is in use, some input files are 1818 // not in native object file format but in the LLVM bitcode format. 1819 // This function compiles bitcode files into a few big native files 1820 // using LLVM functions and replaces bitcode symbols with the results. 1821 // Because all bitcode files that the program consists of are passed to 1822 // the compiler at once, it can do a whole-program optimization. 1823 template <class ELFT> void LinkerDriver::compileBitcodeFiles() { 1824 llvm::TimeTraceScope timeScope("LTO"); 1825 // Compile bitcode files and replace bitcode symbols. 1826 lto.reset(new BitcodeCompiler); 1827 for (BitcodeFile *file : bitcodeFiles) 1828 lto->add(*file); 1829 1830 for (InputFile *file : lto->compile()) { 1831 auto *obj = cast<ObjFile<ELFT>>(file); 1832 obj->parse(/*ignoreComdats=*/true); 1833 1834 // Parse '@' in symbol names for non-relocatable output. 1835 if (!config->relocatable) 1836 for (Symbol *sym : obj->getGlobalSymbols()) 1837 sym->parseSymbolVersion(); 1838 objectFiles.push_back(file); 1839 } 1840 } 1841 1842 // The --wrap option is a feature to rename symbols so that you can write 1843 // wrappers for existing functions. If you pass `-wrap=foo`, all 1844 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are 1845 // expected to write `__wrap_foo` function as a wrapper). The original 1846 // symbol becomes accessible as `__real_foo`, so you can call that from your 1847 // wrapper. 1848 // 1849 // This data structure is instantiated for each -wrap option. 1850 struct WrappedSymbol { 1851 Symbol *sym; 1852 Symbol *real; 1853 Symbol *wrap; 1854 }; 1855 1856 // Handles -wrap option. 1857 // 1858 // This function instantiates wrapper symbols. At this point, they seem 1859 // like they are not being used at all, so we explicitly set some flags so 1860 // that LTO won't eliminate them. 1861 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) { 1862 std::vector<WrappedSymbol> v; 1863 DenseSet<StringRef> seen; 1864 1865 for (auto *arg : args.filtered(OPT_wrap)) { 1866 StringRef name = arg->getValue(); 1867 if (!seen.insert(name).second) 1868 continue; 1869 1870 Symbol *sym = symtab->find(name); 1871 if (!sym) 1872 continue; 1873 1874 Symbol *real = addUnusedUndefined(saver.save("__real_" + name)); 1875 Symbol *wrap = addUnusedUndefined(saver.save("__wrap_" + name)); 1876 v.push_back({sym, real, wrap}); 1877 1878 // We want to tell LTO not to inline symbols to be overwritten 1879 // because LTO doesn't know the final symbol contents after renaming. 1880 real->canInline = false; 1881 sym->canInline = false; 1882 1883 // Tell LTO not to eliminate these symbols. 1884 sym->isUsedInRegularObj = true; 1885 if (!wrap->isUndefined()) 1886 wrap->isUsedInRegularObj = true; 1887 } 1888 return v; 1889 } 1890 1891 // Do renaming for -wrap by updating pointers to symbols. 1892 // 1893 // When this function is executed, only InputFiles and symbol table 1894 // contain pointers to symbol objects. We visit them to replace pointers, 1895 // so that wrapped symbols are swapped as instructed by the command line. 1896 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) { 1897 DenseMap<Symbol *, Symbol *> map; 1898 for (const WrappedSymbol &w : wrapped) { 1899 map[w.sym] = w.wrap; 1900 map[w.real] = w.sym; 1901 } 1902 1903 // Update pointers in input files. 1904 parallelForEach(objectFiles, [&](InputFile *file) { 1905 MutableArrayRef<Symbol *> syms = file->getMutableSymbols(); 1906 for (size_t i = 0, e = syms.size(); i != e; ++i) 1907 if (Symbol *s = map.lookup(syms[i])) 1908 syms[i] = s; 1909 }); 1910 1911 // Update pointers in the symbol table. 1912 for (const WrappedSymbol &w : wrapped) 1913 symtab->wrap(w.sym, w.real, w.wrap); 1914 } 1915 1916 // To enable CET (x86's hardware-assited control flow enforcement), each 1917 // source file must be compiled with -fcf-protection. Object files compiled 1918 // with the flag contain feature flags indicating that they are compatible 1919 // with CET. We enable the feature only when all object files are compatible 1920 // with CET. 1921 // 1922 // This is also the case with AARCH64's BTI and PAC which use the similar 1923 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism. 1924 template <class ELFT> static uint32_t getAndFeatures() { 1925 if (config->emachine != EM_386 && config->emachine != EM_X86_64 && 1926 config->emachine != EM_AARCH64) 1927 return 0; 1928 1929 uint32_t ret = -1; 1930 for (InputFile *f : objectFiles) { 1931 uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures; 1932 if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) { 1933 warn(toString(f) + ": -z force-bti: file does not have " 1934 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property"); 1935 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI; 1936 } else if (config->zForceIbt && 1937 !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) { 1938 warn(toString(f) + ": -z force-ibt: file does not have " 1939 "GNU_PROPERTY_X86_FEATURE_1_IBT property"); 1940 features |= GNU_PROPERTY_X86_FEATURE_1_IBT; 1941 } 1942 if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) { 1943 warn(toString(f) + ": -z pac-plt: file does not have " 1944 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property"); 1945 features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC; 1946 } 1947 ret &= features; 1948 } 1949 1950 // Force enable Shadow Stack. 1951 if (config->zShstk) 1952 ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK; 1953 1954 return ret; 1955 } 1956 1957 // Do actual linking. Note that when this function is called, 1958 // all linker scripts have already been parsed. 1959 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) { 1960 llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link")); 1961 // If a -hash-style option was not given, set to a default value, 1962 // which varies depending on the target. 1963 if (!args.hasArg(OPT_hash_style)) { 1964 if (config->emachine == EM_MIPS) 1965 config->sysvHash = true; 1966 else 1967 config->sysvHash = config->gnuHash = true; 1968 } 1969 1970 // Default output filename is "a.out" by the Unix tradition. 1971 if (config->outputFile.empty()) 1972 config->outputFile = "a.out"; 1973 1974 // Fail early if the output file or map file is not writable. If a user has a 1975 // long link, e.g. due to a large LTO link, they do not wish to run it and 1976 // find that it failed because there was a mistake in their command-line. 1977 if (auto e = tryCreateFile(config->outputFile)) 1978 error("cannot open output file " + config->outputFile + ": " + e.message()); 1979 if (auto e = tryCreateFile(config->mapFile)) 1980 error("cannot open map file " + config->mapFile + ": " + e.message()); 1981 if (errorCount()) 1982 return; 1983 1984 // Use default entry point name if no name was given via the command 1985 // line nor linker scripts. For some reason, MIPS entry point name is 1986 // different from others. 1987 config->warnMissingEntry = 1988 (!config->entry.empty() || (!config->shared && !config->relocatable)); 1989 if (config->entry.empty() && !config->relocatable) 1990 config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start"; 1991 1992 // Handle --trace-symbol. 1993 for (auto *arg : args.filtered(OPT_trace_symbol)) 1994 symtab->insert(arg->getValue())->traced = true; 1995 1996 // Handle -u/--undefined before input files. If both a.a and b.so define foo, 1997 // -u foo a.a b.so will fetch a.a. 1998 for (StringRef name : config->undefined) 1999 addUnusedUndefined(name)->referenced = true; 2000 2001 // Add all files to the symbol table. This will add almost all 2002 // symbols that we need to the symbol table. This process might 2003 // add files to the link, via autolinking, these files are always 2004 // appended to the Files vector. 2005 { 2006 llvm::TimeTraceScope timeScope("Parse input files"); 2007 for (size_t i = 0; i < files.size(); ++i) 2008 parseFile(files[i]); 2009 } 2010 2011 // Now that we have every file, we can decide if we will need a 2012 // dynamic symbol table. 2013 // We need one if we were asked to export dynamic symbols or if we are 2014 // producing a shared library. 2015 // We also need one if any shared libraries are used and for pie executables 2016 // (probably because the dynamic linker needs it). 2017 config->hasDynSymTab = 2018 !sharedFiles.empty() || config->isPic || config->exportDynamic; 2019 2020 // Some symbols (such as __ehdr_start) are defined lazily only when there 2021 // are undefined symbols for them, so we add these to trigger that logic. 2022 for (StringRef name : script->referencedSymbols) 2023 addUndefined(name); 2024 2025 // Prevent LTO from removing any definition referenced by -u. 2026 for (StringRef name : config->undefined) 2027 if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name))) 2028 sym->isUsedInRegularObj = true; 2029 2030 // If an entry symbol is in a static archive, pull out that file now. 2031 if (Symbol *sym = symtab->find(config->entry)) 2032 handleUndefined(sym); 2033 2034 // Handle the `--undefined-glob <pattern>` options. 2035 for (StringRef pat : args::getStrings(args, OPT_undefined_glob)) 2036 handleUndefinedGlob(pat); 2037 2038 // Mark -init and -fini symbols so that the LTO doesn't eliminate them. 2039 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init))) 2040 sym->isUsedInRegularObj = true; 2041 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini))) 2042 sym->isUsedInRegularObj = true; 2043 2044 // If any of our inputs are bitcode files, the LTO code generator may create 2045 // references to certain library functions that might not be explicit in the 2046 // bitcode file's symbol table. If any of those library functions are defined 2047 // in a bitcode file in an archive member, we need to arrange to use LTO to 2048 // compile those archive members by adding them to the link beforehand. 2049 // 2050 // However, adding all libcall symbols to the link can have undesired 2051 // consequences. For example, the libgcc implementation of 2052 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 2053 // that aborts the program if the Linux kernel does not support 64-bit 2054 // atomics, which would prevent the program from running even if it does not 2055 // use 64-bit atomics. 2056 // 2057 // Therefore, we only add libcall symbols to the link before LTO if we have 2058 // to, i.e. if the symbol's definition is in bitcode. Any other required 2059 // libcall symbols will be added to the link after LTO when we add the LTO 2060 // object file to the link. 2061 if (!bitcodeFiles.empty()) 2062 for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2063 handleLibcall(s); 2064 2065 // Return if there were name resolution errors. 2066 if (errorCount()) 2067 return; 2068 2069 // We want to declare linker script's symbols early, 2070 // so that we can version them. 2071 // They also might be exported if referenced by DSOs. 2072 script->declareSymbols(); 2073 2074 // Handle the -exclude-libs option. 2075 if (args.hasArg(OPT_exclude_libs)) 2076 excludeLibs(args); 2077 2078 // Create elfHeader early. We need a dummy section in 2079 // addReservedSymbols to mark the created symbols as not absolute. 2080 Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC); 2081 Out::elfHeader->size = sizeof(typename ELFT::Ehdr); 2082 2083 // Create wrapped symbols for -wrap option. 2084 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 2085 2086 // We need to create some reserved symbols such as _end. Create them. 2087 if (!config->relocatable) 2088 addReservedSymbols(); 2089 2090 // Apply version scripts. 2091 // 2092 // For a relocatable output, version scripts don't make sense, and 2093 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 2094 // name "foo@ver1") rather do harm, so we don't call this if -r is given. 2095 if (!config->relocatable) 2096 symtab->scanVersionScript(); 2097 2098 // Do link-time optimization if given files are LLVM bitcode files. 2099 // This compiles bitcode files into real object files. 2100 // 2101 // With this the symbol table should be complete. After this, no new names 2102 // except a few linker-synthesized ones will be added to the symbol table. 2103 compileBitcodeFiles<ELFT>(); 2104 2105 // Symbol resolution finished. Report backward reference problems. 2106 reportBackrefs(); 2107 if (errorCount()) 2108 return; 2109 2110 // If -thinlto-index-only is given, we should create only "index 2111 // files" and not object files. Index file creation is already done 2112 // in addCombinedLTOObject, so we are done if that's the case. 2113 // Likewise, --plugin-opt=emit-llvm and --plugin-opt=emit-asm are the 2114 // options to create output files in bitcode or assembly code 2115 // repsectively. No object files are generated. 2116 // Also bail out here when only certain thinLTO modules are specified for 2117 // compilation. The intermediate object file are the expected output. 2118 if (config->thinLTOIndexOnly || config->emitLLVM || config->ltoEmitAsm || 2119 !config->thinLTOModulesToCompile.empty()) 2120 return; 2121 2122 // Apply symbol renames for -wrap. 2123 if (!wrapped.empty()) 2124 wrapSymbols(wrapped); 2125 2126 // Now that we have a complete list of input files. 2127 // Beyond this point, no new files are added. 2128 // Aggregate all input sections into one place. 2129 for (InputFile *f : objectFiles) 2130 for (InputSectionBase *s : f->getSections()) 2131 if (s && s != &InputSection::discarded) 2132 inputSections.push_back(s); 2133 for (BinaryFile *f : binaryFiles) 2134 for (InputSectionBase *s : f->getSections()) 2135 inputSections.push_back(cast<InputSection>(s)); 2136 2137 llvm::erase_if(inputSections, [](InputSectionBase *s) { 2138 if (s->type == SHT_LLVM_SYMPART) { 2139 readSymbolPartitionSection<ELFT>(s); 2140 return true; 2141 } 2142 2143 // We do not want to emit debug sections if --strip-all 2144 // or -strip-debug are given. 2145 if (config->strip == StripPolicy::None) 2146 return false; 2147 2148 if (isDebugSection(*s)) 2149 return true; 2150 if (auto *isec = dyn_cast<InputSection>(s)) 2151 if (InputSectionBase *rel = isec->getRelocatedSection()) 2152 if (isDebugSection(*rel)) 2153 return true; 2154 2155 return false; 2156 }); 2157 2158 // Since we now have a complete set of input files, we can create 2159 // a .d file to record build dependencies. 2160 if (!config->dependencyFile.empty()) 2161 writeDependencyFile(); 2162 2163 // Now that the number of partitions is fixed, save a pointer to the main 2164 // partition. 2165 mainPart = &partitions[0]; 2166 2167 // Read .note.gnu.property sections from input object files which 2168 // contain a hint to tweak linker's and loader's behaviors. 2169 config->andFeatures = getAndFeatures<ELFT>(); 2170 2171 // The Target instance handles target-specific stuff, such as applying 2172 // relocations or writing a PLT section. It also contains target-dependent 2173 // values such as a default image base address. 2174 target = getTarget(); 2175 2176 config->eflags = target->calcEFlags(); 2177 // maxPageSize (sometimes called abi page size) is the maximum page size that 2178 // the output can be run on. For example if the OS can use 4k or 64k page 2179 // sizes then maxPageSize must be 64k for the output to be useable on both. 2180 // All important alignment decisions must use this value. 2181 config->maxPageSize = getMaxPageSize(args); 2182 // commonPageSize is the most common page size that the output will be run on. 2183 // For example if an OS can use 4k or 64k page sizes and 4k is more common 2184 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for 2185 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 2186 // is limited to writing trap instructions on the last executable segment. 2187 config->commonPageSize = getCommonPageSize(args); 2188 2189 config->imageBase = getImageBase(args); 2190 2191 if (config->emachine == EM_ARM) { 2192 // FIXME: These warnings can be removed when lld only uses these features 2193 // when the input objects have been compiled with an architecture that 2194 // supports them. 2195 if (config->armHasBlx == false) 2196 warn("lld uses blx instruction, no object with architecture supporting " 2197 "feature detected"); 2198 } 2199 2200 // This adds a .comment section containing a version string. 2201 if (!config->relocatable) 2202 inputSections.push_back(createCommentSection()); 2203 2204 // Replace common symbols with regular symbols. 2205 replaceCommonSymbols(); 2206 2207 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection. 2208 splitSections<ELFT>(); 2209 2210 // Garbage collection and removal of shared symbols from unused shared objects. 2211 markLive<ELFT>(); 2212 demoteSharedSymbols(); 2213 2214 // Make copies of any input sections that need to be copied into each 2215 // partition. 2216 copySectionsIntoPartitions(); 2217 2218 // Create synthesized sections such as .got and .plt. This is called before 2219 // processSectionCommands() so that they can be placed by SECTIONS commands. 2220 createSyntheticSections<ELFT>(); 2221 2222 // Some input sections that are used for exception handling need to be moved 2223 // into synthetic sections. Do that now so that they aren't assigned to 2224 // output sections in the usual way. 2225 if (!config->relocatable) 2226 combineEhSections(); 2227 2228 // Create output sections described by SECTIONS commands. 2229 script->processSectionCommands(); 2230 2231 // Linker scripts control how input sections are assigned to output sections. 2232 // Input sections that were not handled by scripts are called "orphans", and 2233 // they are assigned to output sections by the default rule. Process that. 2234 script->addOrphanSections(); 2235 2236 // Migrate InputSectionDescription::sectionBases to sections. This includes 2237 // merging MergeInputSections into a single MergeSyntheticSection. From this 2238 // point onwards InputSectionDescription::sections should be used instead of 2239 // sectionBases. 2240 for (BaseCommand *base : script->sectionCommands) 2241 if (auto *sec = dyn_cast<OutputSection>(base)) 2242 sec->finalizeInputSections(); 2243 llvm::erase_if(inputSections, 2244 [](InputSectionBase *s) { return isa<MergeInputSection>(s); }); 2245 2246 // Two input sections with different output sections should not be folded. 2247 // ICF runs after processSectionCommands() so that we know the output sections. 2248 if (config->icf != ICFLevel::None) { 2249 findKeepUniqueSections<ELFT>(args); 2250 doIcf<ELFT>(); 2251 } 2252 2253 // Read the callgraph now that we know what was gced or icfed 2254 if (config->callGraphProfileSort) { 2255 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) 2256 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())) 2257 readCallGraph(*buffer); 2258 readCallGraphsFromObjectFiles<ELFT>(); 2259 } 2260 2261 // Write the result to the file. 2262 writeResult<ELFT>(); 2263 } 2264