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