1 //===- Driver.cpp ---------------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // The driver drives the entire linking process. It is responsible for 11 // parsing command line options and doing whatever it is instructed to do. 12 // 13 // One notable thing in the LLD's driver when compared to other linkers is 14 // that the LLD's driver is agnostic on the host operating system. 15 // Other linkers usually have implicit default values (such as a dynamic 16 // linker path or library paths) for each host OS. 17 // 18 // I don't think implicit default values are useful because they are 19 // usually explicitly specified by the compiler driver. They can even 20 // be harmful when you are doing cross-linking. Therefore, in LLD, we 21 // simply trust the compiler driver to pass all required options and 22 // don't try to make effort on our side. 23 // 24 //===----------------------------------------------------------------------===// 25 26 #include "Driver.h" 27 #include "Config.h" 28 #include "Filesystem.h" 29 #include "ICF.h" 30 #include "InputFiles.h" 31 #include "InputSection.h" 32 #include "LinkerScript.h" 33 #include "MarkLive.h" 34 #include "OutputSections.h" 35 #include "ScriptParser.h" 36 #include "SymbolTable.h" 37 #include "Symbols.h" 38 #include "SyntheticSections.h" 39 #include "Target.h" 40 #include "Writer.h" 41 #include "lld/Common/Args.h" 42 #include "lld/Common/Driver.h" 43 #include "lld/Common/ErrorHandler.h" 44 #include "lld/Common/Memory.h" 45 #include "lld/Common/Strings.h" 46 #include "lld/Common/TargetOptionsCommandFlags.h" 47 #include "lld/Common/Threads.h" 48 #include "lld/Common/Version.h" 49 #include "llvm/ADT/SetVector.h" 50 #include "llvm/ADT/StringExtras.h" 51 #include "llvm/ADT/StringSwitch.h" 52 #include "llvm/Support/CommandLine.h" 53 #include "llvm/Support/Compression.h" 54 #include "llvm/Support/Path.h" 55 #include "llvm/Support/TarWriter.h" 56 #include "llvm/Support/TargetSelect.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include <cstdlib> 59 #include <utility> 60 61 using namespace llvm; 62 using namespace llvm::ELF; 63 using namespace llvm::object; 64 using namespace llvm::sys; 65 66 using namespace lld; 67 using namespace lld::elf; 68 69 Configuration *elf::Config; 70 LinkerDriver *elf::Driver; 71 72 static void setConfigs(opt::InputArgList &Args); 73 74 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly, 75 raw_ostream &Error) { 76 errorHandler().LogName = Args[0]; 77 errorHandler().ErrorLimitExceededMsg = 78 "too many errors emitted, stopping now (use " 79 "-error-limit=0 to see all errors)"; 80 errorHandler().ErrorOS = &Error; 81 errorHandler().ExitEarly = CanExitEarly; 82 errorHandler().ColorDiagnostics = Error.has_colors(); 83 84 InputSections.clear(); 85 OutputSections.clear(); 86 Tar = nullptr; 87 BinaryFiles.clear(); 88 BitcodeFiles.clear(); 89 ObjectFiles.clear(); 90 SharedFiles.clear(); 91 92 Config = make<Configuration>(); 93 Driver = make<LinkerDriver>(); 94 Script = make<LinkerScript>(); 95 Symtab = make<SymbolTable>(); 96 Config->ProgName = Args[0]; 97 98 Driver->main(Args); 99 100 // Exit immediately if we don't need to return to the caller. 101 // This saves time because the overhead of calling destructors 102 // for all globally-allocated objects is not negligible. 103 if (CanExitEarly) 104 exitLld(errorCount() ? 1 : 0); 105 106 freeArena(); 107 return !errorCount(); 108 } 109 110 // Parses a linker -m option. 111 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) { 112 uint8_t OSABI = 0; 113 StringRef S = Emul; 114 if (S.endswith("_fbsd")) { 115 S = S.drop_back(5); 116 OSABI = ELFOSABI_FREEBSD; 117 } 118 119 std::pair<ELFKind, uint16_t> Ret = 120 StringSwitch<std::pair<ELFKind, uint16_t>>(S) 121 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64}) 122 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 123 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 124 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 125 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 126 .Case("elf32ppc", {ELF32BEKind, EM_PPC}) 127 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 128 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 129 .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 130 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 131 .Case("elf_i386", {ELF32LEKind, EM_386}) 132 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 133 .Default({ELFNoneKind, EM_NONE}); 134 135 if (Ret.first == ELFNoneKind) 136 error("unknown emulation: " + Emul); 137 return std::make_tuple(Ret.first, Ret.second, OSABI); 138 } 139 140 // Returns slices of MB by parsing MB as an archive file. 141 // Each slice consists of a member file in the archive. 142 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 143 MemoryBufferRef MB) { 144 std::unique_ptr<Archive> File = 145 CHECK(Archive::create(MB), 146 MB.getBufferIdentifier() + ": failed to parse archive"); 147 148 std::vector<std::pair<MemoryBufferRef, uint64_t>> V; 149 Error Err = Error::success(); 150 bool AddToTar = File->isThin() && Tar; 151 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) { 152 Archive::Child C = 153 CHECK(COrErr, MB.getBufferIdentifier() + 154 ": could not get the child of the archive"); 155 MemoryBufferRef MBRef = 156 CHECK(C.getMemoryBufferRef(), 157 MB.getBufferIdentifier() + 158 ": could not get the buffer for a child of the archive"); 159 if (AddToTar) 160 Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer()); 161 V.push_back(std::make_pair(MBRef, C.getChildOffset())); 162 } 163 if (Err) 164 fatal(MB.getBufferIdentifier() + ": Archive::children failed: " + 165 toString(std::move(Err))); 166 167 // Take ownership of memory buffers created for members of thin archives. 168 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers()) 169 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); 170 171 return V; 172 } 173 174 // Opens a file and create a file object. Path has to be resolved already. 175 void LinkerDriver::addFile(StringRef Path, bool WithLOption) { 176 using namespace sys::fs; 177 178 Optional<MemoryBufferRef> Buffer = readFile(Path); 179 if (!Buffer.hasValue()) 180 return; 181 MemoryBufferRef MBRef = *Buffer; 182 183 if (InBinary) { 184 Files.push_back(make<BinaryFile>(MBRef)); 185 return; 186 } 187 188 switch (identify_magic(MBRef.getBuffer())) { 189 case file_magic::unknown: 190 readLinkerScript(MBRef); 191 return; 192 case file_magic::archive: { 193 // Handle -whole-archive. 194 if (InWholeArchive) { 195 for (const auto &P : getArchiveMembers(MBRef)) 196 Files.push_back(createObjectFile(P.first, Path, P.second)); 197 return; 198 } 199 200 std::unique_ptr<Archive> File = 201 CHECK(Archive::create(MBRef), Path + ": failed to parse archive"); 202 203 // If an archive file has no symbol table, it is likely that a user 204 // is attempting LTO and using a default ar command that doesn't 205 // understand the LLVM bitcode file. It is a pretty common error, so 206 // we'll handle it as if it had a symbol table. 207 if (!File->isEmpty() && !File->hasSymbolTable()) { 208 for (const auto &P : getArchiveMembers(MBRef)) 209 Files.push_back(make<LazyObjFile>(P.first, Path, P.second)); 210 return; 211 } 212 213 // Handle the regular case. 214 Files.push_back(make<ArchiveFile>(std::move(File))); 215 return; 216 } 217 case file_magic::elf_shared_object: 218 if (Config->Relocatable) { 219 error("attempted static link of dynamic object " + Path); 220 return; 221 } 222 223 // DSOs usually have DT_SONAME tags in their ELF headers, and the 224 // sonames are used to identify DSOs. But if they are missing, 225 // they are identified by filenames. We don't know whether the new 226 // file has a DT_SONAME or not because we haven't parsed it yet. 227 // Here, we set the default soname for the file because we might 228 // need it later. 229 // 230 // If a file was specified by -lfoo, the directory part is not 231 // significant, as a user did not specify it. This behavior is 232 // compatible with GNU. 233 Files.push_back( 234 createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path)); 235 return; 236 case file_magic::bitcode: 237 case file_magic::elf_relocatable: 238 if (InLib) 239 Files.push_back(make<LazyObjFile>(MBRef, "", 0)); 240 else 241 Files.push_back(createObjectFile(MBRef)); 242 break; 243 default: 244 error(Path + ": unknown file type"); 245 } 246 } 247 248 // Add a given library by searching it from input search paths. 249 void LinkerDriver::addLibrary(StringRef Name) { 250 if (Optional<std::string> Path = searchLibrary(Name)) 251 addFile(*Path, /*WithLOption=*/true); 252 else 253 error("unable to find library -l" + Name); 254 } 255 256 // This function is called on startup. We need this for LTO since 257 // LTO calls LLVM functions to compile bitcode files to native code. 258 // Technically this can be delayed until we read bitcode files, but 259 // we don't bother to do lazily because the initialization is fast. 260 static void initLLVM() { 261 InitializeAllTargets(); 262 InitializeAllTargetMCs(); 263 InitializeAllAsmPrinters(); 264 InitializeAllAsmParsers(); 265 } 266 267 // Some command line options or some combinations of them are not allowed. 268 // This function checks for such errors. 269 static void checkOptions(opt::InputArgList &Args) { 270 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 271 // table which is a relatively new feature. 272 if (Config->EMachine == EM_MIPS && Config->GnuHash) 273 error("the .gnu.hash section is not compatible with the MIPS target."); 274 275 if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64) 276 error("--fix-cortex-a53-843419 is only supported on AArch64 targets."); 277 278 if (Config->Pie && Config->Shared) 279 error("-shared and -pie may not be used together"); 280 281 if (!Config->Shared && !Config->FilterList.empty()) 282 error("-F may not be used without -shared"); 283 284 if (!Config->Shared && !Config->AuxiliaryList.empty()) 285 error("-f may not be used without -shared"); 286 287 if (!Config->Relocatable && !Config->DefineCommon) 288 error("-no-define-common not supported in non relocatable output"); 289 290 if (Config->Relocatable) { 291 if (Config->Shared) 292 error("-r and -shared may not be used together"); 293 if (Config->GcSections) 294 error("-r and --gc-sections may not be used together"); 295 if (Config->ICF) 296 error("-r and --icf may not be used together"); 297 if (Config->Pie) 298 error("-r and -pie may not be used together"); 299 } 300 } 301 302 static const char *getReproduceOption(opt::InputArgList &Args) { 303 if (auto *Arg = Args.getLastArg(OPT_reproduce)) 304 return Arg->getValue(); 305 return getenv("LLD_REPRODUCE"); 306 } 307 308 static bool hasZOption(opt::InputArgList &Args, StringRef Key) { 309 for (auto *Arg : Args.filtered(OPT_z)) 310 if (Key == Arg->getValue()) 311 return true; 312 return false; 313 } 314 315 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) { 316 ELFOptTable Parser; 317 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1)); 318 319 // Interpret this flag early because error() depends on them. 320 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20); 321 322 // Handle -help 323 if (Args.hasArg(OPT_help)) { 324 printHelp(); 325 return; 326 } 327 328 // Handle -v or -version. 329 // 330 // A note about "compatible with GNU linkers" message: this is a hack for 331 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and 332 // still the newest version in March 2017) or earlier to recognize LLD as 333 // a GNU compatible linker. As long as an output for the -v option 334 // contains "GNU" or "with BFD", they recognize us as GNU-compatible. 335 // 336 // This is somewhat ugly hack, but in reality, we had no choice other 337 // than doing this. Considering the very long release cycle of Libtool, 338 // it is not easy to improve it to recognize LLD as a GNU compatible 339 // linker in a timely manner. Even if we can make it, there are still a 340 // lot of "configure" scripts out there that are generated by old version 341 // of Libtool. We cannot convince every software developer to migrate to 342 // the latest version and re-generate scripts. So we have this hack. 343 if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version)) 344 message(getLLDVersion() + " (compatible with GNU linkers)"); 345 346 // The behavior of -v or --version is a bit strange, but this is 347 // needed for compatibility with GNU linkers. 348 if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT)) 349 return; 350 if (Args.hasArg(OPT_version)) 351 return; 352 353 if (const char *Path = getReproduceOption(Args)) { 354 // Note that --reproduce is a debug option so you can ignore it 355 // if you are trying to understand the whole picture of the code. 356 Expected<std::unique_ptr<TarWriter>> ErrOrWriter = 357 TarWriter::create(Path, path::stem(Path)); 358 if (ErrOrWriter) { 359 Tar = ErrOrWriter->get(); 360 Tar->append("response.txt", createResponseFile(Args)); 361 Tar->append("version.txt", getLLDVersion() + "\n"); 362 make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter)); 363 } else { 364 error(Twine("--reproduce: failed to open ") + Path + ": " + 365 toString(ErrOrWriter.takeError())); 366 } 367 } 368 369 readConfigs(Args); 370 initLLVM(); 371 createFiles(Args); 372 inferMachineType(); 373 setConfigs(Args); 374 checkOptions(Args); 375 if (errorCount()) 376 return; 377 378 switch (Config->EKind) { 379 case ELF32LEKind: 380 link<ELF32LE>(Args); 381 return; 382 case ELF32BEKind: 383 link<ELF32BE>(Args); 384 return; 385 case ELF64LEKind: 386 link<ELF64LE>(Args); 387 return; 388 case ELF64BEKind: 389 link<ELF64BE>(Args); 390 return; 391 default: 392 llvm_unreachable("unknown Config->EKind"); 393 } 394 } 395 396 static std::string getRpath(opt::InputArgList &Args) { 397 std::vector<StringRef> V = args::getStrings(Args, OPT_rpath); 398 return llvm::join(V.begin(), V.end(), ":"); 399 } 400 401 // Determines what we should do if there are remaining unresolved 402 // symbols after the name resolution. 403 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) { 404 if (Args.hasArg(OPT_relocatable)) 405 return UnresolvedPolicy::IgnoreAll; 406 407 UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols, 408 OPT_warn_unresolved_symbols, true) 409 ? UnresolvedPolicy::ReportError 410 : UnresolvedPolicy::Warn; 411 412 // Process the last of -unresolved-symbols, -no-undefined or -z defs. 413 for (auto *Arg : llvm::reverse(Args)) { 414 switch (Arg->getOption().getID()) { 415 case OPT_unresolved_symbols: { 416 StringRef S = Arg->getValue(); 417 if (S == "ignore-all" || S == "ignore-in-object-files") 418 return UnresolvedPolicy::Ignore; 419 if (S == "ignore-in-shared-libs" || S == "report-all") 420 return ErrorOrWarn; 421 error("unknown --unresolved-symbols value: " + S); 422 continue; 423 } 424 case OPT_no_undefined: 425 return ErrorOrWarn; 426 case OPT_z: 427 if (StringRef(Arg->getValue()) == "defs") 428 return ErrorOrWarn; 429 continue; 430 } 431 } 432 433 // -shared implies -unresolved-symbols=ignore-all because missing 434 // symbols are likely to be resolved at runtime using other DSOs. 435 if (Config->Shared) 436 return UnresolvedPolicy::Ignore; 437 return ErrorOrWarn; 438 } 439 440 static Target2Policy getTarget2(opt::InputArgList &Args) { 441 StringRef S = Args.getLastArgValue(OPT_target2, "got-rel"); 442 if (S == "rel") 443 return Target2Policy::Rel; 444 if (S == "abs") 445 return Target2Policy::Abs; 446 if (S == "got-rel") 447 return Target2Policy::GotRel; 448 error("unknown --target2 option: " + S); 449 return Target2Policy::GotRel; 450 } 451 452 static bool isOutputFormatBinary(opt::InputArgList &Args) { 453 if (auto *Arg = Args.getLastArg(OPT_oformat)) { 454 StringRef S = Arg->getValue(); 455 if (S == "binary") 456 return true; 457 error("unknown --oformat value: " + S); 458 } 459 return false; 460 } 461 462 static DiscardPolicy getDiscard(opt::InputArgList &Args) { 463 if (Args.hasArg(OPT_relocatable)) 464 return DiscardPolicy::None; 465 466 auto *Arg = 467 Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 468 if (!Arg) 469 return DiscardPolicy::Default; 470 if (Arg->getOption().getID() == OPT_discard_all) 471 return DiscardPolicy::All; 472 if (Arg->getOption().getID() == OPT_discard_locals) 473 return DiscardPolicy::Locals; 474 return DiscardPolicy::None; 475 } 476 477 static StringRef getDynamicLinker(opt::InputArgList &Args) { 478 auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 479 if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker) 480 return ""; 481 return Arg->getValue(); 482 } 483 484 static StripPolicy getStrip(opt::InputArgList &Args) { 485 if (Args.hasArg(OPT_relocatable)) 486 return StripPolicy::None; 487 488 auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug); 489 if (!Arg) 490 return StripPolicy::None; 491 if (Arg->getOption().getID() == OPT_strip_all) 492 return StripPolicy::All; 493 return StripPolicy::Debug; 494 } 495 496 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) { 497 uint64_t VA = 0; 498 if (S.startswith("0x")) 499 S = S.drop_front(2); 500 if (!to_integer(S, VA, 16)) 501 error("invalid argument: " + toString(Arg)); 502 return VA; 503 } 504 505 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) { 506 StringMap<uint64_t> Ret; 507 for (auto *Arg : Args.filtered(OPT_section_start)) { 508 StringRef Name; 509 StringRef Addr; 510 std::tie(Name, Addr) = StringRef(Arg->getValue()).split('='); 511 Ret[Name] = parseSectionAddress(Addr, *Arg); 512 } 513 514 if (auto *Arg = Args.getLastArg(OPT_Ttext)) 515 Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg); 516 if (auto *Arg = Args.getLastArg(OPT_Tdata)) 517 Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg); 518 if (auto *Arg = Args.getLastArg(OPT_Tbss)) 519 Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg); 520 return Ret; 521 } 522 523 static SortSectionPolicy getSortSection(opt::InputArgList &Args) { 524 StringRef S = Args.getLastArgValue(OPT_sort_section); 525 if (S == "alignment") 526 return SortSectionPolicy::Alignment; 527 if (S == "name") 528 return SortSectionPolicy::Name; 529 if (!S.empty()) 530 error("unknown --sort-section rule: " + S); 531 return SortSectionPolicy::Default; 532 } 533 534 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) { 535 StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place"); 536 if (S == "warn") 537 return OrphanHandlingPolicy::Warn; 538 if (S == "error") 539 return OrphanHandlingPolicy::Error; 540 if (S != "place") 541 error("unknown --orphan-handling mode: " + S); 542 return OrphanHandlingPolicy::Place; 543 } 544 545 // Parse --build-id or --build-id=<style>. We handle "tree" as a 546 // synonym for "sha1" because all our hash functions including 547 // -build-id=sha1 are actually tree hashes for performance reasons. 548 static std::pair<BuildIdKind, std::vector<uint8_t>> 549 getBuildId(opt::InputArgList &Args) { 550 auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq); 551 if (!Arg) 552 return {BuildIdKind::None, {}}; 553 554 if (Arg->getOption().getID() == OPT_build_id) 555 return {BuildIdKind::Fast, {}}; 556 557 StringRef S = Arg->getValue(); 558 if (S == "fast") 559 return {BuildIdKind::Fast, {}}; 560 if (S == "md5") 561 return {BuildIdKind::Md5, {}}; 562 if (S == "sha1" || S == "tree") 563 return {BuildIdKind::Sha1, {}}; 564 if (S == "uuid") 565 return {BuildIdKind::Uuid, {}}; 566 if (S.startswith("0x")) 567 return {BuildIdKind::Hexstring, parseHex(S.substr(2))}; 568 569 if (S != "none") 570 error("unknown --build-id style: " + S); 571 return {BuildIdKind::None, {}}; 572 } 573 574 static bool getCompressDebugSections(opt::InputArgList &Args) { 575 StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none"); 576 if (S == "none") 577 return false; 578 if (S != "zlib") 579 error("unknown --compress-debug-sections value: " + S); 580 if (!zlib::isAvailable()) 581 error("--compress-debug-sections: zlib is not available"); 582 return true; 583 } 584 585 static int parseInt(StringRef S, opt::Arg *Arg) { 586 int V = 0; 587 if (!to_integer(S, V, 10)) 588 error(Arg->getSpelling() + "=" + Arg->getValue() + 589 ": number expected, but got '" + S + "'"); 590 return V; 591 } 592 593 // Parse the symbol ordering file and warn for any duplicate entries. 594 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef MB) { 595 SetVector<StringRef> Names; 596 for (StringRef S : args::getLines(MB)) 597 if (!Names.insert(S) && Config->WarnSymbolOrdering) 598 warn(MB.getBufferIdentifier() + ": duplicate ordered symbol: " + S); 599 600 return Names.takeVector(); 601 } 602 603 // Initializes Config members by the command line options. 604 void LinkerDriver::readConfigs(opt::InputArgList &Args) { 605 errorHandler().Verbose = Args.hasArg(OPT_verbose); 606 errorHandler().FatalWarnings = 607 Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false); 608 609 Config->AllowMultipleDefinition = 610 Args.hasFlag(OPT_allow_multiple_definition, 611 OPT_no_allow_multiple_definition, false) || 612 hasZOption(Args, "muldefs"); 613 Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary); 614 Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic); 615 Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions); 616 Config->CheckSections = 617 Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 618 Config->Chroot = Args.getLastArgValue(OPT_chroot); 619 Config->CompressDebugSections = getCompressDebugSections(Args); 620 Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common, 621 !Args.hasArg(OPT_relocatable)); 622 Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true); 623 Config->DisableVerify = Args.hasArg(OPT_disable_verify); 624 Config->Discard = getDiscard(Args); 625 Config->DynamicLinker = getDynamicLinker(Args); 626 Config->EhFrameHdr = 627 Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 628 Config->EmitRelocs = Args.hasArg(OPT_emit_relocs); 629 Config->EnableNewDtags = 630 Args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 631 Config->Entry = Args.getLastArgValue(OPT_entry); 632 Config->ExportDynamic = 633 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 634 Config->FilterList = args::getStrings(Args, OPT_filter); 635 Config->Fini = Args.getLastArgValue(OPT_fini, "_fini"); 636 Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419); 637 Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 638 Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 639 Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 640 Config->ICF = Args.hasFlag(OPT_icf_all, OPT_icf_none, false); 641 Config->IgnoreDataAddressEquality = 642 Args.hasArg(OPT_ignore_data_address_equality); 643 Config->IgnoreFunctionAddressEquality = 644 Args.hasArg(OPT_ignore_function_address_equality); 645 Config->Init = Args.getLastArgValue(OPT_init, "_init"); 646 Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline); 647 Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes); 648 Config->LTOO = args::getInteger(Args, OPT_lto_O, 2); 649 Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1); 650 Config->MapFile = Args.getLastArgValue(OPT_Map); 651 Config->MergeArmExidx = 652 Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 653 Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec); 654 Config->Nostdlib = Args.hasArg(OPT_nostdlib); 655 Config->OFormatBinary = isOutputFormatBinary(Args); 656 Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false); 657 Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename); 658 Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness); 659 Config->Optimize = args::getInteger(Args, OPT_O, 1); 660 Config->OrphanHandling = getOrphanHandling(Args); 661 Config->OutputFile = Args.getLastArgValue(OPT_o); 662 Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false); 663 Config->PrintIcfSections = 664 Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 665 Config->PrintGcSections = 666 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 667 Config->Rpath = getRpath(Args); 668 Config->Relocatable = Args.hasArg(OPT_relocatable); 669 Config->SaveTemps = Args.hasArg(OPT_save_temps); 670 Config->SearchPaths = args::getStrings(Args, OPT_library_path); 671 Config->SectionStartMap = getSectionStartMap(Args); 672 Config->Shared = Args.hasArg(OPT_shared); 673 Config->SingleRoRx = Args.hasArg(OPT_no_rosegment); 674 Config->SoName = Args.getLastArgValue(OPT_soname); 675 Config->SortSection = getSortSection(Args); 676 Config->Strip = getStrip(Args); 677 Config->Sysroot = Args.getLastArgValue(OPT_sysroot); 678 Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 679 Config->Target2 = getTarget2(Args); 680 Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir); 681 Config->ThinLTOCachePolicy = CHECK( 682 parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)), 683 "--thinlto-cache-policy: invalid cache policy"); 684 Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u); 685 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true); 686 Config->Trace = Args.hasArg(OPT_trace); 687 Config->Undefined = args::getStrings(Args, OPT_undefined); 688 Config->UndefinedVersion = 689 Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true); 690 Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args); 691 Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 692 Config->WarnSymbolOrdering = 693 Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 694 Config->ZCombreloc = !hasZOption(Args, "nocombreloc"); 695 Config->ZExecstack = hasZOption(Args, "execstack"); 696 Config->ZHazardplt = hasZOption(Args, "hazardplt"); 697 Config->ZNocopyreloc = hasZOption(Args, "nocopyreloc"); 698 Config->ZNodelete = hasZOption(Args, "nodelete"); 699 Config->ZNodlopen = hasZOption(Args, "nodlopen"); 700 Config->ZNow = hasZOption(Args, "now"); 701 Config->ZOrigin = hasZOption(Args, "origin"); 702 Config->ZRelro = !hasZOption(Args, "norelro"); 703 Config->ZRetpolineplt = hasZOption(Args, "retpolineplt"); 704 Config->ZRodynamic = hasZOption(Args, "rodynamic"); 705 Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0); 706 Config->ZText = !hasZOption(Args, "notext"); 707 Config->ZWxneeded = hasZOption(Args, "wxneeded"); 708 709 // Parse LTO plugin-related options for compatibility with gold. 710 std::vector<const char *> LTOOptions({Config->ProgName.data()}); 711 for (auto *Arg : Args.filtered(OPT_plugin_opt)) { 712 StringRef S = Arg->getValue(); 713 if (S == "disable-verify") 714 Config->DisableVerify = true; 715 else if (S == "save-temps") 716 Config->SaveTemps = true; 717 else if (S.startswith("O")) 718 Config->LTOO = parseInt(S.substr(1), Arg); 719 else if (S.startswith("lto-partitions=")) 720 Config->LTOPartitions = parseInt(S.substr(15), Arg); 721 else if (S.startswith("jobs=")) 722 Config->ThinLTOJobs = parseInt(S.substr(5), Arg); 723 else if (S.startswith("mcpu=")) 724 LTOOptions.push_back(Saver.save("-" + S).data()); 725 else if (!S.startswith("/") && !S.startswith("-fresolution=") && 726 !S.startswith("-pass-through=") && !S.startswith("thinlto")) 727 LTOOptions.push_back(S.data()); 728 } 729 // Parse and evaluate -mllvm options. 730 for (auto *Arg : Args.filtered(OPT_mllvm)) 731 LTOOptions.push_back(Arg->getValue()); 732 cl::ParseCommandLineOptions(LTOOptions.size(), LTOOptions.data()); 733 734 if (Config->LTOO > 3) 735 error("invalid optimization level for LTO: " + Twine(Config->LTOO)); 736 if (Config->LTOPartitions == 0) 737 error("--lto-partitions: number of threads must be > 0"); 738 if (Config->ThinLTOJobs == 0) 739 error("--thinlto-jobs: number of threads must be > 0"); 740 741 // Parse ELF{32,64}{LE,BE} and CPU type. 742 if (auto *Arg = Args.getLastArg(OPT_m)) { 743 StringRef S = Arg->getValue(); 744 std::tie(Config->EKind, Config->EMachine, Config->OSABI) = 745 parseEmulation(S); 746 Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32"); 747 Config->Emulation = S; 748 } 749 750 // Parse -hash-style={sysv,gnu,both}. 751 if (auto *Arg = Args.getLastArg(OPT_hash_style)) { 752 StringRef S = Arg->getValue(); 753 if (S == "sysv") 754 Config->SysvHash = true; 755 else if (S == "gnu") 756 Config->GnuHash = true; 757 else if (S == "both") 758 Config->SysvHash = Config->GnuHash = true; 759 else 760 error("unknown -hash-style: " + S); 761 } 762 763 if (Args.hasArg(OPT_print_map)) 764 Config->MapFile = "-"; 765 766 // --omagic is an option to create old-fashioned executables in which 767 // .text segments are writable. Today, the option is still in use to 768 // create special-purpose programs such as boot loaders. It doesn't 769 // make sense to create PT_GNU_RELRO for such executables. 770 if (Config->Omagic) 771 Config->ZRelro = false; 772 773 std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args); 774 775 if (auto *Arg = Args.getLastArg(OPT_pack_dyn_relocs)) { 776 StringRef S = Arg->getValue(); 777 if (S == "android") 778 Config->AndroidPackDynRelocs = true; 779 else if (S != "none") 780 error("unknown -pack-dyn-relocs format: " + S); 781 } 782 783 if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file)) 784 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 785 Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer); 786 787 // If --retain-symbol-file is used, we'll keep only the symbols listed in 788 // the file and discard all others. 789 if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) { 790 Config->DefaultSymbolVersion = VER_NDX_LOCAL; 791 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 792 for (StringRef S : args::getLines(*Buffer)) 793 Config->VersionScriptGlobals.push_back( 794 {S, /*IsExternCpp*/ false, /*HasWildcard*/ false}); 795 } 796 797 bool HasExportDynamic = 798 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 799 800 // Parses -dynamic-list and -export-dynamic-symbol. They make some 801 // symbols private. Note that -export-dynamic takes precedence over them 802 // as it says all symbols should be exported. 803 if (!HasExportDynamic) { 804 for (auto *Arg : Args.filtered(OPT_dynamic_list)) 805 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 806 readDynamicList(*Buffer); 807 808 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol)) 809 Config->DynamicList.push_back( 810 {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false}); 811 } 812 813 // If --export-dynamic-symbol=foo is given and symbol foo is defined in 814 // an object file in an archive file, that object file should be pulled 815 // out and linked. (It doesn't have to behave like that from technical 816 // point of view, but this is needed for compatibility with GNU.) 817 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol)) 818 Config->Undefined.push_back(Arg->getValue()); 819 820 for (auto *Arg : Args.filtered(OPT_version_script)) 821 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 822 readVersionScript(*Buffer); 823 } 824 825 // Some Config members do not directly correspond to any particular 826 // command line options, but computed based on other Config values. 827 // This function initialize such members. See Config.h for the details 828 // of these values. 829 static void setConfigs(opt::InputArgList &Args) { 830 ELFKind Kind = Config->EKind; 831 uint16_t Machine = Config->EMachine; 832 833 // There is an ILP32 ABI for x86-64, although it's not very popular. 834 // It is called the x32 ABI. 835 bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64); 836 837 Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs); 838 Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind); 839 Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind); 840 Config->Endianness = 841 Config->IsLE ? support::endianness::little : support::endianness::big; 842 Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS); 843 Config->IsRela = 844 (Config->Is64 || IsX32 || Machine == EM_PPC) && Machine != EM_MIPS; 845 Config->Pic = Config->Pie || Config->Shared; 846 Config->Wordsize = Config->Is64 ? 8 : 4; 847 // If the output uses REL relocations we must store the dynamic relocation 848 // addends to the output sections. We also store addends for RELA relocations 849 // if --apply-dynamic-relocs is used. 850 // We default to not writing the addends when using RELA relocations since 851 // any standard conforming tool can find it in r_addend. 852 Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs, 853 OPT_no_apply_dynamic_relocs, false) || 854 !Config->IsRela; 855 } 856 857 // Returns a value of "-format" option. 858 static bool getBinaryOption(StringRef S) { 859 if (S == "binary") 860 return true; 861 if (S == "elf" || S == "default") 862 return false; 863 error("unknown -format value: " + S + 864 " (supported formats: elf, default, binary)"); 865 return false; 866 } 867 868 void LinkerDriver::createFiles(opt::InputArgList &Args) { 869 for (auto *Arg : Args) { 870 switch (Arg->getOption().getUnaliasedOption().getID()) { 871 case OPT_library: 872 addLibrary(Arg->getValue()); 873 break; 874 case OPT_INPUT: 875 addFile(Arg->getValue(), /*WithLOption=*/false); 876 break; 877 case OPT_defsym: { 878 StringRef From; 879 StringRef To; 880 std::tie(From, To) = StringRef(Arg->getValue()).split('='); 881 readDefsym(From, MemoryBufferRef(To, "-defsym")); 882 break; 883 } 884 case OPT_script: 885 if (Optional<std::string> Path = searchLinkerScript(Arg->getValue())) { 886 if (Optional<MemoryBufferRef> MB = readFile(*Path)) 887 readLinkerScript(*MB); 888 break; 889 } 890 error(Twine("cannot find linker script ") + Arg->getValue()); 891 break; 892 case OPT_as_needed: 893 Config->AsNeeded = true; 894 break; 895 case OPT_format: 896 InBinary = getBinaryOption(Arg->getValue()); 897 break; 898 case OPT_no_as_needed: 899 Config->AsNeeded = false; 900 break; 901 case OPT_Bstatic: 902 Config->Static = true; 903 break; 904 case OPT_Bdynamic: 905 Config->Static = false; 906 break; 907 case OPT_whole_archive: 908 InWholeArchive = true; 909 break; 910 case OPT_no_whole_archive: 911 InWholeArchive = false; 912 break; 913 case OPT_start_lib: 914 InLib = true; 915 break; 916 case OPT_end_lib: 917 InLib = false; 918 break; 919 } 920 } 921 922 if (Files.empty() && errorCount() == 0) 923 error("no input files"); 924 } 925 926 // If -m <machine_type> was not given, infer it from object files. 927 void LinkerDriver::inferMachineType() { 928 if (Config->EKind != ELFNoneKind) 929 return; 930 931 for (InputFile *F : Files) { 932 if (F->EKind == ELFNoneKind) 933 continue; 934 Config->EKind = F->EKind; 935 Config->EMachine = F->EMachine; 936 Config->OSABI = F->OSABI; 937 Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F); 938 return; 939 } 940 error("target emulation unknown: -m or at least one .o file required"); 941 } 942 943 // Parse -z max-page-size=<value>. The default value is defined by 944 // each target. 945 static uint64_t getMaxPageSize(opt::InputArgList &Args) { 946 uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size", 947 Target->DefaultMaxPageSize); 948 if (!isPowerOf2_64(Val)) 949 error("max-page-size: value isn't a power of 2"); 950 return Val; 951 } 952 953 // Parses -image-base option. 954 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) { 955 // Because we are using "Config->MaxPageSize" here, this function has to be 956 // called after the variable is initialized. 957 auto *Arg = Args.getLastArg(OPT_image_base); 958 if (!Arg) 959 return None; 960 961 StringRef S = Arg->getValue(); 962 uint64_t V; 963 if (!to_integer(S, V)) { 964 error("-image-base: number expected, but got " + S); 965 return 0; 966 } 967 if ((V % Config->MaxPageSize) != 0) 968 warn("-image-base: address isn't multiple of page size: " + S); 969 return V; 970 } 971 972 // Parses `--exclude-libs=lib,lib,...`. 973 // The library names may be delimited by commas or colons. 974 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) { 975 DenseSet<StringRef> Ret; 976 for (auto *Arg : Args.filtered(OPT_exclude_libs)) { 977 StringRef S = Arg->getValue(); 978 for (;;) { 979 size_t Pos = S.find_first_of(",:"); 980 if (Pos == StringRef::npos) 981 break; 982 Ret.insert(S.substr(0, Pos)); 983 S = S.substr(Pos + 1); 984 } 985 Ret.insert(S); 986 } 987 return Ret; 988 } 989 990 // Handles the -exclude-libs option. If a static library file is specified 991 // by the -exclude-libs option, all public symbols from the archive become 992 // private unless otherwise specified by version scripts or something. 993 // A special library name "ALL" means all archive files. 994 // 995 // This is not a popular option, but some programs such as bionic libc use it. 996 template <class ELFT> 997 static void excludeLibs(opt::InputArgList &Args) { 998 DenseSet<StringRef> Libs = getExcludeLibs(Args); 999 bool All = Libs.count("ALL"); 1000 1001 for (InputFile *File : ObjectFiles) 1002 if (!File->ArchiveName.empty()) 1003 if (All || Libs.count(path::filename(File->ArchiveName))) 1004 for (Symbol *Sym : File->getSymbols()) 1005 if (!Sym->isLocal() && Sym->File == File) 1006 Sym->VersionId = VER_NDX_LOCAL; 1007 } 1008 1009 // Do actual linking. Note that when this function is called, 1010 // all linker scripts have already been parsed. 1011 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) { 1012 Target = getTarget(); 1013 1014 Config->MaxPageSize = getMaxPageSize(Args); 1015 Config->ImageBase = getImageBase(Args); 1016 1017 // If a -hash-style option was not given, set to a default value, 1018 // which varies depending on the target. 1019 if (!Args.hasArg(OPT_hash_style)) { 1020 if (Config->EMachine == EM_MIPS) 1021 Config->SysvHash = true; 1022 else 1023 Config->SysvHash = Config->GnuHash = true; 1024 } 1025 1026 // Default output filename is "a.out" by the Unix tradition. 1027 if (Config->OutputFile.empty()) 1028 Config->OutputFile = "a.out"; 1029 1030 // Fail early if the output file or map file is not writable. If a user has a 1031 // long link, e.g. due to a large LTO link, they do not wish to run it and 1032 // find that it failed because there was a mistake in their command-line. 1033 if (auto E = tryCreateFile(Config->OutputFile)) 1034 error("cannot open output file " + Config->OutputFile + ": " + E.message()); 1035 if (auto E = tryCreateFile(Config->MapFile)) 1036 error("cannot open map file " + Config->MapFile + ": " + E.message()); 1037 if (errorCount()) 1038 return; 1039 1040 // Use default entry point name if no name was given via the command 1041 // line nor linker scripts. For some reason, MIPS entry point name is 1042 // different from others. 1043 Config->WarnMissingEntry = 1044 (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable)); 1045 if (Config->Entry.empty() && !Config->Relocatable) 1046 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start"; 1047 1048 // Handle --trace-symbol. 1049 for (auto *Arg : Args.filtered(OPT_trace_symbol)) 1050 Symtab->trace(Arg->getValue()); 1051 1052 // Add all files to the symbol table. This will add almost all 1053 // symbols that we need to the symbol table. 1054 for (InputFile *F : Files) 1055 Symtab->addFile<ELFT>(F); 1056 1057 // Now that we have every file, we can decide if we will need a 1058 // dynamic symbol table. 1059 // We need one if we were asked to export dynamic symbols or if we are 1060 // producing a shared library. 1061 // We also need one if any shared libraries are used and for pie executables 1062 // (probably because the dynamic linker needs it). 1063 Config->HasDynSymTab = 1064 !SharedFiles.empty() || Config->Pic || Config->ExportDynamic; 1065 1066 // Some symbols (such as __ehdr_start) are defined lazily only when there 1067 // are undefined symbols for them, so we add these to trigger that logic. 1068 for (StringRef Sym : Script->ReferencedSymbols) 1069 Symtab->addUndefined<ELFT>(Sym); 1070 1071 // Handle the `--undefined <sym>` options. 1072 for (StringRef S : Config->Undefined) 1073 Symtab->fetchIfLazy<ELFT>(S); 1074 1075 // If an entry symbol is in a static archive, pull out that file now 1076 // to complete the symbol table. After this, no new names except a 1077 // few linker-synthesized ones will be added to the symbol table. 1078 Symtab->fetchIfLazy<ELFT>(Config->Entry); 1079 1080 // Return if there were name resolution errors. 1081 if (errorCount()) 1082 return; 1083 1084 // We want to declare linker script's symbols early, 1085 // so that we can version them. 1086 // They also might be exported if referenced by DSOs. 1087 Script->declareSymbols(); 1088 1089 // Handle the -exclude-libs option. 1090 if (Args.hasArg(OPT_exclude_libs)) 1091 excludeLibs<ELFT>(Args); 1092 1093 // Create ElfHeader early. We need a dummy section in 1094 // addReservedSymbols to mark the created symbols as not absolute. 1095 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC); 1096 Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr); 1097 1098 // We need to create some reserved symbols such as _end. Create them. 1099 if (!Config->Relocatable) 1100 addReservedSymbols(); 1101 1102 // Apply version scripts. 1103 // 1104 // For a relocatable output, version scripts don't make sense, and 1105 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 1106 // name "foo@ver1") rather do harm, so we don't call this if -r is given. 1107 if (!Config->Relocatable) 1108 Symtab->scanVersionScript(); 1109 1110 // Create wrapped symbols for -wrap option. 1111 for (auto *Arg : Args.filtered(OPT_wrap)) 1112 Symtab->addSymbolWrap<ELFT>(Arg->getValue()); 1113 1114 Symtab->addCombinedLTOObject<ELFT>(); 1115 if (errorCount()) 1116 return; 1117 1118 // Apply symbol renames for -wrap. 1119 Symtab->applySymbolWrap(); 1120 1121 // Now that we have a complete list of input files. 1122 // Beyond this point, no new files are added. 1123 // Aggregate all input sections into one place. 1124 for (InputFile *F : ObjectFiles) 1125 for (InputSectionBase *S : F->getSections()) 1126 if (S && S != &InputSection::Discarded) 1127 InputSections.push_back(S); 1128 for (BinaryFile *F : BinaryFiles) 1129 for (InputSectionBase *S : F->getSections()) 1130 InputSections.push_back(cast<InputSection>(S)); 1131 1132 // We do not want to emit debug sections if --strip-all 1133 // or -strip-debug are given. 1134 if (Config->Strip != StripPolicy::None) 1135 llvm::erase_if(InputSections, [](InputSectionBase *S) { 1136 return S->Name.startswith(".debug") || S->Name.startswith(".zdebug"); 1137 }); 1138 1139 Config->EFlags = Target->calcEFlags(); 1140 1141 if (Config->EMachine == EM_ARM) { 1142 // FIXME: These warnings can be removed when lld only uses these features 1143 // when the input objects have been compiled with an architecture that 1144 // supports them. 1145 if (Config->ARMHasBlx == false) 1146 warn("lld uses blx instruction, no object with architecture supporting " 1147 "feature detected."); 1148 if (Config->ARMJ1J2BranchEncoding == false) 1149 warn("lld uses extended branch encoding, no object with architecture " 1150 "supporting feature detected."); 1151 if (Config->ARMHasMovtMovw == false) 1152 warn("lld may use movt/movw, no object with architecture supporting " 1153 "feature detected."); 1154 } 1155 1156 // This adds a .comment section containing a version string. We have to add it 1157 // before decompressAndMergeSections because the .comment section is a 1158 // mergeable section. 1159 if (!Config->Relocatable) 1160 InputSections.push_back(createCommentSection()); 1161 1162 // Do size optimizations: garbage collection, merging of SHF_MERGE sections 1163 // and identical code folding. 1164 markLive<ELFT>(); 1165 decompressSections(); 1166 mergeSections(); 1167 if (Config->ICF) 1168 doIcf<ELFT>(); 1169 1170 // Write the result to the file. 1171 writeResult<ELFT>(); 1172 } 1173