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