1 //===- Driver.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include "InputFiles.h"
15 #include "InputSection.h"
16 #include "LinkerScript.h"
19 #include "SymbolTable.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"
34 using namespace llvm::ELF;
35 using namespace llvm::object;
36 using namespace llvm::sys;
39 using namespace lld::elf;
41 Configuration *elf::Config;
42 LinkerDriver *elf::Driver;
44 BumpPtrAllocator elf::BAlloc;
45 StringSaver elf::Saver{BAlloc};
46 std::vector<SpecificAllocBase *> elf::SpecificAllocBase::Instances;
48 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
54 Config = make<Configuration>();
55 Driver = make<LinkerDriver>();
56 ScriptConfig = make<ScriptConfiguration>();
58 Driver->main(Args, CanExitEarly);
63 // Parses a linker -m option.
64 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
67 if (S.endswith("_fbsd")) {
69 OSABI = ELFOSABI_FREEBSD;
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});
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);
94 error("unknown emulation: " + Emul);
96 return std::make_tuple(Ret.first, Ret.second, OSABI);
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");
107 std::vector<MemoryBufferRef> V;
108 Error Err = Error::success();
109 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
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");
120 fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
121 toString(std::move(Err)));
123 // Take ownership of memory buffers created for members of thin archives.
124 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
125 make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
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;
135 Optional<MemoryBufferRef> Buffer = readFile(Path);
136 if (!Buffer.hasValue())
138 MemoryBufferRef MBRef = *Buffer;
141 Files.push_back(make<BinaryFile>(MBRef));
145 switch (identify_magic(MBRef.getBuffer())) {
146 case file_magic::unknown:
147 readLinkerScript(MBRef);
149 case file_magic::archive:
150 if (InWholeArchive) {
151 for (MemoryBufferRef MB : getArchiveMembers(MBRef))
152 Files.push_back(createObjectFile(MB, Path));
155 Files.push_back(make<ArchiveFile>(MBRef));
157 case file_magic::elf_shared_object:
158 if (Config->Relocatable) {
159 error("attempted static link of dynamic object " + Path);
162 Files.push_back(createSharedFile(MBRef));
166 Files.push_back(make<LazyObjectFile>(MBRef));
168 Files.push_back(createObjectFile(MBRef));
172 Optional<MemoryBufferRef> LinkerDriver::readFile(StringRef Path) {
174 outs() << Path << "\n";
176 auto MBOrErr = MemoryBuffer::getFile(Path);
177 if (auto EC = MBOrErr.getError()) {
178 error(EC, "cannot open " + Path);
181 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
182 MemoryBufferRef MBRef = MB->getMemBufferRef();
183 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
186 Cpio->append(relativeToRoot(Path), MBRef.getBuffer());
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))
196 error("unable to find library -l" + Name);
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();
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());
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.");
225 if (Config->Pie && Config->Shared)
226 error("-shared and -pie may not be used together");
228 if (Config->Relocatable) {
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");
234 error("-r and --icf may not be used together");
236 error("-r and -pie may not be used together");
240 static StringRef getString(opt::InputArgList &Args, unsigned Key,
241 StringRef Default = "") {
242 if (auto *Arg = Args.getLastArg(Key))
243 return Arg->getValue();
247 static int getInteger(opt::InputArgList &Args, unsigned Key, int 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);
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");
263 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
264 for (auto *Arg : Args.filtered(OPT_z))
265 if (Key == Arg->getValue())
270 static uint64_t getZOptionValue(opt::InputArgList &Args, StringRef Key,
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);
278 if (Value.getAsInteger(0, Result))
279 error("invalid " + Key + ": " + Value);
286 void LinkerDriver::main(ArrayRef<const char *> ArgsArr, bool CanExitEarly) {
288 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
290 // Interpret this flag early because error() depends on them.
291 Config->ErrorLimit = getInteger(Args, OPT_error_limit, 20);
294 if (Args.hasArg(OPT_help)) {
295 printHelp(ArgsArr[0]);
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))
307 Config->ExitEarly = CanExitEarly && !Args.hasArg(OPT_full_shutdown);
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);
315 Cpio->append("response.txt", createResponseFile(Args));
316 Cpio->append("version.txt", getLLDVersion() + "\n");
319 Twine("--reproduce: failed to open ") + Path + ".cpio");
330 switch (Config->EKind) {
344 llvm_unreachable("unknown Config->EKind");
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;
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);
364 return UnresolvedPolicy::ReportError;
367 static Target2Policy getTarget2Option(opt::InputArgList &Args) {
368 if (auto *Arg = Args.getLastArg(OPT_target2)) {
369 StringRef S = Arg->getValue();
371 return Target2Policy::Rel;
373 return Target2Policy::Abs;
375 return Target2Policy::GotRel;
376 error("unknown --target2 option: " + S);
378 return Target2Policy::GotRel;
381 static bool isOutputFormatBinary(opt::InputArgList &Args) {
382 if (auto *Arg = Args.getLastArg(OPT_oformat)) {
383 StringRef S = Arg->getValue();
386 error("unknown --oformat value: " + S);
391 static bool getArg(opt::InputArgList &Args, unsigned K1, unsigned K2,
393 if (auto *Arg = Args.getLastArg(K1, K2))
394 return Arg->getOption().getID() == K1;
398 static DiscardPolicy getDiscardOption(opt::InputArgList &Args) {
399 if (Config->Relocatable)
400 return DiscardPolicy::None;
402 Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
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;
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;
418 return StripPolicy::None;
421 static uint64_t parseSectionAddress(StringRef S, opt::Arg *Arg) {
423 if (S.startswith("0x"))
425 if (S.getAsInteger(16, VA))
426 error("invalid argument: " + stringize(Arg));
430 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
431 StringMap<uint64_t> Ret;
432 for (auto *Arg : Args.filtered(OPT_section_start)) {
435 std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
436 Ret[Name] = parseSectionAddress(Addr, Arg);
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);
448 static SortSectionPolicy getSortKind(opt::InputArgList &Args) {
449 StringRef S = getString(Args, OPT_sort_section);
450 if (S == "alignment")
451 return SortSectionPolicy::Alignment;
453 return SortSectionPolicy::Name;
455 error("unknown --sort-section rule: " + S);
456 return SortSectionPolicy::Default;
459 static std::vector<StringRef> getLines(MemoryBufferRef MB) {
460 SmallVector<StringRef, 0> Arr;
461 MB.getBuffer().split(Arr, '\n');
463 std::vector<StringRef> Ret;
464 for (StringRef S : Arr) {
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());
477 std::vector<StringRef> RPaths;
478 for (auto *Arg : Args.filtered(OPT_rpath))
479 RPaths.push_back(Arg->getValue());
481 Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
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) =
488 Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
489 Config->Emulation = S;
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);
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);
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");
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");
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);
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.
562 Config->ZRelro = false;
564 if (!Config->Relocatable)
565 Config->Strip = getStripOption(Args);
567 // Config->Pic is true if we are generating position-independent code.
568 Config->Pic = Config->Pie || Config->Shared;
570 if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
571 StringRef S = Arg->getValue();
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);
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();
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));
598 error("unknown --build-id style: " + S);
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");
607 for (auto *Arg : Args.filtered(OPT_undefined))
608 Config->Undefined.push_back(Arg->getValue());
610 if (auto *Arg = Args.getLastArg(OPT_dynamic_list))
611 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
612 readDynamicList(*Buffer);
614 if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
615 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
616 Config->SymbolOrderingFile = getLines(*Buffer);
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);
627 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
628 Config->VersionScriptGlobals.push_back(
629 {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
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
634 if (Args.hasArg(OPT_dynamic_list) || Args.hasArg(OPT_export_dynamic_symbol)) {
635 Config->ExportDynamic = true;
637 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
640 if (auto *Arg = Args.getLastArg(OPT_version_script))
641 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
642 readVersionScript(*Buffer);
645 // Returns a value of "-format" option.
646 static bool getBinaryOption(StringRef S) {
649 if (S == "elf" || S == "default")
651 error("unknown -format value: " + S +
652 " (supported formats: elf, default, binary)");
656 void LinkerDriver::createFiles(opt::InputArgList &Args) {
657 for (auto *Arg : Args) {
658 switch (Arg->getOption().getID()) {
660 addLibrary(Arg->getValue());
663 addFile(Arg->getValue());
665 case OPT_alias_script_T:
667 if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue()))
668 readLinkerScript(*MB);
671 Config->AsNeeded = true;
674 InBinary = getBinaryOption(Arg->getValue());
676 case OPT_no_as_needed:
677 Config->AsNeeded = false;
680 Config->Static = true;
683 Config->Static = false;
685 case OPT_whole_archive:
686 InWholeArchive = true;
688 case OPT_no_whole_archive:
689 InWholeArchive = false;
700 if (Files.empty() && ErrorCount == 0)
701 error("no input files");
704 // If -m <machine_type> was not given, infer it from object files.
705 void LinkerDriver::inferMachineType() {
706 if (Config->EKind != ELFNoneKind)
709 for (InputFile *F : Files) {
710 if (F->EKind == ELFNoneKind)
712 Config->EKind = F->EKind;
713 Config->EMachine = F->EMachine;
714 Config->OSABI = F->OSABI;
715 Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
718 error("target emulation unknown: -m or at least one .o file required");
721 // Parse -z max-page-size=<value>. The default value is defined by
723 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
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");
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);
738 return Config->Pic ? 0 : Target->DefaultImageBase;
740 StringRef S = Arg->getValue();
742 if (S.getAsInteger(0, V)) {
743 error("-image-base: number expected, but got " + S);
746 if ((V % Config->MaxPageSize) != 0)
747 warn("-image-base: address isn't multiple of page size: " + S);
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>>();
760 ELFT::Is64Bits || Config->EMachine == EM_X86_64 || Config->MipsN32Abi;
762 (Config->EMachine == EM_MIPS && Config->EKind == ELF64LEKind);
763 Config->MaxPageSize = getMaxPageSize(Args);
764 Config->ImageBase = getImageBase(Args);
766 // Default output filename is "a.out" by the Unix tradition.
767 if (Config->OutputFile.empty())
768 Config->OutputFile = "a.out";
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";
778 // Handle --trace-symbol.
779 for (auto *Arg : Args.filtered(OPT_trace_symbol))
780 Symtab.trace(Arg->getValue());
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)
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);
793 // Return if there were name resolution errors.
797 Symtab.scanUndefinedFlags();
798 Symtab.scanShlibUndefined();
799 Symtab.scanVersionScript();
801 Symtab.addCombinedLTOObject();
805 for (auto *Arg : Args.filtered(OPT_wrap))
806 Symtab.wrap(Arg->getValue());
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));
819 // Do size optimizations: garbage collection and identical code folding.
820 if (Config->GcSections)
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) {
831 if (S->isCompressed())
833 if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(S))
834 MS->splitIntoPieces();
837 // Write the result to the file.