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