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