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