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