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