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/Threads.h" 47 #include "lld/Common/Version.h" 48 #include "llvm/ADT/SetVector.h" 49 #include "llvm/ADT/StringExtras.h" 50 #include "llvm/ADT/StringSwitch.h" 51 #include "llvm/Support/CommandLine.h" 52 #include "llvm/Support/Compression.h" 53 #include "llvm/Support/LEB128.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 using namespace llvm::support; 66 67 using namespace lld; 68 using namespace lld::elf; 69 70 Configuration *elf::Config; 71 LinkerDriver *elf::Driver; 72 73 static void setConfigs(opt::InputArgList &Args); 74 static void readConfigs(opt::InputArgList &Args); 75 76 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly, 77 raw_ostream &Error) { 78 errorHandler().LogName = args::getFilenameWithoutExe(Args[0]); 79 errorHandler().ErrorLimitExceededMsg = 80 "too many errors emitted, stopping now (use " 81 "-error-limit=0 to see all errors)"; 82 errorHandler().ErrorOS = &Error; 83 errorHandler().ExitEarly = CanExitEarly; 84 errorHandler().ColorDiagnostics = Error.has_colors(); 85 86 InputSections.clear(); 87 OutputSections.clear(); 88 BinaryFiles.clear(); 89 BitcodeFiles.clear(); 90 ObjectFiles.clear(); 91 SharedFiles.clear(); 92 93 Config = make<Configuration>(); 94 Driver = make<LinkerDriver>(); 95 Script = make<LinkerScript>(); 96 Symtab = make<SymbolTable>(); 97 98 Tar = nullptr; 99 memset(&In, 0, sizeof(In)); 100 101 Partitions = {Partition()}; 102 103 SharedFile::VernauxNum = 0; 104 105 Config->ProgName = Args[0]; 106 107 Driver->main(Args); 108 109 // Exit immediately if we don't need to return to the caller. 110 // This saves time because the overhead of calling destructors 111 // for all globally-allocated objects is not negligible. 112 if (CanExitEarly) 113 exitLld(errorCount() ? 1 : 0); 114 115 freeArena(); 116 return !errorCount(); 117 } 118 119 // Parses a linker -m option. 120 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) { 121 uint8_t OSABI = 0; 122 StringRef S = Emul; 123 if (S.endswith("_fbsd")) { 124 S = S.drop_back(5); 125 OSABI = ELFOSABI_FREEBSD; 126 } 127 128 std::pair<ELFKind, uint16_t> Ret = 129 StringSwitch<std::pair<ELFKind, uint16_t>>(S) 130 .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec", 131 {ELF64LEKind, EM_AARCH64}) 132 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM}) 133 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64}) 134 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS}) 135 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS}) 136 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV}) 137 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC}) 138 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS}) 139 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS}) 140 .Case("elf64lriscv", {ELF64LEKind, EM_RISCV}) 141 .Case("elf64ppc", {ELF64BEKind, EM_PPC64}) 142 .Case("elf64lppc", {ELF64LEKind, EM_PPC64}) 143 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64}) 144 .Case("elf_i386", {ELF32LEKind, EM_386}) 145 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU}) 146 .Default({ELFNoneKind, EM_NONE}); 147 148 if (Ret.first == ELFNoneKind) 149 error("unknown emulation: " + Emul); 150 return std::make_tuple(Ret.first, Ret.second, OSABI); 151 } 152 153 // Returns slices of MB by parsing MB as an archive file. 154 // Each slice consists of a member file in the archive. 155 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers( 156 MemoryBufferRef MB) { 157 std::unique_ptr<Archive> File = 158 CHECK(Archive::create(MB), 159 MB.getBufferIdentifier() + ": failed to parse archive"); 160 161 std::vector<std::pair<MemoryBufferRef, uint64_t>> V; 162 Error Err = Error::success(); 163 bool AddToTar = File->isThin() && Tar; 164 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) { 165 Archive::Child C = 166 CHECK(COrErr, MB.getBufferIdentifier() + 167 ": could not get the child of the archive"); 168 MemoryBufferRef MBRef = 169 CHECK(C.getMemoryBufferRef(), 170 MB.getBufferIdentifier() + 171 ": could not get the buffer for a child of the archive"); 172 if (AddToTar) 173 Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer()); 174 V.push_back(std::make_pair(MBRef, C.getChildOffset())); 175 } 176 if (Err) 177 fatal(MB.getBufferIdentifier() + ": Archive::children failed: " + 178 toString(std::move(Err))); 179 180 // Take ownership of memory buffers created for members of thin archives. 181 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers()) 182 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); 183 184 return V; 185 } 186 187 // Opens a file and create a file object. Path has to be resolved already. 188 void LinkerDriver::addFile(StringRef Path, bool WithLOption) { 189 using namespace sys::fs; 190 191 Optional<MemoryBufferRef> Buffer = readFile(Path); 192 if (!Buffer.hasValue()) 193 return; 194 MemoryBufferRef MBRef = *Buffer; 195 196 if (Config->FormatBinary) { 197 Files.push_back(make<BinaryFile>(MBRef)); 198 return; 199 } 200 201 switch (identify_magic(MBRef.getBuffer())) { 202 case file_magic::unknown: 203 readLinkerScript(MBRef); 204 return; 205 case file_magic::archive: { 206 // Handle -whole-archive. 207 if (InWholeArchive) { 208 for (const auto &P : getArchiveMembers(MBRef)) 209 Files.push_back(createObjectFile(P.first, Path, P.second)); 210 return; 211 } 212 213 std::unique_ptr<Archive> File = 214 CHECK(Archive::create(MBRef), Path + ": failed to parse archive"); 215 216 // If an archive file has no symbol table, it is likely that a user 217 // is attempting LTO and using a default ar command that doesn't 218 // understand the LLVM bitcode file. It is a pretty common error, so 219 // we'll handle it as if it had a symbol table. 220 if (!File->isEmpty() && !File->hasSymbolTable()) { 221 // Check if all members are bitcode files. If not, ignore, which is the 222 // default action without the LTO hack described above. 223 for (const std::pair<MemoryBufferRef, uint64_t> &P : 224 getArchiveMembers(MBRef)) 225 if (identify_magic(P.first.getBuffer()) != file_magic::bitcode) 226 return; 227 228 for (const std::pair<MemoryBufferRef, uint64_t> &P : 229 getArchiveMembers(MBRef)) 230 Files.push_back(make<LazyObjFile>(P.first, Path, P.second)); 231 return; 232 } 233 234 // Handle the regular case. 235 Files.push_back(make<ArchiveFile>(std::move(File))); 236 return; 237 } 238 case file_magic::elf_shared_object: 239 if (Config->Static || Config->Relocatable) { 240 error("attempted static link of dynamic object " + Path); 241 return; 242 } 243 244 // DSOs usually have DT_SONAME tags in their ELF headers, and the 245 // sonames are used to identify DSOs. But if they are missing, 246 // they are identified by filenames. We don't know whether the new 247 // file has a DT_SONAME or not because we haven't parsed it yet. 248 // Here, we set the default soname for the file because we might 249 // need it later. 250 // 251 // If a file was specified by -lfoo, the directory part is not 252 // significant, as a user did not specify it. This behavior is 253 // compatible with GNU. 254 Files.push_back( 255 make<SharedFile>(MBRef, WithLOption ? path::filename(Path) : Path)); 256 return; 257 case file_magic::bitcode: 258 case file_magic::elf_relocatable: 259 if (InLib) 260 Files.push_back(make<LazyObjFile>(MBRef, "", 0)); 261 else 262 Files.push_back(createObjectFile(MBRef)); 263 break; 264 default: 265 error(Path + ": unknown file type"); 266 } 267 } 268 269 // Add a given library by searching it from input search paths. 270 void LinkerDriver::addLibrary(StringRef Name) { 271 if (Optional<std::string> Path = searchLibrary(Name)) 272 addFile(*Path, /*WithLOption=*/true); 273 else 274 error("unable to find library -l" + Name); 275 } 276 277 // This function is called on startup. We need this for LTO since 278 // LTO calls LLVM functions to compile bitcode files to native code. 279 // Technically this can be delayed until we read bitcode files, but 280 // we don't bother to do lazily because the initialization is fast. 281 static void initLLVM() { 282 InitializeAllTargets(); 283 InitializeAllTargetMCs(); 284 InitializeAllAsmPrinters(); 285 InitializeAllAsmParsers(); 286 } 287 288 // Some command line options or some combinations of them are not allowed. 289 // This function checks for such errors. 290 static void checkOptions() { 291 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup 292 // table which is a relatively new feature. 293 if (Config->EMachine == EM_MIPS && Config->GnuHash) 294 error("the .gnu.hash section is not compatible with the MIPS target"); 295 296 if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64) 297 error("--fix-cortex-a53-843419 is only supported on AArch64 targets"); 298 299 if (Config->TocOptimize && Config->EMachine != EM_PPC64) 300 error("--toc-optimize is only supported on the PowerPC64 target"); 301 302 if (Config->Pie && Config->Shared) 303 error("-shared and -pie may not be used together"); 304 305 if (!Config->Shared && !Config->FilterList.empty()) 306 error("-F may not be used without -shared"); 307 308 if (!Config->Shared && !Config->AuxiliaryList.empty()) 309 error("-f may not be used without -shared"); 310 311 if (!Config->Relocatable && !Config->DefineCommon) 312 error("-no-define-common not supported in non relocatable output"); 313 314 if (Config->ZText && Config->ZIfuncNoplt) 315 error("-z text and -z ifunc-noplt may not be used together"); 316 317 if (Config->Relocatable) { 318 if (Config->Shared) 319 error("-r and -shared may not be used together"); 320 if (Config->GcSections) 321 error("-r and --gc-sections may not be used together"); 322 if (Config->GdbIndex) 323 error("-r and --gdb-index may not be used together"); 324 if (Config->ICF != ICFLevel::None) 325 error("-r and --icf may not be used together"); 326 if (Config->Pie) 327 error("-r and -pie may not be used together"); 328 } 329 330 if (Config->ExecuteOnly) { 331 if (Config->EMachine != EM_AARCH64) 332 error("-execute-only is only supported on AArch64 targets"); 333 334 if (Config->SingleRoRx && !Script->HasSectionsCommand) 335 error("-execute-only and -no-rosegment cannot be used together"); 336 } 337 } 338 339 static const char *getReproduceOption(opt::InputArgList &Args) { 340 if (auto *Arg = Args.getLastArg(OPT_reproduce)) 341 return Arg->getValue(); 342 return getenv("LLD_REPRODUCE"); 343 } 344 345 static bool hasZOption(opt::InputArgList &Args, StringRef Key) { 346 for (auto *Arg : Args.filtered(OPT_z)) 347 if (Key == Arg->getValue()) 348 return true; 349 return false; 350 } 351 352 static bool getZFlag(opt::InputArgList &Args, StringRef K1, StringRef K2, 353 bool Default) { 354 for (auto *Arg : Args.filtered_reverse(OPT_z)) { 355 if (K1 == Arg->getValue()) 356 return true; 357 if (K2 == Arg->getValue()) 358 return false; 359 } 360 return Default; 361 } 362 363 static bool isKnownZFlag(StringRef S) { 364 return S == "combreloc" || S == "copyreloc" || S == "defs" || 365 S == "execstack" || S == "global" || S == "hazardplt" || 366 S == "ifunc-noplt" || S == "initfirst" || S == "interpose" || 367 S == "keep-text-section-prefix" || S == "lazy" || S == "muldefs" || 368 S == "nocombreloc" || S == "nocopyreloc" || S == "nodefaultlib" || 369 S == "nodelete" || S == "nodlopen" || S == "noexecstack" || 370 S == "nokeep-text-section-prefix" || S == "norelro" || S == "notext" || 371 S == "now" || S == "origin" || S == "relro" || S == "retpolineplt" || 372 S == "rodynamic" || S == "text" || S == "wxneeded" || 373 S.startswith("common-page-size") || S.startswith("max-page-size=") || 374 S.startswith("stack-size="); 375 } 376 377 // Report an error for an unknown -z option. 378 static void checkZOptions(opt::InputArgList &Args) { 379 for (auto *Arg : Args.filtered(OPT_z)) 380 if (!isKnownZFlag(Arg->getValue())) 381 error("unknown -z value: " + StringRef(Arg->getValue())); 382 } 383 384 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) { 385 ELFOptTable Parser; 386 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1)); 387 388 // Interpret this flag early because error() depends on them. 389 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20); 390 checkZOptions(Args); 391 392 // Handle -help 393 if (Args.hasArg(OPT_help)) { 394 printHelp(); 395 return; 396 } 397 398 // Handle -v or -version. 399 // 400 // A note about "compatible with GNU linkers" message: this is a hack for 401 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and 402 // still the newest version in March 2017) or earlier to recognize LLD as 403 // a GNU compatible linker. As long as an output for the -v option 404 // contains "GNU" or "with BFD", they recognize us as GNU-compatible. 405 // 406 // This is somewhat ugly hack, but in reality, we had no choice other 407 // than doing this. Considering the very long release cycle of Libtool, 408 // it is not easy to improve it to recognize LLD as a GNU compatible 409 // linker in a timely manner. Even if we can make it, there are still a 410 // lot of "configure" scripts out there that are generated by old version 411 // of Libtool. We cannot convince every software developer to migrate to 412 // the latest version and re-generate scripts. So we have this hack. 413 if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version)) 414 message(getLLDVersion() + " (compatible with GNU linkers)"); 415 416 if (const char *Path = getReproduceOption(Args)) { 417 // Note that --reproduce is a debug option so you can ignore it 418 // if you are trying to understand the whole picture of the code. 419 Expected<std::unique_ptr<TarWriter>> ErrOrWriter = 420 TarWriter::create(Path, path::stem(Path)); 421 if (ErrOrWriter) { 422 Tar = std::move(*ErrOrWriter); 423 Tar->append("response.txt", createResponseFile(Args)); 424 Tar->append("version.txt", getLLDVersion() + "\n"); 425 } else { 426 error("--reproduce: " + toString(ErrOrWriter.takeError())); 427 } 428 } 429 430 readConfigs(Args); 431 432 // The behavior of -v or --version is a bit strange, but this is 433 // needed for compatibility with GNU linkers. 434 if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT)) 435 return; 436 if (Args.hasArg(OPT_version)) 437 return; 438 439 initLLVM(); 440 createFiles(Args); 441 if (errorCount()) 442 return; 443 444 inferMachineType(); 445 setConfigs(Args); 446 checkOptions(); 447 if (errorCount()) 448 return; 449 450 // The Target instance handles target-specific stuff, such as applying 451 // relocations or writing a PLT section. It also contains target-dependent 452 // values such as a default image base address. 453 Target = getTarget(); 454 455 switch (Config->EKind) { 456 case ELF32LEKind: 457 link<ELF32LE>(Args); 458 return; 459 case ELF32BEKind: 460 link<ELF32BE>(Args); 461 return; 462 case ELF64LEKind: 463 link<ELF64LE>(Args); 464 return; 465 case ELF64BEKind: 466 link<ELF64BE>(Args); 467 return; 468 default: 469 llvm_unreachable("unknown Config->EKind"); 470 } 471 } 472 473 static std::string getRpath(opt::InputArgList &Args) { 474 std::vector<StringRef> V = args::getStrings(Args, OPT_rpath); 475 return llvm::join(V.begin(), V.end(), ":"); 476 } 477 478 // Determines what we should do if there are remaining unresolved 479 // symbols after the name resolution. 480 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) { 481 UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols, 482 OPT_warn_unresolved_symbols, true) 483 ? UnresolvedPolicy::ReportError 484 : UnresolvedPolicy::Warn; 485 486 // Process the last of -unresolved-symbols, -no-undefined or -z defs. 487 for (auto *Arg : llvm::reverse(Args)) { 488 switch (Arg->getOption().getID()) { 489 case OPT_unresolved_symbols: { 490 StringRef S = Arg->getValue(); 491 if (S == "ignore-all" || S == "ignore-in-object-files") 492 return UnresolvedPolicy::Ignore; 493 if (S == "ignore-in-shared-libs" || S == "report-all") 494 return ErrorOrWarn; 495 error("unknown --unresolved-symbols value: " + S); 496 continue; 497 } 498 case OPT_no_undefined: 499 return ErrorOrWarn; 500 case OPT_z: 501 if (StringRef(Arg->getValue()) == "defs") 502 return ErrorOrWarn; 503 continue; 504 } 505 } 506 507 // -shared implies -unresolved-symbols=ignore-all because missing 508 // symbols are likely to be resolved at runtime using other DSOs. 509 if (Config->Shared) 510 return UnresolvedPolicy::Ignore; 511 return ErrorOrWarn; 512 } 513 514 static Target2Policy getTarget2(opt::InputArgList &Args) { 515 StringRef S = Args.getLastArgValue(OPT_target2, "got-rel"); 516 if (S == "rel") 517 return Target2Policy::Rel; 518 if (S == "abs") 519 return Target2Policy::Abs; 520 if (S == "got-rel") 521 return Target2Policy::GotRel; 522 error("unknown --target2 option: " + S); 523 return Target2Policy::GotRel; 524 } 525 526 static bool isOutputFormatBinary(opt::InputArgList &Args) { 527 StringRef S = Args.getLastArgValue(OPT_oformat, "elf"); 528 if (S == "binary") 529 return true; 530 if (!S.startswith("elf")) 531 error("unknown --oformat value: " + S); 532 return false; 533 } 534 535 static DiscardPolicy getDiscard(opt::InputArgList &Args) { 536 if (Args.hasArg(OPT_relocatable)) 537 return DiscardPolicy::None; 538 539 auto *Arg = 540 Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none); 541 if (!Arg) 542 return DiscardPolicy::Default; 543 if (Arg->getOption().getID() == OPT_discard_all) 544 return DiscardPolicy::All; 545 if (Arg->getOption().getID() == OPT_discard_locals) 546 return DiscardPolicy::Locals; 547 return DiscardPolicy::None; 548 } 549 550 static StringRef getDynamicLinker(opt::InputArgList &Args) { 551 auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); 552 if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker) 553 return ""; 554 return Arg->getValue(); 555 } 556 557 static ICFLevel getICF(opt::InputArgList &Args) { 558 auto *Arg = Args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all); 559 if (!Arg || Arg->getOption().getID() == OPT_icf_none) 560 return ICFLevel::None; 561 if (Arg->getOption().getID() == OPT_icf_safe) 562 return ICFLevel::Safe; 563 return ICFLevel::All; 564 } 565 566 static StripPolicy getStrip(opt::InputArgList &Args) { 567 if (Args.hasArg(OPT_relocatable)) 568 return StripPolicy::None; 569 570 auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug); 571 if (!Arg) 572 return StripPolicy::None; 573 if (Arg->getOption().getID() == OPT_strip_all) 574 return StripPolicy::All; 575 return StripPolicy::Debug; 576 } 577 578 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) { 579 uint64_t VA = 0; 580 if (S.startswith("0x")) 581 S = S.drop_front(2); 582 if (!to_integer(S, VA, 16)) 583 error("invalid argument: " + toString(Arg)); 584 return VA; 585 } 586 587 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) { 588 StringMap<uint64_t> Ret; 589 for (auto *Arg : Args.filtered(OPT_section_start)) { 590 StringRef Name; 591 StringRef Addr; 592 std::tie(Name, Addr) = StringRef(Arg->getValue()).split('='); 593 Ret[Name] = parseSectionAddress(Addr, *Arg); 594 } 595 596 if (auto *Arg = Args.getLastArg(OPT_Ttext)) 597 Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg); 598 if (auto *Arg = Args.getLastArg(OPT_Tdata)) 599 Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg); 600 if (auto *Arg = Args.getLastArg(OPT_Tbss)) 601 Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg); 602 return Ret; 603 } 604 605 static SortSectionPolicy getSortSection(opt::InputArgList &Args) { 606 StringRef S = Args.getLastArgValue(OPT_sort_section); 607 if (S == "alignment") 608 return SortSectionPolicy::Alignment; 609 if (S == "name") 610 return SortSectionPolicy::Name; 611 if (!S.empty()) 612 error("unknown --sort-section rule: " + S); 613 return SortSectionPolicy::Default; 614 } 615 616 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) { 617 StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place"); 618 if (S == "warn") 619 return OrphanHandlingPolicy::Warn; 620 if (S == "error") 621 return OrphanHandlingPolicy::Error; 622 if (S != "place") 623 error("unknown --orphan-handling mode: " + S); 624 return OrphanHandlingPolicy::Place; 625 } 626 627 // Parse --build-id or --build-id=<style>. We handle "tree" as a 628 // synonym for "sha1" because all our hash functions including 629 // -build-id=sha1 are actually tree hashes for performance reasons. 630 static std::pair<BuildIdKind, std::vector<uint8_t>> 631 getBuildId(opt::InputArgList &Args) { 632 auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq); 633 if (!Arg) 634 return {BuildIdKind::None, {}}; 635 636 if (Arg->getOption().getID() == OPT_build_id) 637 return {BuildIdKind::Fast, {}}; 638 639 StringRef S = Arg->getValue(); 640 if (S == "fast") 641 return {BuildIdKind::Fast, {}}; 642 if (S == "md5") 643 return {BuildIdKind::Md5, {}}; 644 if (S == "sha1" || S == "tree") 645 return {BuildIdKind::Sha1, {}}; 646 if (S == "uuid") 647 return {BuildIdKind::Uuid, {}}; 648 if (S.startswith("0x")) 649 return {BuildIdKind::Hexstring, parseHex(S.substr(2))}; 650 651 if (S != "none") 652 error("unknown --build-id style: " + S); 653 return {BuildIdKind::None, {}}; 654 } 655 656 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &Args) { 657 StringRef S = Args.getLastArgValue(OPT_pack_dyn_relocs, "none"); 658 if (S == "android") 659 return {true, false}; 660 if (S == "relr") 661 return {false, true}; 662 if (S == "android+relr") 663 return {true, true}; 664 665 if (S != "none") 666 error("unknown -pack-dyn-relocs format: " + S); 667 return {false, false}; 668 } 669 670 static void readCallGraph(MemoryBufferRef MB) { 671 // Build a map from symbol name to section 672 DenseMap<StringRef, Symbol *> Map; 673 for (InputFile *File : ObjectFiles) 674 for (Symbol *Sym : File->getSymbols()) 675 Map[Sym->getName()] = Sym; 676 677 auto FindSection = [&](StringRef Name) -> InputSectionBase * { 678 Symbol *Sym = Map.lookup(Name); 679 if (!Sym) { 680 if (Config->WarnSymbolOrdering) 681 warn(MB.getBufferIdentifier() + ": no such symbol: " + Name); 682 return nullptr; 683 } 684 maybeWarnUnorderableSymbol(Sym); 685 686 if (Defined *DR = dyn_cast_or_null<Defined>(Sym)) 687 return dyn_cast_or_null<InputSectionBase>(DR->Section); 688 return nullptr; 689 }; 690 691 for (StringRef Line : args::getLines(MB)) { 692 SmallVector<StringRef, 3> Fields; 693 Line.split(Fields, ' '); 694 uint64_t Count; 695 696 if (Fields.size() != 3 || !to_integer(Fields[2], Count)) { 697 error(MB.getBufferIdentifier() + ": parse error"); 698 return; 699 } 700 701 if (InputSectionBase *From = FindSection(Fields[0])) 702 if (InputSectionBase *To = FindSection(Fields[1])) 703 Config->CallGraphProfile[std::make_pair(From, To)] += Count; 704 } 705 } 706 707 template <class ELFT> static void readCallGraphsFromObjectFiles() { 708 for (auto File : ObjectFiles) { 709 auto *Obj = cast<ObjFile<ELFT>>(File); 710 711 for (const Elf_CGProfile_Impl<ELFT> &CGPE : Obj->CGProfile) { 712 auto *FromSym = dyn_cast<Defined>(&Obj->getSymbol(CGPE.cgp_from)); 713 auto *ToSym = dyn_cast<Defined>(&Obj->getSymbol(CGPE.cgp_to)); 714 if (!FromSym || !ToSym) 715 continue; 716 717 auto *From = dyn_cast_or_null<InputSectionBase>(FromSym->Section); 718 auto *To = dyn_cast_or_null<InputSectionBase>(ToSym->Section); 719 if (From && To) 720 Config->CallGraphProfile[{From, To}] += CGPE.cgp_weight; 721 } 722 } 723 } 724 725 static bool getCompressDebugSections(opt::InputArgList &Args) { 726 StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none"); 727 if (S == "none") 728 return false; 729 if (S != "zlib") 730 error("unknown --compress-debug-sections value: " + S); 731 if (!zlib::isAvailable()) 732 error("--compress-debug-sections: zlib is not available"); 733 return true; 734 } 735 736 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &Args, 737 unsigned Id) { 738 auto *Arg = Args.getLastArg(Id); 739 if (!Arg) 740 return {"", ""}; 741 742 StringRef S = Arg->getValue(); 743 std::pair<StringRef, StringRef> Ret = S.split(';'); 744 if (Ret.second.empty()) 745 error(Arg->getSpelling() + " expects 'old;new' format, but got " + S); 746 return Ret; 747 } 748 749 // Parse the symbol ordering file and warn for any duplicate entries. 750 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef MB) { 751 SetVector<StringRef> Names; 752 for (StringRef S : args::getLines(MB)) 753 if (!Names.insert(S) && Config->WarnSymbolOrdering) 754 warn(MB.getBufferIdentifier() + ": duplicate ordered symbol: " + S); 755 756 return Names.takeVector(); 757 } 758 759 static void parseClangOption(StringRef Opt, const Twine &Msg) { 760 std::string Err; 761 raw_string_ostream OS(Err); 762 763 const char *Argv[] = {Config->ProgName.data(), Opt.data()}; 764 if (cl::ParseCommandLineOptions(2, Argv, "", &OS)) 765 return; 766 OS.flush(); 767 error(Msg + ": " + StringRef(Err).trim()); 768 } 769 770 // Initializes Config members by the command line options. 771 static void readConfigs(opt::InputArgList &Args) { 772 errorHandler().Verbose = Args.hasArg(OPT_verbose); 773 errorHandler().FatalWarnings = 774 Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false); 775 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true); 776 777 Config->AllowMultipleDefinition = 778 Args.hasFlag(OPT_allow_multiple_definition, 779 OPT_no_allow_multiple_definition, false) || 780 hasZOption(Args, "muldefs"); 781 Config->AllowShlibUndefined = 782 Args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined, 783 Args.hasArg(OPT_shared)); 784 Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary); 785 Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic); 786 Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions); 787 Config->CheckSections = 788 Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true); 789 Config->Chroot = Args.getLastArgValue(OPT_chroot); 790 Config->CompressDebugSections = getCompressDebugSections(Args); 791 Config->Cref = Args.hasFlag(OPT_cref, OPT_no_cref, false); 792 Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common, 793 !Args.hasArg(OPT_relocatable)); 794 Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true); 795 Config->DependentLibraries = Args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true); 796 Config->DisableVerify = Args.hasArg(OPT_disable_verify); 797 Config->Discard = getDiscard(Args); 798 Config->DwoDir = Args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq); 799 Config->DynamicLinker = getDynamicLinker(Args); 800 Config->EhFrameHdr = 801 Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false); 802 Config->EmitLLVM = Args.hasArg(OPT_plugin_opt_emit_llvm, false); 803 Config->EmitRelocs = Args.hasArg(OPT_emit_relocs); 804 Config->CallGraphProfileSort = Args.hasFlag( 805 OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true); 806 Config->EnableNewDtags = 807 Args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true); 808 Config->Entry = Args.getLastArgValue(OPT_entry); 809 Config->ExecuteOnly = 810 Args.hasFlag(OPT_execute_only, OPT_no_execute_only, false); 811 Config->ExportDynamic = 812 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 813 Config->FilterList = args::getStrings(Args, OPT_filter); 814 Config->Fini = Args.getLastArgValue(OPT_fini, "_fini"); 815 Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419); 816 Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false); 817 Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true); 818 Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false); 819 Config->ICF = getICF(Args); 820 Config->IgnoreDataAddressEquality = 821 Args.hasArg(OPT_ignore_data_address_equality); 822 Config->IgnoreFunctionAddressEquality = 823 Args.hasArg(OPT_ignore_function_address_equality); 824 Config->Init = Args.getLastArgValue(OPT_init, "_init"); 825 Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline); 826 Config->LTOCSProfileGenerate = Args.hasArg(OPT_lto_cs_profile_generate); 827 Config->LTOCSProfileFile = Args.getLastArgValue(OPT_lto_cs_profile_file); 828 Config->LTODebugPassManager = Args.hasArg(OPT_lto_debug_pass_manager); 829 Config->LTONewPassManager = Args.hasArg(OPT_lto_new_pass_manager); 830 Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes); 831 Config->LTOO = args::getInteger(Args, OPT_lto_O, 2); 832 Config->LTOObjPath = Args.getLastArgValue(OPT_plugin_opt_obj_path_eq); 833 Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1); 834 Config->LTOSampleProfile = Args.getLastArgValue(OPT_lto_sample_profile); 835 Config->MapFile = Args.getLastArgValue(OPT_Map); 836 Config->MipsGotSize = args::getInteger(Args, OPT_mips_got_size, 0xfff0); 837 Config->MergeArmExidx = 838 Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true); 839 Config->Nmagic = Args.hasFlag(OPT_nmagic, OPT_no_nmagic, false); 840 Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec); 841 Config->Nostdlib = Args.hasArg(OPT_nostdlib); 842 Config->OFormatBinary = isOutputFormatBinary(Args); 843 Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false); 844 Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename); 845 Config->OptRemarksPasses = Args.getLastArgValue(OPT_opt_remarks_passes); 846 Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness); 847 Config->Optimize = args::getInteger(Args, OPT_O, 1); 848 Config->OrphanHandling = getOrphanHandling(Args); 849 Config->OutputFile = Args.getLastArgValue(OPT_o); 850 Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false); 851 Config->PrintIcfSections = 852 Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false); 853 Config->PrintGcSections = 854 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false); 855 Config->PrintSymbolOrder = 856 Args.getLastArgValue(OPT_print_symbol_order); 857 Config->Rpath = getRpath(Args); 858 Config->Relocatable = Args.hasArg(OPT_relocatable); 859 Config->SaveTemps = Args.hasArg(OPT_save_temps); 860 Config->SearchPaths = args::getStrings(Args, OPT_library_path); 861 Config->SectionStartMap = getSectionStartMap(Args); 862 Config->Shared = Args.hasArg(OPT_shared); 863 Config->SingleRoRx = Args.hasArg(OPT_no_rosegment); 864 Config->SoName = Args.getLastArgValue(OPT_soname); 865 Config->SortSection = getSortSection(Args); 866 Config->SplitStackAdjustSize = args::getInteger(Args, OPT_split_stack_adjust_size, 16384); 867 Config->Strip = getStrip(Args); 868 Config->Sysroot = Args.getLastArgValue(OPT_sysroot); 869 Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false); 870 Config->Target2 = getTarget2(Args); 871 Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir); 872 Config->ThinLTOCachePolicy = CHECK( 873 parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)), 874 "--thinlto-cache-policy: invalid cache policy"); 875 Config->ThinLTOEmitImportsFiles = 876 Args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files); 877 Config->ThinLTOIndexOnly = Args.hasArg(OPT_plugin_opt_thinlto_index_only) || 878 Args.hasArg(OPT_plugin_opt_thinlto_index_only_eq); 879 Config->ThinLTOIndexOnlyArg = 880 Args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq); 881 Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u); 882 Config->ThinLTOObjectSuffixReplace = 883 getOldNewOptions(Args, OPT_plugin_opt_thinlto_object_suffix_replace_eq); 884 Config->ThinLTOPrefixReplace = 885 getOldNewOptions(Args, OPT_plugin_opt_thinlto_prefix_replace_eq); 886 Config->Trace = Args.hasArg(OPT_trace); 887 Config->Undefined = args::getStrings(Args, OPT_undefined); 888 Config->UndefinedVersion = 889 Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true); 890 Config->UseAndroidRelrTags = Args.hasFlag( 891 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false); 892 Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args); 893 Config->WarnBackrefs = 894 Args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false); 895 Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false); 896 Config->WarnIfuncTextrel = 897 Args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false); 898 Config->WarnSymbolOrdering = 899 Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true); 900 Config->ZCombreloc = getZFlag(Args, "combreloc", "nocombreloc", true); 901 Config->ZCopyreloc = getZFlag(Args, "copyreloc", "nocopyreloc", true); 902 Config->ZExecstack = getZFlag(Args, "execstack", "noexecstack", false); 903 Config->ZGlobal = hasZOption(Args, "global"); 904 Config->ZHazardplt = hasZOption(Args, "hazardplt"); 905 Config->ZIfuncNoplt = hasZOption(Args, "ifunc-noplt"); 906 Config->ZInitfirst = hasZOption(Args, "initfirst"); 907 Config->ZInterpose = hasZOption(Args, "interpose"); 908 Config->ZKeepTextSectionPrefix = getZFlag( 909 Args, "keep-text-section-prefix", "nokeep-text-section-prefix", false); 910 Config->ZNodefaultlib = hasZOption(Args, "nodefaultlib"); 911 Config->ZNodelete = hasZOption(Args, "nodelete"); 912 Config->ZNodlopen = hasZOption(Args, "nodlopen"); 913 Config->ZNow = getZFlag(Args, "now", "lazy", false); 914 Config->ZOrigin = hasZOption(Args, "origin"); 915 Config->ZRelro = getZFlag(Args, "relro", "norelro", true); 916 Config->ZRetpolineplt = hasZOption(Args, "retpolineplt"); 917 Config->ZRodynamic = hasZOption(Args, "rodynamic"); 918 Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0); 919 Config->ZText = getZFlag(Args, "text", "notext", true); 920 Config->ZWxneeded = hasZOption(Args, "wxneeded"); 921 922 // Parse LTO options. 923 if (auto *Arg = Args.getLastArg(OPT_plugin_opt_mcpu_eq)) 924 parseClangOption(Saver.save("-mcpu=" + StringRef(Arg->getValue())), 925 Arg->getSpelling()); 926 927 for (auto *Arg : Args.filtered(OPT_plugin_opt)) 928 parseClangOption(Arg->getValue(), Arg->getSpelling()); 929 930 // Parse -mllvm options. 931 for (auto *Arg : Args.filtered(OPT_mllvm)) 932 parseClangOption(Arg->getValue(), Arg->getSpelling()); 933 934 if (Config->LTOO > 3) 935 error("invalid optimization level for LTO: " + Twine(Config->LTOO)); 936 if (Config->LTOPartitions == 0) 937 error("--lto-partitions: number of threads must be > 0"); 938 if (Config->ThinLTOJobs == 0) 939 error("--thinlto-jobs: number of threads must be > 0"); 940 941 if (Config->SplitStackAdjustSize < 0) 942 error("--split-stack-adjust-size: size must be >= 0"); 943 944 // Parse ELF{32,64}{LE,BE} and CPU type. 945 if (auto *Arg = Args.getLastArg(OPT_m)) { 946 StringRef S = Arg->getValue(); 947 std::tie(Config->EKind, Config->EMachine, Config->OSABI) = 948 parseEmulation(S); 949 Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32"); 950 Config->Emulation = S; 951 } 952 953 // Parse -hash-style={sysv,gnu,both}. 954 if (auto *Arg = Args.getLastArg(OPT_hash_style)) { 955 StringRef S = Arg->getValue(); 956 if (S == "sysv") 957 Config->SysvHash = true; 958 else if (S == "gnu") 959 Config->GnuHash = true; 960 else if (S == "both") 961 Config->SysvHash = Config->GnuHash = true; 962 else 963 error("unknown -hash-style: " + S); 964 } 965 966 if (Args.hasArg(OPT_print_map)) 967 Config->MapFile = "-"; 968 969 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic). 970 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled 971 // it. 972 if (Config->Nmagic || Config->Omagic) 973 Config->ZRelro = false; 974 975 std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args); 976 977 std::tie(Config->AndroidPackDynRelocs, Config->RelrPackDynRelocs) = 978 getPackDynRelocs(Args); 979 980 if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file)){ 981 if (Args.hasArg(OPT_call_graph_ordering_file)) 982 error("--symbol-ordering-file and --call-graph-order-file " 983 "may not be used together"); 984 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())){ 985 Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer); 986 // Also need to disable CallGraphProfileSort to prevent 987 // LLD order symbols with CGProfile 988 Config->CallGraphProfileSort = false; 989 } 990 } 991 992 // If --retain-symbol-file is used, we'll keep only the symbols listed in 993 // the file and discard all others. 994 if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) { 995 Config->DefaultSymbolVersion = VER_NDX_LOCAL; 996 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 997 for (StringRef S : args::getLines(*Buffer)) 998 Config->VersionScriptGlobals.push_back( 999 {S, /*IsExternCpp*/ false, /*HasWildcard*/ false}); 1000 } 1001 1002 bool HasExportDynamic = 1003 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false); 1004 1005 // Parses -dynamic-list and -export-dynamic-symbol. They make some 1006 // symbols private. Note that -export-dynamic takes precedence over them 1007 // as it says all symbols should be exported. 1008 if (!HasExportDynamic) { 1009 for (auto *Arg : Args.filtered(OPT_dynamic_list)) 1010 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 1011 readDynamicList(*Buffer); 1012 1013 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol)) 1014 Config->DynamicList.push_back( 1015 {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false}); 1016 } 1017 1018 // If --export-dynamic-symbol=foo is given and symbol foo is defined in 1019 // an object file in an archive file, that object file should be pulled 1020 // out and linked. (It doesn't have to behave like that from technical 1021 // point of view, but this is needed for compatibility with GNU.) 1022 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol)) 1023 Config->Undefined.push_back(Arg->getValue()); 1024 1025 for (auto *Arg : Args.filtered(OPT_version_script)) 1026 if (Optional<std::string> Path = searchScript(Arg->getValue())) { 1027 if (Optional<MemoryBufferRef> Buffer = readFile(*Path)) 1028 readVersionScript(*Buffer); 1029 } else { 1030 error(Twine("cannot find version script ") + Arg->getValue()); 1031 } 1032 } 1033 1034 // Some Config members do not directly correspond to any particular 1035 // command line options, but computed based on other Config values. 1036 // This function initialize such members. See Config.h for the details 1037 // of these values. 1038 static void setConfigs(opt::InputArgList &Args) { 1039 ELFKind K = Config->EKind; 1040 uint16_t M = Config->EMachine; 1041 1042 Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs); 1043 Config->Is64 = (K == ELF64LEKind || K == ELF64BEKind); 1044 Config->IsLE = (K == ELF32LEKind || K == ELF64LEKind); 1045 Config->Endianness = Config->IsLE ? endianness::little : endianness::big; 1046 Config->IsMips64EL = (K == ELF64LEKind && M == EM_MIPS); 1047 Config->Pic = Config->Pie || Config->Shared; 1048 Config->PicThunk = Args.hasArg(OPT_pic_veneer, Config->Pic); 1049 Config->Wordsize = Config->Is64 ? 8 : 4; 1050 1051 // ELF defines two different ways to store relocation addends as shown below: 1052 // 1053 // Rel: Addends are stored to the location where relocations are applied. 1054 // Rela: Addends are stored as part of relocation entry. 1055 // 1056 // In other words, Rela makes it easy to read addends at the price of extra 1057 // 4 or 8 byte for each relocation entry. We don't know why ELF defined two 1058 // different mechanisms in the first place, but this is how the spec is 1059 // defined. 1060 // 1061 // You cannot choose which one, Rel or Rela, you want to use. Instead each 1062 // ABI defines which one you need to use. The following expression expresses 1063 // that. 1064 Config->IsRela = M == EM_AARCH64 || M == EM_AMDGPU || M == EM_HEXAGON || 1065 M == EM_PPC || M == EM_PPC64 || M == EM_RISCV || 1066 M == EM_X86_64; 1067 1068 // If the output uses REL relocations we must store the dynamic relocation 1069 // addends to the output sections. We also store addends for RELA relocations 1070 // if --apply-dynamic-relocs is used. 1071 // We default to not writing the addends when using RELA relocations since 1072 // any standard conforming tool can find it in r_addend. 1073 Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs, 1074 OPT_no_apply_dynamic_relocs, false) || 1075 !Config->IsRela; 1076 1077 Config->TocOptimize = 1078 Args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, M == EM_PPC64); 1079 } 1080 1081 // Returns a value of "-format" option. 1082 static bool isFormatBinary(StringRef S) { 1083 if (S == "binary") 1084 return true; 1085 if (S == "elf" || S == "default") 1086 return false; 1087 error("unknown -format value: " + S + 1088 " (supported formats: elf, default, binary)"); 1089 return false; 1090 } 1091 1092 void LinkerDriver::createFiles(opt::InputArgList &Args) { 1093 // For --{push,pop}-state. 1094 std::vector<std::tuple<bool, bool, bool>> Stack; 1095 1096 // Iterate over argv to process input files and positional arguments. 1097 for (auto *Arg : Args) { 1098 switch (Arg->getOption().getUnaliasedOption().getID()) { 1099 case OPT_library: 1100 addLibrary(Arg->getValue()); 1101 break; 1102 case OPT_INPUT: 1103 addFile(Arg->getValue(), /*WithLOption=*/false); 1104 break; 1105 case OPT_defsym: { 1106 StringRef From; 1107 StringRef To; 1108 std::tie(From, To) = StringRef(Arg->getValue()).split('='); 1109 if (From.empty() || To.empty()) 1110 error("-defsym: syntax error: " + StringRef(Arg->getValue())); 1111 else 1112 readDefsym(From, MemoryBufferRef(To, "-defsym")); 1113 break; 1114 } 1115 case OPT_script: 1116 if (Optional<std::string> Path = searchScript(Arg->getValue())) { 1117 if (Optional<MemoryBufferRef> MB = readFile(*Path)) 1118 readLinkerScript(*MB); 1119 break; 1120 } 1121 error(Twine("cannot find linker script ") + Arg->getValue()); 1122 break; 1123 case OPT_as_needed: 1124 Config->AsNeeded = true; 1125 break; 1126 case OPT_format: 1127 Config->FormatBinary = isFormatBinary(Arg->getValue()); 1128 break; 1129 case OPT_no_as_needed: 1130 Config->AsNeeded = false; 1131 break; 1132 case OPT_Bstatic: 1133 case OPT_omagic: 1134 case OPT_nmagic: 1135 Config->Static = true; 1136 break; 1137 case OPT_Bdynamic: 1138 Config->Static = false; 1139 break; 1140 case OPT_whole_archive: 1141 InWholeArchive = true; 1142 break; 1143 case OPT_no_whole_archive: 1144 InWholeArchive = false; 1145 break; 1146 case OPT_just_symbols: 1147 if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue())) { 1148 Files.push_back(createObjectFile(*MB)); 1149 Files.back()->JustSymbols = true; 1150 } 1151 break; 1152 case OPT_start_group: 1153 if (InputFile::IsInGroup) 1154 error("nested --start-group"); 1155 InputFile::IsInGroup = true; 1156 break; 1157 case OPT_end_group: 1158 if (!InputFile::IsInGroup) 1159 error("stray --end-group"); 1160 InputFile::IsInGroup = false; 1161 ++InputFile::NextGroupId; 1162 break; 1163 case OPT_start_lib: 1164 if (InLib) 1165 error("nested --start-lib"); 1166 if (InputFile::IsInGroup) 1167 error("may not nest --start-lib in --start-group"); 1168 InLib = true; 1169 InputFile::IsInGroup = true; 1170 break; 1171 case OPT_end_lib: 1172 if (!InLib) 1173 error("stray --end-lib"); 1174 InLib = false; 1175 InputFile::IsInGroup = false; 1176 ++InputFile::NextGroupId; 1177 break; 1178 case OPT_push_state: 1179 Stack.emplace_back(Config->AsNeeded, Config->Static, InWholeArchive); 1180 break; 1181 case OPT_pop_state: 1182 if (Stack.empty()) { 1183 error("unbalanced --push-state/--pop-state"); 1184 break; 1185 } 1186 std::tie(Config->AsNeeded, Config->Static, InWholeArchive) = Stack.back(); 1187 Stack.pop_back(); 1188 break; 1189 } 1190 } 1191 1192 if (Files.empty() && errorCount() == 0) 1193 error("no input files"); 1194 } 1195 1196 // If -m <machine_type> was not given, infer it from object files. 1197 void LinkerDriver::inferMachineType() { 1198 if (Config->EKind != ELFNoneKind) 1199 return; 1200 1201 for (InputFile *F : Files) { 1202 if (F->EKind == ELFNoneKind) 1203 continue; 1204 Config->EKind = F->EKind; 1205 Config->EMachine = F->EMachine; 1206 Config->OSABI = F->OSABI; 1207 Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F); 1208 return; 1209 } 1210 error("target emulation unknown: -m or at least one .o file required"); 1211 } 1212 1213 // Parse -z max-page-size=<value>. The default value is defined by 1214 // each target. 1215 static uint64_t getMaxPageSize(opt::InputArgList &Args) { 1216 uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size", 1217 Target->DefaultMaxPageSize); 1218 if (!isPowerOf2_64(Val)) 1219 error("max-page-size: value isn't a power of 2"); 1220 if (Config->Nmagic || Config->Omagic) { 1221 if (Val != Target->DefaultMaxPageSize) 1222 warn("-z max-page-size set, but paging disabled by omagic or nmagic"); 1223 return 1; 1224 } 1225 return Val; 1226 } 1227 1228 // Parse -z common-page-size=<value>. The default value is defined by 1229 // each target. 1230 static uint64_t getCommonPageSize(opt::InputArgList &Args) { 1231 uint64_t Val = args::getZOptionValue(Args, OPT_z, "common-page-size", 1232 Target->DefaultCommonPageSize); 1233 if (!isPowerOf2_64(Val)) 1234 error("common-page-size: value isn't a power of 2"); 1235 if (Config->Nmagic || Config->Omagic) { 1236 if (Val != Target->DefaultCommonPageSize) 1237 warn("-z common-page-size set, but paging disabled by omagic or nmagic"); 1238 return 1; 1239 } 1240 // CommonPageSize can't be larger than MaxPageSize. 1241 if (Val > Config->MaxPageSize) 1242 Val = Config->MaxPageSize; 1243 return Val; 1244 } 1245 1246 // Parses -image-base option. 1247 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) { 1248 // Because we are using "Config->MaxPageSize" here, this function has to be 1249 // called after the variable is initialized. 1250 auto *Arg = Args.getLastArg(OPT_image_base); 1251 if (!Arg) 1252 return None; 1253 1254 StringRef S = Arg->getValue(); 1255 uint64_t V; 1256 if (!to_integer(S, V)) { 1257 error("-image-base: number expected, but got " + S); 1258 return 0; 1259 } 1260 if ((V % Config->MaxPageSize) != 0) 1261 warn("-image-base: address isn't multiple of page size: " + S); 1262 return V; 1263 } 1264 1265 // Parses `--exclude-libs=lib,lib,...`. 1266 // The library names may be delimited by commas or colons. 1267 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) { 1268 DenseSet<StringRef> Ret; 1269 for (auto *Arg : Args.filtered(OPT_exclude_libs)) { 1270 StringRef S = Arg->getValue(); 1271 for (;;) { 1272 size_t Pos = S.find_first_of(",:"); 1273 if (Pos == StringRef::npos) 1274 break; 1275 Ret.insert(S.substr(0, Pos)); 1276 S = S.substr(Pos + 1); 1277 } 1278 Ret.insert(S); 1279 } 1280 return Ret; 1281 } 1282 1283 // Handles the -exclude-libs option. If a static library file is specified 1284 // by the -exclude-libs option, all public symbols from the archive become 1285 // private unless otherwise specified by version scripts or something. 1286 // A special library name "ALL" means all archive files. 1287 // 1288 // This is not a popular option, but some programs such as bionic libc use it. 1289 static void excludeLibs(opt::InputArgList &Args) { 1290 DenseSet<StringRef> Libs = getExcludeLibs(Args); 1291 bool All = Libs.count("ALL"); 1292 1293 auto Visit = [&](InputFile *File) { 1294 if (!File->ArchiveName.empty()) 1295 if (All || Libs.count(path::filename(File->ArchiveName))) 1296 for (Symbol *Sym : File->getSymbols()) 1297 if (!Sym->isLocal() && Sym->File == File) 1298 Sym->VersionId = VER_NDX_LOCAL; 1299 }; 1300 1301 for (InputFile *File : ObjectFiles) 1302 Visit(File); 1303 1304 for (BitcodeFile *File : BitcodeFiles) 1305 Visit(File); 1306 } 1307 1308 // Force Sym to be entered in the output. Used for -u or equivalent. 1309 static void handleUndefined(StringRef Name) { 1310 Symbol *Sym = Symtab->find(Name); 1311 if (!Sym) 1312 return; 1313 1314 // Since symbol S may not be used inside the program, LTO may 1315 // eliminate it. Mark the symbol as "used" to prevent it. 1316 Sym->IsUsedInRegularObj = true; 1317 1318 if (Sym->isLazy()) 1319 Sym->fetch(); 1320 } 1321 1322 static void handleLibcall(StringRef Name) { 1323 Symbol *Sym = Symtab->find(Name); 1324 if (!Sym || !Sym->isLazy()) 1325 return; 1326 1327 MemoryBufferRef MB; 1328 if (auto *LO = dyn_cast<LazyObject>(Sym)) 1329 MB = LO->File->MB; 1330 else 1331 MB = cast<LazyArchive>(Sym)->getMemberBuffer(); 1332 1333 if (isBitcode(MB)) 1334 Sym->fetch(); 1335 } 1336 1337 // Replaces common symbols with defined symbols reside in .bss sections. 1338 // This function is called after all symbol names are resolved. As a 1339 // result, the passes after the symbol resolution won't see any 1340 // symbols of type CommonSymbol. 1341 static void replaceCommonSymbols() { 1342 Symtab->forEachSymbol([](Symbol *Sym) { 1343 auto *S = dyn_cast<CommonSymbol>(Sym); 1344 if (!S) 1345 return; 1346 1347 auto *Bss = make<BssSection>("COMMON", S->Size, S->Alignment); 1348 Bss->File = S->File; 1349 Bss->markDead(); 1350 InputSections.push_back(Bss); 1351 S->replace(Defined{S->File, S->getName(), S->Binding, S->StOther, S->Type, 1352 /*Value=*/0, S->Size, Bss}); 1353 }); 1354 } 1355 1356 // If all references to a DSO happen to be weak, the DSO is not added 1357 // to DT_NEEDED. If that happens, we need to eliminate shared symbols 1358 // created from the DSO. Otherwise, they become dangling references 1359 // that point to a non-existent DSO. 1360 static void demoteSharedSymbols() { 1361 Symtab->forEachSymbol([](Symbol *Sym) { 1362 auto *S = dyn_cast<SharedSymbol>(Sym); 1363 if (!S || S->getFile().IsNeeded) 1364 return; 1365 1366 bool Used = S->Used; 1367 S->replace(Undefined{nullptr, S->getName(), STB_WEAK, S->StOther, S->Type}); 1368 S->Used = Used; 1369 }); 1370 } 1371 1372 // The section referred to by S is considered address-significant. Set the 1373 // KeepUnique flag on the section if appropriate. 1374 static void markAddrsig(Symbol *S) { 1375 if (auto *D = dyn_cast_or_null<Defined>(S)) 1376 if (D->Section) 1377 // We don't need to keep text sections unique under --icf=all even if they 1378 // are address-significant. 1379 if (Config->ICF == ICFLevel::Safe || !(D->Section->Flags & SHF_EXECINSTR)) 1380 D->Section->KeepUnique = true; 1381 } 1382 1383 // Record sections that define symbols mentioned in --keep-unique <symbol> 1384 // and symbols referred to by address-significance tables. These sections are 1385 // ineligible for ICF. 1386 template <class ELFT> 1387 static void findKeepUniqueSections(opt::InputArgList &Args) { 1388 for (auto *Arg : Args.filtered(OPT_keep_unique)) { 1389 StringRef Name = Arg->getValue(); 1390 auto *D = dyn_cast_or_null<Defined>(Symtab->find(Name)); 1391 if (!D || !D->Section) { 1392 warn("could not find symbol " + Name + " to keep unique"); 1393 continue; 1394 } 1395 D->Section->KeepUnique = true; 1396 } 1397 1398 // --icf=all --ignore-data-address-equality means that we can ignore 1399 // the dynsym and address-significance tables entirely. 1400 if (Config->ICF == ICFLevel::All && Config->IgnoreDataAddressEquality) 1401 return; 1402 1403 // Symbols in the dynsym could be address-significant in other executables 1404 // or DSOs, so we conservatively mark them as address-significant. 1405 Symtab->forEachSymbol([&](Symbol *Sym) { 1406 if (Sym->includeInDynsym()) 1407 markAddrsig(Sym); 1408 }); 1409 1410 // Visit the address-significance table in each object file and mark each 1411 // referenced symbol as address-significant. 1412 for (InputFile *F : ObjectFiles) { 1413 auto *Obj = cast<ObjFile<ELFT>>(F); 1414 ArrayRef<Symbol *> Syms = Obj->getSymbols(); 1415 if (Obj->AddrsigSec) { 1416 ArrayRef<uint8_t> Contents = 1417 check(Obj->getObj().getSectionContents(Obj->AddrsigSec)); 1418 const uint8_t *Cur = Contents.begin(); 1419 while (Cur != Contents.end()) { 1420 unsigned Size; 1421 const char *Err; 1422 uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err); 1423 if (Err) 1424 fatal(toString(F) + ": could not decode addrsig section: " + Err); 1425 markAddrsig(Syms[SymIndex]); 1426 Cur += Size; 1427 } 1428 } else { 1429 // If an object file does not have an address-significance table, 1430 // conservatively mark all of its symbols as address-significant. 1431 for (Symbol *S : Syms) 1432 markAddrsig(S); 1433 } 1434 } 1435 } 1436 1437 // This function reads a symbol partition specification section. These sections 1438 // are used to control which partition a symbol is allocated to. See 1439 // https://lld.llvm.org/Partitions.html for more details on partitions. 1440 template <typename ELFT> 1441 static void readSymbolPartitionSection(InputSectionBase *S) { 1442 // Read the relocation that refers to the partition's entry point symbol. 1443 Symbol *Sym; 1444 if (S->AreRelocsRela) 1445 Sym = &S->getFile<ELFT>()->getRelocTargetSym(S->template relas<ELFT>()[0]); 1446 else 1447 Sym = &S->getFile<ELFT>()->getRelocTargetSym(S->template rels<ELFT>()[0]); 1448 if (!isa<Defined>(Sym) || !Sym->includeInDynsym()) 1449 return; 1450 1451 StringRef PartName = reinterpret_cast<const char *>(S->data().data()); 1452 for (Partition &Part : Partitions) { 1453 if (Part.Name == PartName) { 1454 Sym->Partition = Part.getNumber(); 1455 return; 1456 } 1457 } 1458 1459 // Forbid partitions from being used on incompatible targets, and forbid them 1460 // from being used together with various linker features that assume a single 1461 // set of output sections. 1462 if (Script->HasSectionsCommand) 1463 error(toString(S->File) + 1464 ": partitions cannot be used with the SECTIONS command"); 1465 if (Script->hasPhdrsCommands()) 1466 error(toString(S->File) + 1467 ": partitions cannot be used with the PHDRS command"); 1468 if (!Config->SectionStartMap.empty()) 1469 error(toString(S->File) + ": partitions cannot be used with " 1470 "--section-start, -Ttext, -Tdata or -Tbss"); 1471 if (Config->EMachine == EM_MIPS) 1472 error(toString(S->File) + ": partitions cannot be used on this target"); 1473 1474 // Impose a limit of no more than 254 partitions. This limit comes from the 1475 // sizes of the Partition fields in InputSectionBase and Symbol, as well as 1476 // the amount of space devoted to the partition number in RankFlags. 1477 if (Partitions.size() == 254) 1478 fatal("may not have more than 254 partitions"); 1479 1480 Partitions.emplace_back(); 1481 Partition &NewPart = Partitions.back(); 1482 NewPart.Name = PartName; 1483 Sym->Partition = NewPart.getNumber(); 1484 } 1485 1486 static Symbol *addUndefined(StringRef Name) { 1487 return Symtab->addSymbol( 1488 Undefined{nullptr, Name, STB_GLOBAL, STV_DEFAULT, 0}); 1489 } 1490 1491 // This function is where all the optimizations of link-time 1492 // optimization takes place. When LTO is in use, some input files are 1493 // not in native object file format but in the LLVM bitcode format. 1494 // This function compiles bitcode files into a few big native files 1495 // using LLVM functions and replaces bitcode symbols with the results. 1496 // Because all bitcode files that the program consists of are passed to 1497 // the compiler at once, it can do a whole-program optimization. 1498 template <class ELFT> void LinkerDriver::compileBitcodeFiles() { 1499 // Compile bitcode files and replace bitcode symbols. 1500 LTO.reset(new BitcodeCompiler); 1501 for (BitcodeFile *File : BitcodeFiles) 1502 LTO->add(*File); 1503 1504 for (InputFile *File : LTO->compile()) { 1505 DenseMap<CachedHashStringRef, const InputFile *> DummyGroups; 1506 auto *Obj = cast<ObjFile<ELFT>>(File); 1507 Obj->parse(DummyGroups); 1508 for (Symbol *Sym : Obj->getGlobalSymbols()) 1509 Sym->parseSymbolVersion(); 1510 ObjectFiles.push_back(File); 1511 } 1512 } 1513 1514 // The --wrap option is a feature to rename symbols so that you can write 1515 // wrappers for existing functions. If you pass `-wrap=foo`, all 1516 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are 1517 // expected to write `wrap_foo` function as a wrapper). The original 1518 // symbol becomes accessible as `real_foo`, so you can call that from your 1519 // wrapper. 1520 // 1521 // This data structure is instantiated for each -wrap option. 1522 struct WrappedSymbol { 1523 Symbol *Sym; 1524 Symbol *Real; 1525 Symbol *Wrap; 1526 }; 1527 1528 // Handles -wrap option. 1529 // 1530 // This function instantiates wrapper symbols. At this point, they seem 1531 // like they are not being used at all, so we explicitly set some flags so 1532 // that LTO won't eliminate them. 1533 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &Args) { 1534 std::vector<WrappedSymbol> V; 1535 DenseSet<StringRef> Seen; 1536 1537 for (auto *Arg : Args.filtered(OPT_wrap)) { 1538 StringRef Name = Arg->getValue(); 1539 if (!Seen.insert(Name).second) 1540 continue; 1541 1542 Symbol *Sym = Symtab->find(Name); 1543 if (!Sym) 1544 continue; 1545 1546 Symbol *Real = addUndefined(Saver.save("__real_" + Name)); 1547 Symbol *Wrap = addUndefined(Saver.save("__wrap_" + Name)); 1548 V.push_back({Sym, Real, Wrap}); 1549 1550 // We want to tell LTO not to inline symbols to be overwritten 1551 // because LTO doesn't know the final symbol contents after renaming. 1552 Real->CanInline = false; 1553 Sym->CanInline = false; 1554 1555 // Tell LTO not to eliminate these symbols. 1556 Sym->IsUsedInRegularObj = true; 1557 Wrap->IsUsedInRegularObj = true; 1558 } 1559 return V; 1560 } 1561 1562 // Do renaming for -wrap by updating pointers to symbols. 1563 // 1564 // When this function is executed, only InputFiles and symbol table 1565 // contain pointers to symbol objects. We visit them to replace pointers, 1566 // so that wrapped symbols are swapped as instructed by the command line. 1567 static void wrapSymbols(ArrayRef<WrappedSymbol> Wrapped) { 1568 DenseMap<Symbol *, Symbol *> Map; 1569 for (const WrappedSymbol &W : Wrapped) { 1570 Map[W.Sym] = W.Wrap; 1571 Map[W.Real] = W.Sym; 1572 } 1573 1574 // Update pointers in input files. 1575 parallelForEach(ObjectFiles, [&](InputFile *File) { 1576 MutableArrayRef<Symbol *> Syms = File->getMutableSymbols(); 1577 for (size_t I = 0, E = Syms.size(); I != E; ++I) 1578 if (Symbol *S = Map.lookup(Syms[I])) 1579 Syms[I] = S; 1580 }); 1581 1582 // Update pointers in the symbol table. 1583 for (const WrappedSymbol &W : Wrapped) 1584 Symtab->wrap(W.Sym, W.Real, W.Wrap); 1585 } 1586 1587 static const char *LibcallRoutineNames[] = { 1588 #define HANDLE_LIBCALL(code, name) name, 1589 #include "llvm/IR/RuntimeLibcalls.def" 1590 #undef HANDLE_LIBCALL 1591 }; 1592 1593 // Do actual linking. Note that when this function is called, 1594 // all linker scripts have already been parsed. 1595 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) { 1596 // If a -hash-style option was not given, set to a default value, 1597 // which varies depending on the target. 1598 if (!Args.hasArg(OPT_hash_style)) { 1599 if (Config->EMachine == EM_MIPS) 1600 Config->SysvHash = true; 1601 else 1602 Config->SysvHash = Config->GnuHash = true; 1603 } 1604 1605 // Default output filename is "a.out" by the Unix tradition. 1606 if (Config->OutputFile.empty()) 1607 Config->OutputFile = "a.out"; 1608 1609 // Fail early if the output file or map file is not writable. If a user has a 1610 // long link, e.g. due to a large LTO link, they do not wish to run it and 1611 // find that it failed because there was a mistake in their command-line. 1612 if (auto E = tryCreateFile(Config->OutputFile)) 1613 error("cannot open output file " + Config->OutputFile + ": " + E.message()); 1614 if (auto E = tryCreateFile(Config->MapFile)) 1615 error("cannot open map file " + Config->MapFile + ": " + E.message()); 1616 if (errorCount()) 1617 return; 1618 1619 // Use default entry point name if no name was given via the command 1620 // line nor linker scripts. For some reason, MIPS entry point name is 1621 // different from others. 1622 Config->WarnMissingEntry = 1623 (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable)); 1624 if (Config->Entry.empty() && !Config->Relocatable) 1625 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start"; 1626 1627 // Handle --trace-symbol. 1628 for (auto *Arg : Args.filtered(OPT_trace_symbol)) 1629 Symtab->insert(Arg->getValue())->Traced = true; 1630 1631 // Add all files to the symbol table. This will add almost all 1632 // symbols that we need to the symbol table. This process might 1633 // add files to the link, via autolinking, these files are always 1634 // appended to the Files vector. 1635 for (size_t I = 0; I < Files.size(); ++I) 1636 parseFile(Files[I]); 1637 1638 // Now that we have every file, we can decide if we will need a 1639 // dynamic symbol table. 1640 // We need one if we were asked to export dynamic symbols or if we are 1641 // producing a shared library. 1642 // We also need one if any shared libraries are used and for pie executables 1643 // (probably because the dynamic linker needs it). 1644 Config->HasDynSymTab = 1645 !SharedFiles.empty() || Config->Pic || Config->ExportDynamic; 1646 1647 // Some symbols (such as __ehdr_start) are defined lazily only when there 1648 // are undefined symbols for them, so we add these to trigger that logic. 1649 for (StringRef Name : Script->ReferencedSymbols) 1650 addUndefined(Name); 1651 1652 // Handle the `--undefined <sym>` options. 1653 for (StringRef S : Config->Undefined) 1654 handleUndefined(S); 1655 1656 // If an entry symbol is in a static archive, pull out that file now. 1657 handleUndefined(Config->Entry); 1658 1659 // If any of our inputs are bitcode files, the LTO code generator may create 1660 // references to certain library functions that might not be explicit in the 1661 // bitcode file's symbol table. If any of those library functions are defined 1662 // in a bitcode file in an archive member, we need to arrange to use LTO to 1663 // compile those archive members by adding them to the link beforehand. 1664 // 1665 // However, adding all libcall symbols to the link can have undesired 1666 // consequences. For example, the libgcc implementation of 1667 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry 1668 // that aborts the program if the Linux kernel does not support 64-bit 1669 // atomics, which would prevent the program from running even if it does not 1670 // use 64-bit atomics. 1671 // 1672 // Therefore, we only add libcall symbols to the link before LTO if we have 1673 // to, i.e. if the symbol's definition is in bitcode. Any other required 1674 // libcall symbols will be added to the link after LTO when we add the LTO 1675 // object file to the link. 1676 if (!BitcodeFiles.empty()) 1677 for (const char *S : LibcallRoutineNames) 1678 handleLibcall(S); 1679 1680 // Return if there were name resolution errors. 1681 if (errorCount()) 1682 return; 1683 1684 // Now when we read all script files, we want to finalize order of linker 1685 // script commands, which can be not yet final because of INSERT commands. 1686 Script->processInsertCommands(); 1687 1688 // We want to declare linker script's symbols early, 1689 // so that we can version them. 1690 // They also might be exported if referenced by DSOs. 1691 Script->declareSymbols(); 1692 1693 // Handle the -exclude-libs option. 1694 if (Args.hasArg(OPT_exclude_libs)) 1695 excludeLibs(Args); 1696 1697 // Create ElfHeader early. We need a dummy section in 1698 // addReservedSymbols to mark the created symbols as not absolute. 1699 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC); 1700 Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr); 1701 1702 // Create wrapped symbols for -wrap option. 1703 std::vector<WrappedSymbol> Wrapped = addWrappedSymbols(Args); 1704 1705 // We need to create some reserved symbols such as _end. Create them. 1706 if (!Config->Relocatable) 1707 addReservedSymbols(); 1708 1709 // Apply version scripts. 1710 // 1711 // For a relocatable output, version scripts don't make sense, and 1712 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol 1713 // name "foo@ver1") rather do harm, so we don't call this if -r is given. 1714 if (!Config->Relocatable) 1715 Symtab->scanVersionScript(); 1716 1717 // Do link-time optimization if given files are LLVM bitcode files. 1718 // This compiles bitcode files into real object files. 1719 // 1720 // With this the symbol table should be complete. After this, no new names 1721 // except a few linker-synthesized ones will be added to the symbol table. 1722 compileBitcodeFiles<ELFT>(); 1723 if (errorCount()) 1724 return; 1725 1726 // If -thinlto-index-only is given, we should create only "index 1727 // files" and not object files. Index file creation is already done 1728 // in addCombinedLTOObject, so we are done if that's the case. 1729 if (Config->ThinLTOIndexOnly) 1730 return; 1731 1732 // Likewise, --plugin-opt=emit-llvm is an option to make LTO create 1733 // an output file in bitcode and exit, so that you can just get a 1734 // combined bitcode file. 1735 if (Config->EmitLLVM) 1736 return; 1737 1738 // Apply symbol renames for -wrap. 1739 if (!Wrapped.empty()) 1740 wrapSymbols(Wrapped); 1741 1742 // Now that we have a complete list of input files. 1743 // Beyond this point, no new files are added. 1744 // Aggregate all input sections into one place. 1745 for (InputFile *F : ObjectFiles) 1746 for (InputSectionBase *S : F->getSections()) 1747 if (S && S != &InputSection::Discarded) 1748 InputSections.push_back(S); 1749 for (BinaryFile *F : BinaryFiles) 1750 for (InputSectionBase *S : F->getSections()) 1751 InputSections.push_back(cast<InputSection>(S)); 1752 1753 llvm::erase_if(InputSections, [](InputSectionBase *S) { 1754 if (S->Type == SHT_LLVM_SYMPART) { 1755 readSymbolPartitionSection<ELFT>(S); 1756 return true; 1757 } 1758 1759 // We do not want to emit debug sections if --strip-all 1760 // or -strip-debug are given. 1761 return Config->Strip != StripPolicy::None && 1762 (S->Name.startswith(".debug") || S->Name.startswith(".zdebug")); 1763 }); 1764 1765 Config->EFlags = Target->calcEFlags(); 1766 // MaxPageSize (sometimes called abi page size) is the maximum page size that 1767 // the output can be run on. For example if the OS can use 4k or 64k page 1768 // sizes then MaxPageSize must be 64 for the output to be useable on both. 1769 // All important alignment decisions must use this value. 1770 Config->MaxPageSize = getMaxPageSize(Args); 1771 // CommonPageSize is the most common page size that the output will be run on. 1772 // For example if an OS can use 4k or 64k page sizes and 4k is more common 1773 // than 64k then CommonPageSize is set to 4k. CommonPageSize can be used for 1774 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it 1775 // is limited to writing trap instructions on the last executable segment. 1776 Config->CommonPageSize = getCommonPageSize(Args); 1777 1778 Config->ImageBase = getImageBase(Args); 1779 1780 if (Config->EMachine == EM_ARM) { 1781 // FIXME: These warnings can be removed when lld only uses these features 1782 // when the input objects have been compiled with an architecture that 1783 // supports them. 1784 if (Config->ARMHasBlx == false) 1785 warn("lld uses blx instruction, no object with architecture supporting " 1786 "feature detected"); 1787 } 1788 1789 // This adds a .comment section containing a version string. We have to add it 1790 // before mergeSections because the .comment section is a mergeable section. 1791 if (!Config->Relocatable) 1792 InputSections.push_back(createCommentSection()); 1793 1794 // Replace common symbols with regular symbols. 1795 replaceCommonSymbols(); 1796 1797 // Do size optimizations: garbage collection, merging of SHF_MERGE sections 1798 // and identical code folding. 1799 splitSections<ELFT>(); 1800 markLive<ELFT>(); 1801 demoteSharedSymbols(); 1802 mergeSections(); 1803 if (Config->ICF != ICFLevel::None) { 1804 findKeepUniqueSections<ELFT>(Args); 1805 doIcf<ELFT>(); 1806 } 1807 1808 // Read the callgraph now that we know what was gced or icfed 1809 if (Config->CallGraphProfileSort) { 1810 if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file)) 1811 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue())) 1812 readCallGraph(*Buffer); 1813 readCallGraphsFromObjectFiles<ELFT>(); 1814 } 1815 1816 // Write the result to the file. 1817 writeResult<ELFT>(); 1818 } 1819