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