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/Path.h"
29 #include "llvm/Support/TargetSelect.h"
30 #include "llvm/Support/raw_ostream.h"
35 using namespace llvm::ELF;
36 using namespace llvm::object;
37 using namespace llvm::sys;
40 using namespace lld::elf;
42 Configuration *elf::Config;
43 LinkerDriver *elf::Driver;
45 BumpPtrAllocator elf::BAlloc;
46 StringSaver elf::Saver{BAlloc};
47 std::vector<SpecificAllocBase *> elf::SpecificAllocBase::Instances;
49 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
55 Config = make<Configuration>();
56 Driver = make<LinkerDriver>();
57 ScriptConfig = make<ScriptConfiguration>();
59 Driver->main(Args, CanExitEarly);
64 // Parses a linker -m option.
65 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
68 if (S.endswith("_fbsd")) {
70 OSABI = ELFOSABI_FREEBSD;
73 std::pair<ELFKind, uint16_t> Ret =
74 StringSwitch<std::pair<ELFKind, uint16_t>>(S)
75 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
76 .Case("armelf_linux_eabi", {ELF32LEKind, EM_ARM})
77 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
78 .Case("elf32btsmip", {ELF32BEKind, EM_MIPS})
79 .Case("elf32ltsmip", {ELF32LEKind, EM_MIPS})
80 .Case("elf32btsmipn32", {ELF32BEKind, EM_MIPS})
81 .Case("elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
82 .Case("elf32ppc", {ELF32BEKind, EM_PPC})
83 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
84 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
85 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
86 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
87 .Case("elf_i386", {ELF32LEKind, EM_386})
88 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
89 .Default({ELFNoneKind, EM_NONE});
91 if (Ret.first == ELFNoneKind) {
92 if (S == "i386pe" || S == "i386pep" || S == "thumb2pe")
93 error("Windows targets are not supported on the ELF frontend: " + Emul);
95 error("unknown emulation: " + Emul);
97 return std::make_tuple(Ret.first, Ret.second, OSABI);
100 // Returns slices of MB by parsing MB as an archive file.
101 // Each slice consists of a member file in the archive.
102 std::vector<MemoryBufferRef>
103 LinkerDriver::getArchiveMembers(MemoryBufferRef MB) {
104 std::unique_ptr<Archive> File =
105 check(Archive::create(MB),
106 MB.getBufferIdentifier() + ": failed to parse archive");
108 std::vector<MemoryBufferRef> V;
109 Error Err = Error::success();
110 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
112 check(COrErr, MB.getBufferIdentifier() +
113 ": could not get the child of the archive");
114 MemoryBufferRef MBRef =
115 check(C.getMemoryBufferRef(),
116 MB.getBufferIdentifier() +
117 ": could not get the buffer for a child of the archive");
121 fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
122 toString(std::move(Err)));
124 // Take ownership of memory buffers created for members of thin archives.
125 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
126 make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
131 // Opens and parses a file. Path has to be resolved already.
132 // Newly created memory buffers are owned by this driver.
133 void LinkerDriver::addFile(StringRef Path) {
134 using namespace sys::fs;
136 Optional<MemoryBufferRef> Buffer = readFile(Path);
137 if (!Buffer.hasValue())
139 MemoryBufferRef MBRef = *Buffer;
142 Files.push_back(make<BinaryFile>(MBRef));
146 switch (identify_magic(MBRef.getBuffer())) {
147 case file_magic::unknown:
148 readLinkerScript(MBRef);
150 case file_magic::archive:
151 if (InWholeArchive) {
152 for (MemoryBufferRef MB : getArchiveMembers(MBRef))
153 Files.push_back(createObjectFile(MB, Path));
156 Files.push_back(make<ArchiveFile>(MBRef));
158 case file_magic::elf_shared_object:
159 if (Config->Relocatable) {
160 error("attempted static link of dynamic object " + Path);
163 Files.push_back(createSharedFile(MBRef));
167 Files.push_back(make<LazyObjectFile>(MBRef));
169 Files.push_back(createObjectFile(MBRef));
173 Optional<MemoryBufferRef> LinkerDriver::readFile(StringRef Path) {
175 outs() << Path << "\n";
177 auto MBOrErr = MemoryBuffer::getFile(Path);
178 if (auto EC = MBOrErr.getError()) {
179 error(EC, "cannot open " + Path);
182 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
183 MemoryBufferRef MBRef = MB->getMemBufferRef();
184 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
187 Tar->append(relativeToRoot(Path), MBRef.getBuffer());
192 // Add a given library by searching it from input search paths.
193 void LinkerDriver::addLibrary(StringRef Name) {
194 if (Optional<std::string> Path = searchLibrary(Name))
197 error("unable to find library -l" + Name);
200 // This function is called on startup. We need this for LTO since
201 // LTO calls LLVM functions to compile bitcode files to native code.
202 // Technically this can be delayed until we read bitcode files, but
203 // we don't bother to do lazily because the initialization is fast.
204 static void initLLVM(opt::InputArgList &Args) {
205 InitializeAllTargets();
206 InitializeAllTargetMCs();
207 InitializeAllAsmPrinters();
208 InitializeAllAsmParsers();
210 // Parse and evaluate -mllvm options.
211 std::vector<const char *> V;
212 V.push_back("lld (LLVM option parsing)");
213 for (auto *Arg : Args.filtered(OPT_mllvm))
214 V.push_back(Arg->getValue());
215 cl::ParseCommandLineOptions(V.size(), V.data());
218 // Some command line options or some combinations of them are not allowed.
219 // This function checks for such errors.
220 static void checkOptions(opt::InputArgList &Args) {
221 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
222 // table which is a relatively new feature.
223 if (Config->EMachine == EM_MIPS && Config->GnuHash)
224 error("the .gnu.hash section is not compatible with the MIPS target.");
226 if (Config->Pie && Config->Shared)
227 error("-shared and -pie may not be used together");
229 if (Config->Relocatable) {
231 error("-r and -shared may not be used together");
232 if (Config->GcSections)
233 error("-r and --gc-sections may not be used together");
235 error("-r and --icf may not be used together");
237 error("-r and -pie may not be used together");
241 static StringRef getString(opt::InputArgList &Args, unsigned Key,
242 StringRef Default = "") {
243 if (auto *Arg = Args.getLastArg(Key))
244 return Arg->getValue();
248 static int getInteger(opt::InputArgList &Args, unsigned Key, int Default) {
250 if (auto *Arg = Args.getLastArg(Key)) {
251 StringRef S = Arg->getValue();
252 if (S.getAsInteger(10, V))
253 error(Arg->getSpelling() + ": number expected, but got " + S);
258 static const char *getReproduceOption(opt::InputArgList &Args) {
259 if (auto *Arg = Args.getLastArg(OPT_reproduce))
260 return Arg->getValue();
261 return getenv("LLD_REPRODUCE");
264 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
265 for (auto *Arg : Args.filtered(OPT_z))
266 if (Key == Arg->getValue())
271 static uint64_t getZOptionValue(opt::InputArgList &Args, StringRef Key,
273 for (auto *Arg : Args.filtered(OPT_z)) {
274 StringRef Value = Arg->getValue();
275 size_t Pos = Value.find("=");
276 if (Pos != StringRef::npos && Key == Value.substr(0, Pos)) {
277 Value = Value.substr(Pos + 1);
279 if (Value.getAsInteger(0, Result))
280 error("invalid " + Key + ": " + Value);
287 void LinkerDriver::main(ArrayRef<const char *> ArgsArr, bool CanExitEarly) {
289 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
291 // Interpret this flag early because error() depends on them.
292 Config->ErrorLimit = getInteger(Args, OPT_error_limit, 20);
295 if (Args.hasArg(OPT_help)) {
296 printHelp(ArgsArr[0]);
300 // GNU linkers disagree here. Though both -version and -v are mentioned
301 // in help to print the version information, GNU ld just normally exits,
302 // while gold can continue linking. We are compatible with ld.bfd here.
303 if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v))
304 outs() << getLLDVersion() << "\n";
305 if (Args.hasArg(OPT_version))
308 Config->ExitEarly = CanExitEarly && !Args.hasArg(OPT_full_shutdown);
310 if (const char *Path = getReproduceOption(Args)) {
311 // Note that --reproduce is a debug option so you can ignore it
312 // if you are trying to understand the whole picture of the code.
313 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
314 TarWriter::create(Path, path::stem(Path));
316 Tar = std::move(*ErrOrWriter);
317 Tar->append("response.txt", createResponseFile(Args));
318 Tar->append("version.txt", getLLDVersion() + "\n");
320 error(Twine("--reproduce: failed to open ") + Path + ": " +
321 toString(ErrOrWriter.takeError()));
333 switch (Config->EKind) {
347 llvm_unreachable("unknown Config->EKind");
351 static UnresolvedPolicy getUnresolvedSymbolOption(opt::InputArgList &Args) {
352 if (Args.hasArg(OPT_noinhibit_exec))
353 return UnresolvedPolicy::Warn;
354 if (Args.hasArg(OPT_no_undefined) || hasZOption(Args, "defs"))
355 return UnresolvedPolicy::NoUndef;
356 if (Config->Relocatable)
357 return UnresolvedPolicy::Ignore;
359 if (auto *Arg = Args.getLastArg(OPT_unresolved_symbols)) {
360 StringRef S = Arg->getValue();
361 if (S == "ignore-all" || S == "ignore-in-object-files")
362 return UnresolvedPolicy::Ignore;
363 if (S == "ignore-in-shared-libs" || S == "report-all")
364 return UnresolvedPolicy::ReportError;
365 error("unknown --unresolved-symbols value: " + S);
367 return UnresolvedPolicy::ReportError;
370 static Target2Policy getTarget2Option(opt::InputArgList &Args) {
371 if (auto *Arg = Args.getLastArg(OPT_target2)) {
372 StringRef S = Arg->getValue();
374 return Target2Policy::Rel;
376 return Target2Policy::Abs;
378 return Target2Policy::GotRel;
379 error("unknown --target2 option: " + S);
381 return Target2Policy::GotRel;
384 static bool isOutputFormatBinary(opt::InputArgList &Args) {
385 if (auto *Arg = Args.getLastArg(OPT_oformat)) {
386 StringRef S = Arg->getValue();
389 error("unknown --oformat value: " + S);
394 static bool getArg(opt::InputArgList &Args, unsigned K1, unsigned K2,
396 if (auto *Arg = Args.getLastArg(K1, K2))
397 return Arg->getOption().getID() == K1;
401 static DiscardPolicy getDiscardOption(opt::InputArgList &Args) {
402 if (Config->Relocatable)
403 return DiscardPolicy::None;
405 Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
407 return DiscardPolicy::Default;
408 if (Arg->getOption().getID() == OPT_discard_all)
409 return DiscardPolicy::All;
410 if (Arg->getOption().getID() == OPT_discard_locals)
411 return DiscardPolicy::Locals;
412 return DiscardPolicy::None;
415 static StripPolicy getStripOption(opt::InputArgList &Args) {
416 if (auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug)) {
417 if (Arg->getOption().getID() == OPT_strip_all)
418 return StripPolicy::All;
419 return StripPolicy::Debug;
421 return StripPolicy::None;
424 static uint64_t parseSectionAddress(StringRef S, opt::Arg *Arg) {
426 if (S.startswith("0x"))
428 if (S.getAsInteger(16, VA))
429 error("invalid argument: " + toString(Arg));
433 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
434 StringMap<uint64_t> Ret;
435 for (auto *Arg : Args.filtered(OPT_section_start)) {
438 std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
439 Ret[Name] = parseSectionAddress(Addr, Arg);
442 if (auto *Arg = Args.getLastArg(OPT_Ttext))
443 Ret[".text"] = parseSectionAddress(Arg->getValue(), Arg);
444 if (auto *Arg = Args.getLastArg(OPT_Tdata))
445 Ret[".data"] = parseSectionAddress(Arg->getValue(), Arg);
446 if (auto *Arg = Args.getLastArg(OPT_Tbss))
447 Ret[".bss"] = parseSectionAddress(Arg->getValue(), Arg);
451 static SortSectionPolicy getSortKind(opt::InputArgList &Args) {
452 StringRef S = getString(Args, OPT_sort_section);
453 if (S == "alignment")
454 return SortSectionPolicy::Alignment;
456 return SortSectionPolicy::Name;
458 error("unknown --sort-section rule: " + S);
459 return SortSectionPolicy::Default;
462 static std::vector<StringRef> getLines(MemoryBufferRef MB) {
463 SmallVector<StringRef, 0> Arr;
464 MB.getBuffer().split(Arr, '\n');
466 std::vector<StringRef> Ret;
467 for (StringRef S : Arr) {
475 // Initializes Config members by the command line options.
476 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
477 for (auto *Arg : Args.filtered(OPT_L))
478 Config->SearchPaths.push_back(Arg->getValue());
480 std::vector<StringRef> RPaths;
481 for (auto *Arg : Args.filtered(OPT_rpath))
482 RPaths.push_back(Arg->getValue());
484 Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
486 if (auto *Arg = Args.getLastArg(OPT_m)) {
487 // Parse ELF{32,64}{LE,BE} and CPU type.
488 StringRef S = Arg->getValue();
489 std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
491 Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
492 Config->Emulation = S;
495 Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
496 Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
497 Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
498 Config->Demangle = getArg(Args, OPT_demangle, OPT_no_demangle, true);
499 Config->DisableVerify = Args.hasArg(OPT_disable_verify);
500 Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
501 Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
502 Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
503 Config->FatalWarnings = Args.hasArg(OPT_fatal_warnings);
504 Config->GcSections = getArg(Args, OPT_gc_sections, OPT_no_gc_sections, false);
505 Config->GdbIndex = Args.hasArg(OPT_gdb_index);
506 Config->ICF = Args.hasArg(OPT_icf);
507 Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
508 Config->NoUndefinedVersion = Args.hasArg(OPT_no_undefined_version);
509 Config->Nostdlib = Args.hasArg(OPT_nostdlib);
510 Config->OMagic = Args.hasArg(OPT_omagic);
511 Config->Pie = getArg(Args, OPT_pie, OPT_nopie, false);
512 Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
513 Config->Relocatable = Args.hasArg(OPT_relocatable);
514 Config->Discard = getDiscardOption(Args);
515 Config->SaveTemps = Args.hasArg(OPT_save_temps);
516 Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
517 Config->Shared = Args.hasArg(OPT_shared);
518 Config->Target1Rel = getArg(Args, OPT_target1_rel, OPT_target1_abs, false);
519 Config->Threads = getArg(Args, OPT_threads, OPT_no_threads, true);
520 Config->Trace = Args.hasArg(OPT_trace);
521 Config->Verbose = Args.hasArg(OPT_verbose);
522 Config->WarnCommon = Args.hasArg(OPT_warn_common);
524 Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
525 Config->Entry = getString(Args, OPT_entry);
526 Config->Fini = getString(Args, OPT_fini, "_fini");
527 Config->Init = getString(Args, OPT_init, "_init");
528 Config->LTOAAPipeline = getString(Args, OPT_lto_aa_pipeline);
529 Config->LTONewPmPasses = getString(Args, OPT_lto_newpm_passes);
530 Config->OutputFile = getString(Args, OPT_o);
531 Config->SoName = getString(Args, OPT_soname);
532 Config->Sysroot = getString(Args, OPT_sysroot);
534 Config->Optimize = getInteger(Args, OPT_O, 1);
535 Config->LTOO = getInteger(Args, OPT_lto_O, 2);
536 if (Config->LTOO > 3)
537 error("invalid optimization level for LTO: " + getString(Args, OPT_lto_O));
538 Config->LTOPartitions = getInteger(Args, OPT_lto_partitions, 1);
539 if (Config->LTOPartitions == 0)
540 error("--lto-partitions: number of threads must be > 0");
541 Config->ThinLTOJobs = getInteger(Args, OPT_thinlto_jobs, -1u);
542 if (Config->ThinLTOJobs == 0)
543 error("--thinlto-jobs: number of threads must be > 0");
545 Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
546 Config->ZExecstack = hasZOption(Args, "execstack");
547 Config->ZNodelete = hasZOption(Args, "nodelete");
548 Config->ZNow = hasZOption(Args, "now");
549 Config->ZOrigin = hasZOption(Args, "origin");
550 Config->ZRelro = !hasZOption(Args, "norelro");
551 Config->ZStackSize = getZOptionValue(Args, "stack-size", -1);
552 Config->ZWxneeded = hasZOption(Args, "wxneeded");
554 Config->OFormatBinary = isOutputFormatBinary(Args);
555 Config->SectionStartMap = getSectionStartMap(Args);
556 Config->SortSection = getSortKind(Args);
557 Config->Target2 = getTarget2Option(Args);
558 Config->UnresolvedSymbols = getUnresolvedSymbolOption(Args);
560 // --omagic is an option to create old-fashioned executables in which
561 // .text segments are writable. Today, the option is still in use to
562 // create special-purpose programs such as boot loaders. It doesn't
563 // make sense to create PT_GNU_RELRO for such executables.
565 Config->ZRelro = false;
567 if (!Config->Relocatable)
568 Config->Strip = getStripOption(Args);
570 // Config->Pic is true if we are generating position-independent code.
571 Config->Pic = Config->Pie || Config->Shared;
573 if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
574 StringRef S = Arg->getValue();
576 Config->GnuHash = true;
577 Config->SysvHash = false;
578 } else if (S == "both") {
579 Config->GnuHash = true;
580 } else if (S != "sysv")
581 error("unknown hash style: " + S);
584 // Parse --build-id or --build-id=<style>.
585 if (Args.hasArg(OPT_build_id))
586 Config->BuildId = BuildIdKind::Fast;
587 if (auto *Arg = Args.getLastArg(OPT_build_id_eq)) {
588 StringRef S = Arg->getValue();
590 Config->BuildId = BuildIdKind::Md5;
591 } else if (S == "sha1" || S == "tree") {
592 Config->BuildId = BuildIdKind::Sha1;
593 } else if (S == "uuid") {
594 Config->BuildId = BuildIdKind::Uuid;
595 } else if (S == "none") {
596 Config->BuildId = BuildIdKind::None;
597 } else if (S.startswith("0x")) {
598 Config->BuildId = BuildIdKind::Hexstring;
599 Config->BuildIdVector = parseHex(S.substr(2));
601 error("unknown --build-id style: " + S);
605 for (auto *Arg : Args.filtered(OPT_auxiliary))
606 Config->AuxiliaryList.push_back(Arg->getValue());
607 if (!Config->Shared && !Config->AuxiliaryList.empty())
608 error("-f may not be used without -shared");
610 for (auto *Arg : Args.filtered(OPT_undefined))
611 Config->Undefined.push_back(Arg->getValue());
613 if (auto *Arg = Args.getLastArg(OPT_dynamic_list))
614 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
615 readDynamicList(*Buffer);
617 if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
618 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
619 Config->SymbolOrderingFile = getLines(*Buffer);
621 // If --retain-symbol-file is used, we'll retail only the symbols listed in
622 // the file and discard all others.
623 if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
624 Config->Discard = DiscardPolicy::RetainFile;
625 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
626 for (StringRef S : getLines(*Buffer))
627 Config->RetainSymbolsFile.insert(S);
630 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
631 Config->VersionScriptGlobals.push_back(
632 {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
634 // Dynamic lists are a simplified linker script that doesn't need the
635 // "global:" and implicitly ends with a "local:*". Set the variables needed to
637 if (Args.hasArg(OPT_dynamic_list) || Args.hasArg(OPT_export_dynamic_symbol)) {
638 Config->ExportDynamic = true;
640 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
643 if (auto *Arg = Args.getLastArg(OPT_version_script))
644 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
645 readVersionScript(*Buffer);
648 // Returns a value of "-format" option.
649 static bool getBinaryOption(StringRef S) {
652 if (S == "elf" || S == "default")
654 error("unknown -format value: " + S +
655 " (supported formats: elf, default, binary)");
659 void LinkerDriver::createFiles(opt::InputArgList &Args) {
660 for (auto *Arg : Args) {
661 switch (Arg->getOption().getID()) {
663 addLibrary(Arg->getValue());
666 addFile(Arg->getValue());
668 case OPT_alias_script_T:
670 if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue()))
671 readLinkerScript(*MB);
674 Config->AsNeeded = true;
677 InBinary = getBinaryOption(Arg->getValue());
679 case OPT_no_as_needed:
680 Config->AsNeeded = false;
683 Config->Static = true;
686 Config->Static = false;
688 case OPT_whole_archive:
689 InWholeArchive = true;
691 case OPT_no_whole_archive:
692 InWholeArchive = false;
703 if (Files.empty() && ErrorCount == 0)
704 error("no input files");
707 // If -m <machine_type> was not given, infer it from object files.
708 void LinkerDriver::inferMachineType() {
709 if (Config->EKind != ELFNoneKind)
712 for (InputFile *F : Files) {
713 if (F->EKind == ELFNoneKind)
715 Config->EKind = F->EKind;
716 Config->EMachine = F->EMachine;
717 Config->OSABI = F->OSABI;
718 Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
721 error("target emulation unknown: -m or at least one .o file required");
724 // Parse -z max-page-size=<value>. The default value is defined by
726 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
728 getZOptionValue(Args, "max-page-size", Target->DefaultMaxPageSize);
729 if (!isPowerOf2_64(Val))
730 error("max-page-size: value isn't a power of 2");
734 // Parses -image-base option.
735 static uint64_t getImageBase(opt::InputArgList &Args) {
736 // Use default if no -image-base option is given.
737 // Because we are using "Target" here, this function
738 // has to be called after the variable is initialized.
739 auto *Arg = Args.getLastArg(OPT_image_base);
741 return Config->Pic ? 0 : Target->DefaultImageBase;
743 StringRef S = Arg->getValue();
745 if (S.getAsInteger(0, V)) {
746 error("-image-base: number expected, but got " + S);
749 if ((V % Config->MaxPageSize) != 0)
750 warn("-image-base: address isn't multiple of page size: " + S);
754 // Do actual linking. Note that when this function is called,
755 // all linker scripts have already been parsed.
756 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
757 SymbolTable<ELFT> Symtab;
758 elf::Symtab<ELFT>::X = &Symtab;
759 Target = createTarget();
760 ScriptBase = Script<ELFT>::X = make<LinkerScript<ELFT>>();
763 ELFT::Is64Bits || Config->EMachine == EM_X86_64 || Config->MipsN32Abi;
765 (Config->EMachine == EM_MIPS && Config->EKind == ELF64LEKind);
766 Config->MaxPageSize = getMaxPageSize(Args);
767 Config->ImageBase = getImageBase(Args);
769 // Default output filename is "a.out" by the Unix tradition.
770 if (Config->OutputFile.empty())
771 Config->OutputFile = "a.out";
773 // Use default entry point name if no name was given via the command
774 // line nor linker scripts. For some reason, MIPS entry point name is
775 // different from others.
776 Config->WarnMissingEntry =
777 (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
778 if (Config->Entry.empty() && !Config->Relocatable)
779 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
781 // Handle --trace-symbol.
782 for (auto *Arg : Args.filtered(OPT_trace_symbol))
783 Symtab.trace(Arg->getValue());
785 // Add all files to the symbol table. This will add almost all
786 // symbols that we need to the symbol table.
787 for (InputFile *F : Files)
790 // If an entry symbol is in a static archive, pull out that file now
791 // to complete the symbol table. After this, no new names except a
792 // few linker-synthesized ones will be added to the symbol table.
793 if (Symtab.find(Config->Entry))
794 Symtab.addUndefined(Config->Entry);
796 // Return if there were name resolution errors.
800 Symtab.scanUndefinedFlags();
801 Symtab.scanShlibUndefined();
802 Symtab.scanVersionScript();
804 Symtab.addCombinedLTOObject();
808 for (auto *Arg : Args.filtered(OPT_wrap))
809 Symtab.wrap(Arg->getValue());
811 // Now that we have a complete list of input files.
812 // Beyond this point, no new files are added.
813 // Aggregate all input sections into one place.
814 for (elf::ObjectFile<ELFT> *F : Symtab.getObjectFiles())
815 for (InputSectionBase<ELFT> *S : F->getSections())
816 if (S && S != &InputSection<ELFT>::Discarded)
817 Symtab.Sections.push_back(S);
818 for (BinaryFile *F : Symtab.getBinaryFiles())
819 for (InputSectionData *S : F->getSections())
820 Symtab.Sections.push_back(cast<InputSection<ELFT>>(S));
822 // Do size optimizations: garbage collection and identical code folding.
823 if (Config->GcSections)
828 // MergeInputSection::splitIntoPieces needs to be called before
829 // any call of MergeInputSection::getOffset. Do that.
830 forEach(Symtab.Sections.begin(), Symtab.Sections.end(),
831 [](InputSectionBase<ELFT> *S) {
834 if (S->isCompressed())
836 if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(S))
837 MS->splitIntoPieces();
840 // Write the result to the file.