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