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/Object/Decompressor.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/TarWriter.h"
31 #include "llvm/Support/TargetSelect.h"
32 #include "llvm/Support/raw_ostream.h"
37 using namespace llvm::ELF;
38 using namespace llvm::object;
39 using namespace llvm::sys;
42 using namespace lld::elf;
44 Configuration *elf::Config;
45 LinkerDriver *elf::Driver;
47 BumpPtrAllocator elf::BAlloc;
48 StringSaver elf::Saver{BAlloc};
49 std::vector<SpecificAllocBase *> elf::SpecificAllocBase::Instances;
51 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
58 Config = make<Configuration>();
59 Driver = make<LinkerDriver>();
60 ScriptConfig = make<ScriptConfiguration>();
62 Driver->main(Args, CanExitEarly);
67 // Parses a linker -m option.
68 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
71 if (S.endswith("_fbsd")) {
73 OSABI = ELFOSABI_FREEBSD;
76 std::pair<ELFKind, uint16_t> Ret =
77 StringSwitch<std::pair<ELFKind, uint16_t>>(S)
78 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
79 .Case("armelf_linux_eabi", {ELF32LEKind, EM_ARM})
80 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
81 .Case("elf32btsmip", {ELF32BEKind, EM_MIPS})
82 .Case("elf32ltsmip", {ELF32LEKind, EM_MIPS})
83 .Case("elf32btsmipn32", {ELF32BEKind, EM_MIPS})
84 .Case("elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
85 .Case("elf32ppc", {ELF32BEKind, EM_PPC})
86 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
87 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
88 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
89 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
90 .Case("elf_i386", {ELF32LEKind, EM_386})
91 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
92 .Default({ELFNoneKind, EM_NONE});
94 if (Ret.first == ELFNoneKind) {
95 if (S == "i386pe" || S == "i386pep" || S == "thumb2pe")
96 error("Windows targets are not supported on the ELF frontend: " + Emul);
98 error("unknown emulation: " + Emul);
100 return std::make_tuple(Ret.first, Ret.second, OSABI);
103 // Returns slices of MB by parsing MB as an archive file.
104 // Each slice consists of a member file in the archive.
105 std::vector<MemoryBufferRef>
106 LinkerDriver::getArchiveMembers(MemoryBufferRef MB) {
107 std::unique_ptr<Archive> File =
108 check(Archive::create(MB),
109 MB.getBufferIdentifier() + ": failed to parse archive");
111 std::vector<MemoryBufferRef> V;
112 Error Err = Error::success();
113 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
115 check(COrErr, MB.getBufferIdentifier() +
116 ": could not get the child of the archive");
117 MemoryBufferRef MBRef =
118 check(C.getMemoryBufferRef(),
119 MB.getBufferIdentifier() +
120 ": could not get the buffer for a child of the archive");
124 fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
125 toString(std::move(Err)));
127 // Take ownership of memory buffers created for members of thin archives.
128 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
129 make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
134 // Opens and parses a file. Path has to be resolved already.
135 // Newly created memory buffers are owned by this driver.
136 void LinkerDriver::addFile(StringRef Path) {
137 using namespace sys::fs;
139 Optional<MemoryBufferRef> Buffer = readFile(Path);
140 if (!Buffer.hasValue())
142 MemoryBufferRef MBRef = *Buffer;
145 Files.push_back(make<BinaryFile>(MBRef));
149 switch (identify_magic(MBRef.getBuffer())) {
150 case file_magic::unknown:
151 readLinkerScript(MBRef);
153 case file_magic::archive:
154 if (InWholeArchive) {
155 for (MemoryBufferRef MB : getArchiveMembers(MBRef))
156 Files.push_back(createObjectFile(MB, Path));
159 Files.push_back(make<ArchiveFile>(MBRef));
161 case file_magic::elf_shared_object:
162 if (Config->Relocatable) {
163 error("attempted static link of dynamic object " + Path);
166 Files.push_back(createSharedFile(MBRef));
170 Files.push_back(make<LazyObjectFile>(MBRef));
172 Files.push_back(createObjectFile(MBRef));
176 // Add a given library by searching it from input search paths.
177 void LinkerDriver::addLibrary(StringRef Name) {
178 if (Optional<std::string> Path = searchLibrary(Name))
181 error("unable to find library -l" + Name);
184 // This function is called on startup. We need this for LTO since
185 // LTO calls LLVM functions to compile bitcode files to native code.
186 // Technically this can be delayed until we read bitcode files, but
187 // we don't bother to do lazily because the initialization is fast.
188 static void initLLVM(opt::InputArgList &Args) {
189 InitializeAllTargets();
190 InitializeAllTargetMCs();
191 InitializeAllAsmPrinters();
192 InitializeAllAsmParsers();
194 // Parse and evaluate -mllvm options.
195 std::vector<const char *> V;
196 V.push_back("lld (LLVM option parsing)");
197 for (auto *Arg : Args.filtered(OPT_mllvm))
198 V.push_back(Arg->getValue());
199 cl::ParseCommandLineOptions(V.size(), V.data());
202 // Some command line options or some combinations of them are not allowed.
203 // This function checks for such errors.
204 static void checkOptions(opt::InputArgList &Args) {
205 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
206 // table which is a relatively new feature.
207 if (Config->EMachine == EM_MIPS && Config->GnuHash)
208 error("the .gnu.hash section is not compatible with the MIPS target.");
210 if (Config->Pie && Config->Shared)
211 error("-shared and -pie may not be used together");
213 if (Config->Relocatable) {
215 error("-r and -shared may not be used together");
216 if (Config->GcSections)
217 error("-r and --gc-sections may not be used together");
219 error("-r and --icf may not be used together");
221 error("-r and -pie may not be used together");
225 static StringRef getString(opt::InputArgList &Args, unsigned Key,
226 StringRef Default = "") {
227 if (auto *Arg = Args.getLastArg(Key))
228 return Arg->getValue();
232 static int getInteger(opt::InputArgList &Args, unsigned Key, int Default) {
234 if (auto *Arg = Args.getLastArg(Key)) {
235 StringRef S = Arg->getValue();
236 if (S.getAsInteger(10, V))
237 error(Arg->getSpelling() + ": number expected, but got " + S);
242 static const char *getReproduceOption(opt::InputArgList &Args) {
243 if (auto *Arg = Args.getLastArg(OPT_reproduce))
244 return Arg->getValue();
245 return getenv("LLD_REPRODUCE");
248 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
249 for (auto *Arg : Args.filtered(OPT_z))
250 if (Key == Arg->getValue())
255 static uint64_t getZOptionValue(opt::InputArgList &Args, StringRef Key,
257 for (auto *Arg : Args.filtered(OPT_z)) {
258 StringRef Value = Arg->getValue();
259 size_t Pos = Value.find("=");
260 if (Pos != StringRef::npos && Key == Value.substr(0, Pos)) {
261 Value = Value.substr(Pos + 1);
263 if (Value.getAsInteger(0, Result))
264 error("invalid " + Key + ": " + Value);
271 void LinkerDriver::main(ArrayRef<const char *> ArgsArr, bool CanExitEarly) {
273 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
275 // Interpret this flag early because error() depends on them.
276 Config->ErrorLimit = getInteger(Args, OPT_error_limit, 20);
279 if (Args.hasArg(OPT_help)) {
280 printHelp(ArgsArr[0]);
284 // Handle -v or -version.
286 // A note about "compatible with GNU linkers" message: this is a hack for
287 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
288 // still the newest version in March 2017) or earlier to recognize LLD as
289 // a GNU compatible linker. As long as an output for the -v option
290 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
292 // This is somewhat ugly hack, but in reality, we had no choice other
293 // than doing this. Considering the very long release cycle of Libtool,
294 // it is not easy to improve it to recognize LLD as a GNU compatible
295 // linker in a timely manner. Even if we can make it, there are still a
296 // lot of "configure" scripts out there that are generated by old version
297 // of Libtool. We cannot convince every software developer to migrate to
298 // the latest version and re-generate scripts. So we have this hack.
299 if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
300 outs() << getLLDVersion() << " (compatible with GNU linkers)\n";
302 // ld.bfd always exits after printing out the version string.
303 // ld.gold proceeds if a given option is -v. Because gold's behavior
304 // is more permissive than ld.bfd, we chose what gold does here.
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 = ErrOrWriter->get();
317 Tar->append("response.txt", createResponseFile(Args));
318 Tar->append("version.txt", getLLDVersion() + "\n");
319 make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
321 error(Twine("--reproduce: failed to open ") + Path + ": " +
322 toString(ErrOrWriter.takeError()));
334 switch (Config->EKind) {
348 llvm_unreachable("unknown Config->EKind");
352 static UnresolvedPolicy getUnresolvedSymbolOption(opt::InputArgList &Args) {
353 if (Args.hasArg(OPT_noinhibit_exec))
354 return UnresolvedPolicy::Warn;
355 if (Args.hasArg(OPT_no_undefined) || hasZOption(Args, "defs"))
356 return UnresolvedPolicy::NoUndef;
357 if (Config->Relocatable)
358 return UnresolvedPolicy::Ignore;
360 if (auto *Arg = Args.getLastArg(OPT_unresolved_symbols)) {
361 StringRef S = Arg->getValue();
362 if (S == "ignore-all" || S == "ignore-in-object-files")
363 return UnresolvedPolicy::Ignore;
364 if (S == "ignore-in-shared-libs" || S == "report-all")
365 return UnresolvedPolicy::ReportError;
366 error("unknown --unresolved-symbols value: " + S);
368 return UnresolvedPolicy::ReportError;
371 static Target2Policy getTarget2Option(opt::InputArgList &Args) {
372 if (auto *Arg = Args.getLastArg(OPT_target2)) {
373 StringRef S = Arg->getValue();
375 return Target2Policy::Rel;
377 return Target2Policy::Abs;
379 return Target2Policy::GotRel;
380 error("unknown --target2 option: " + S);
382 return Target2Policy::GotRel;
385 static bool isOutputFormatBinary(opt::InputArgList &Args) {
386 if (auto *Arg = Args.getLastArg(OPT_oformat)) {
387 StringRef S = Arg->getValue();
390 error("unknown --oformat value: " + S);
395 static bool getArg(opt::InputArgList &Args, unsigned K1, unsigned K2,
397 if (auto *Arg = Args.getLastArg(K1, K2))
398 return Arg->getOption().getID() == K1;
402 static DiscardPolicy getDiscardOption(opt::InputArgList &Args) {
403 if (Config->Relocatable)
404 return DiscardPolicy::None;
406 Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
408 return DiscardPolicy::Default;
409 if (Arg->getOption().getID() == OPT_discard_all)
410 return DiscardPolicy::All;
411 if (Arg->getOption().getID() == OPT_discard_locals)
412 return DiscardPolicy::Locals;
413 return DiscardPolicy::None;
416 static StripPolicy getStripOption(opt::InputArgList &Args) {
417 if (auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug)) {
418 if (Arg->getOption().getID() == OPT_strip_all)
419 return StripPolicy::All;
420 return StripPolicy::Debug;
422 return StripPolicy::None;
425 static uint64_t parseSectionAddress(StringRef S, opt::Arg *Arg) {
427 if (S.startswith("0x"))
429 if (S.getAsInteger(16, VA))
430 error("invalid argument: " + toString(Arg));
434 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
435 StringMap<uint64_t> Ret;
436 for (auto *Arg : Args.filtered(OPT_section_start)) {
439 std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
440 Ret[Name] = parseSectionAddress(Addr, Arg);
443 if (auto *Arg = Args.getLastArg(OPT_Ttext))
444 Ret[".text"] = parseSectionAddress(Arg->getValue(), Arg);
445 if (auto *Arg = Args.getLastArg(OPT_Tdata))
446 Ret[".data"] = parseSectionAddress(Arg->getValue(), Arg);
447 if (auto *Arg = Args.getLastArg(OPT_Tbss))
448 Ret[".bss"] = parseSectionAddress(Arg->getValue(), Arg);
452 static SortSectionPolicy getSortKind(opt::InputArgList &Args) {
453 StringRef S = getString(Args, OPT_sort_section);
454 if (S == "alignment")
455 return SortSectionPolicy::Alignment;
457 return SortSectionPolicy::Name;
459 error("unknown --sort-section rule: " + S);
460 return SortSectionPolicy::Default;
463 static std::vector<StringRef> getLines(MemoryBufferRef MB) {
464 SmallVector<StringRef, 0> Arr;
465 MB.getBuffer().split(Arr, '\n');
467 std::vector<StringRef> Ret;
468 for (StringRef S : Arr) {
476 // Initializes Config members by the command line options.
477 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
478 for (auto *Arg : Args.filtered(OPT_L))
479 Config->SearchPaths.push_back(Arg->getValue());
481 std::vector<StringRef> RPaths;
482 for (auto *Arg : Args.filtered(OPT_rpath))
483 RPaths.push_back(Arg->getValue());
485 Config->RPath = llvm::join(RPaths.begin(), RPaths.end(), ":");
487 if (auto *Arg = Args.getLastArg(OPT_m)) {
488 // Parse ELF{32,64}{LE,BE} and CPU type.
489 StringRef S = Arg->getValue();
490 std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
492 Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
493 Config->Emulation = S;
496 Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
497 Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
498 Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
499 Config->Demangle = getArg(Args, OPT_demangle, OPT_no_demangle, true);
500 Config->DisableVerify = Args.hasArg(OPT_disable_verify);
501 Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
502 Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
503 Config->ExportDynamic = Args.hasArg(OPT_export_dynamic);
504 Config->FatalWarnings = Args.hasArg(OPT_fatal_warnings);
505 Config->GcSections = getArg(Args, OPT_gc_sections, OPT_no_gc_sections, false);
506 Config->GdbIndex = Args.hasArg(OPT_gdb_index);
507 Config->ICF = Args.hasArg(OPT_icf);
508 Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
509 Config->NoUndefinedVersion = Args.hasArg(OPT_no_undefined_version);
510 Config->Nostdlib = Args.hasArg(OPT_nostdlib);
511 Config->OMagic = Args.hasArg(OPT_omagic);
512 Config->Pie = getArg(Args, OPT_pie, OPT_nopie, false);
513 Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
514 Config->Relocatable = Args.hasArg(OPT_relocatable);
515 Config->DefineCommon = getArg(Args, OPT_define_common, OPT_no_define_common,
516 !Config->Relocatable);
517 Config->Discard = getDiscardOption(Args);
518 Config->SaveTemps = Args.hasArg(OPT_save_temps);
519 Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
520 Config->Shared = Args.hasArg(OPT_shared);
521 Config->Target1Rel = getArg(Args, OPT_target1_rel, OPT_target1_abs, false);
522 Config->Threads = getArg(Args, OPT_threads, OPT_no_threads, true);
523 Config->Trace = Args.hasArg(OPT_trace);
524 Config->Verbose = Args.hasArg(OPT_verbose);
525 Config->WarnCommon = Args.hasArg(OPT_warn_common);
527 Config->DynamicLinker = getString(Args, OPT_dynamic_linker);
528 Config->Entry = getString(Args, OPT_entry);
529 Config->Fini = getString(Args, OPT_fini, "_fini");
530 Config->Init = getString(Args, OPT_init, "_init");
531 Config->LTOAAPipeline = getString(Args, OPT_lto_aa_pipeline);
532 Config->LTONewPmPasses = getString(Args, OPT_lto_newpm_passes);
533 Config->OutputFile = getString(Args, OPT_o);
534 Config->SoName = getString(Args, OPT_soname);
535 Config->Sysroot = getString(Args, OPT_sysroot);
537 Config->Optimize = getInteger(Args, OPT_O, 1);
538 Config->LTOO = getInteger(Args, OPT_lto_O, 2);
539 if (Config->LTOO > 3)
540 error("invalid optimization level for LTO: " + getString(Args, OPT_lto_O));
541 Config->LTOPartitions = getInteger(Args, OPT_lto_partitions, 1);
542 if (Config->LTOPartitions == 0)
543 error("--lto-partitions: number of threads must be > 0");
544 Config->ThinLTOJobs = getInteger(Args, OPT_thinlto_jobs, -1u);
545 if (Config->ThinLTOJobs == 0)
546 error("--thinlto-jobs: number of threads must be > 0");
548 Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
549 Config->ZExecstack = hasZOption(Args, "execstack");
550 Config->ZNodelete = hasZOption(Args, "nodelete");
551 Config->ZNow = hasZOption(Args, "now");
552 Config->ZOrigin = hasZOption(Args, "origin");
553 Config->ZRelro = !hasZOption(Args, "norelro");
554 Config->ZStackSize = getZOptionValue(Args, "stack-size", -1);
555 Config->ZWxneeded = hasZOption(Args, "wxneeded");
557 Config->OFormatBinary = isOutputFormatBinary(Args);
558 Config->SectionStartMap = getSectionStartMap(Args);
559 Config->SortSection = getSortKind(Args);
560 Config->Target2 = getTarget2Option(Args);
561 Config->UnresolvedSymbols = getUnresolvedSymbolOption(Args);
563 // --omagic is an option to create old-fashioned executables in which
564 // .text segments are writable. Today, the option is still in use to
565 // create special-purpose programs such as boot loaders. It doesn't
566 // make sense to create PT_GNU_RELRO for such executables.
568 Config->ZRelro = false;
570 if (!Config->Relocatable)
571 Config->Strip = getStripOption(Args);
573 // Config->Pic is true if we are generating position-independent code.
574 Config->Pic = Config->Pie || Config->Shared;
576 if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
577 StringRef S = Arg->getValue();
579 Config->GnuHash = true;
580 Config->SysvHash = false;
581 } else if (S == "both") {
582 Config->GnuHash = true;
583 } else if (S != "sysv")
584 error("unknown hash style: " + S);
587 // Parse --build-id or --build-id=<style>.
588 if (Args.hasArg(OPT_build_id))
589 Config->BuildId = BuildIdKind::Fast;
590 if (auto *Arg = Args.getLastArg(OPT_build_id_eq)) {
591 StringRef S = Arg->getValue();
593 Config->BuildId = BuildIdKind::Md5;
594 } else if (S == "sha1" || S == "tree") {
595 Config->BuildId = BuildIdKind::Sha1;
596 } else if (S == "uuid") {
597 Config->BuildId = BuildIdKind::Uuid;
598 } else if (S == "none") {
599 Config->BuildId = BuildIdKind::None;
600 } else if (S.startswith("0x")) {
601 Config->BuildId = BuildIdKind::Hexstring;
602 Config->BuildIdVector = parseHex(S.substr(2));
604 error("unknown --build-id style: " + S);
608 for (auto *Arg : Args.filtered(OPT_auxiliary))
609 Config->AuxiliaryList.push_back(Arg->getValue());
610 if (!Config->Shared && !Config->AuxiliaryList.empty())
611 error("-f may not be used without -shared");
613 for (auto *Arg : Args.filtered(OPT_undefined))
614 Config->Undefined.push_back(Arg->getValue());
616 if (auto *Arg = Args.getLastArg(OPT_dynamic_list))
617 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
618 readDynamicList(*Buffer);
620 if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
621 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
622 Config->SymbolOrderingFile = getLines(*Buffer);
624 // If --retain-symbol-file is used, we'll retail only the symbols listed in
625 // the file and discard all others.
626 if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
627 Config->Discard = DiscardPolicy::RetainFile;
628 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
629 for (StringRef S : getLines(*Buffer))
630 Config->RetainSymbolsFile.insert(S);
633 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
634 Config->VersionScriptGlobals.push_back(
635 {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
637 // Dynamic lists are a simplified linker script that doesn't need the
638 // "global:" and implicitly ends with a "local:*". Set the variables needed to
640 if (Args.hasArg(OPT_dynamic_list) || Args.hasArg(OPT_export_dynamic_symbol)) {
641 Config->ExportDynamic = true;
643 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
646 if (auto *Arg = Args.getLastArg(OPT_version_script))
647 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
648 readVersionScript(*Buffer);
651 // Returns a value of "-format" option.
652 static bool getBinaryOption(StringRef S) {
655 if (S == "elf" || S == "default")
657 error("unknown -format value: " + S +
658 " (supported formats: elf, default, binary)");
662 void LinkerDriver::createFiles(opt::InputArgList &Args) {
663 for (auto *Arg : Args) {
664 switch (Arg->getOption().getID()) {
666 addLibrary(Arg->getValue());
669 addFile(Arg->getValue());
671 case OPT_alias_script_T:
673 if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue()))
674 readLinkerScript(*MB);
677 Config->AsNeeded = true;
680 InBinary = getBinaryOption(Arg->getValue());
682 case OPT_no_as_needed:
683 Config->AsNeeded = false;
686 Config->Static = true;
689 Config->Static = false;
691 case OPT_whole_archive:
692 InWholeArchive = true;
694 case OPT_no_whole_archive:
695 InWholeArchive = false;
706 if (Files.empty() && ErrorCount == 0)
707 error("no input files");
710 // If -m <machine_type> was not given, infer it from object files.
711 void LinkerDriver::inferMachineType() {
712 if (Config->EKind != ELFNoneKind)
715 for (InputFile *F : Files) {
716 if (F->EKind == ELFNoneKind)
718 Config->EKind = F->EKind;
719 Config->EMachine = F->EMachine;
720 Config->OSABI = F->OSABI;
721 Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
724 error("target emulation unknown: -m or at least one .o file required");
727 // Parse -z max-page-size=<value>. The default value is defined by
729 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
731 getZOptionValue(Args, "max-page-size", Target->DefaultMaxPageSize);
732 if (!isPowerOf2_64(Val))
733 error("max-page-size: value isn't a power of 2");
737 // Parses -image-base option.
738 static uint64_t getImageBase(opt::InputArgList &Args) {
739 // Use default if no -image-base option is given.
740 // Because we are using "Target" here, this function
741 // has to be called after the variable is initialized.
742 auto *Arg = Args.getLastArg(OPT_image_base);
744 return Config->Pic ? 0 : Target->DefaultImageBase;
746 StringRef S = Arg->getValue();
748 if (S.getAsInteger(0, V)) {
749 error("-image-base: number expected, but got " + S);
752 if ((V % Config->MaxPageSize) != 0)
753 warn("-image-base: address isn't multiple of page size: " + S);
757 // Do actual linking. Note that when this function is called,
758 // all linker scripts have already been parsed.
759 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
760 SymbolTable<ELFT> Symtab;
761 elf::Symtab<ELFT>::X = &Symtab;
762 Target = createTarget();
763 ScriptBase = Script<ELFT>::X = make<LinkerScript<ELFT>>();
766 ELFT::Is64Bits || Config->EMachine == EM_X86_64 || Config->MipsN32Abi;
768 (Config->EMachine == EM_MIPS && Config->EKind == ELF64LEKind);
769 Config->MaxPageSize = getMaxPageSize(Args);
770 Config->ImageBase = getImageBase(Args);
772 // Default output filename is "a.out" by the Unix tradition.
773 if (Config->OutputFile.empty())
774 Config->OutputFile = "a.out";
776 // Use default entry point name if no name was given via the command
777 // line nor linker scripts. For some reason, MIPS entry point name is
778 // different from others.
779 Config->WarnMissingEntry =
780 (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
781 if (Config->Entry.empty() && !Config->Relocatable)
782 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
784 // Handle --trace-symbol.
785 for (auto *Arg : Args.filtered(OPT_trace_symbol))
786 Symtab.trace(Arg->getValue());
788 // Add all files to the symbol table. This will add almost all
789 // symbols that we need to the symbol table.
790 for (InputFile *F : Files)
793 // If an entry symbol is in a static archive, pull out that file now
794 // to complete the symbol table. After this, no new names except a
795 // few linker-synthesized ones will be added to the symbol table.
796 if (Symtab.find(Config->Entry))
797 Symtab.addUndefined(Config->Entry);
799 // Return if there were name resolution errors.
803 Symtab.scanUndefinedFlags();
804 Symtab.scanShlibUndefined();
805 Symtab.scanVersionScript();
807 Symtab.addCombinedLTOObject();
811 for (auto *Arg : Args.filtered(OPT_wrap))
812 Symtab.wrap(Arg->getValue());
814 // Now that we have a complete list of input files.
815 // Beyond this point, no new files are added.
816 // Aggregate all input sections into one place.
817 for (elf::ObjectFile<ELFT> *F : Symtab.getObjectFiles())
818 for (InputSectionBase<ELFT> *S : F->getSections())
819 if (S && S != &InputSection<ELFT>::Discarded)
820 Symtab.Sections.push_back(S);
821 for (BinaryFile *F : Symtab.getBinaryFiles())
822 for (InputSectionData *S : F->getSections())
823 Symtab.Sections.push_back(cast<InputSection<ELFT>>(S));
825 // Do size optimizations: garbage collection and identical code folding.
826 if (Config->GcSections)
831 // MergeInputSection::splitIntoPieces needs to be called before
832 // any call of MergeInputSection::getOffset. Do that.
833 forEach(Symtab.Sections.begin(), Symtab.Sections.end(),
834 [](InputSectionBase<ELFT> *S) {
837 if (Decompressor::isCompressedELFSection(S->Flags, S->Name))
839 if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(S))
840 MS->splitIntoPieces();
843 // Write the result to the file.