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