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