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