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