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