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