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