1 //===- Driver.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The driver drives the entire linking process. It is responsible for
11 // parsing command line options and doing whatever it is instructed to do.
13 // One notable thing in the LLD's driver when compared to other linkers is
14 // that the LLD's driver is agnostic on the host operating system.
15 // Other linkers usually have implicit default values (such as a dynamic
16 // linker path or library paths) for each host OS.
18 // I don't think implicit default values are useful because they are
19 // usually explicitly specified by the compiler driver. They can even
20 // be harmful when you are doing cross-linking. Therefore, in LLD, we
21 // simply trust the compiler driver to pass all required options and
22 // don't try to make effort on our side.
24 //===----------------------------------------------------------------------===//
29 #include "Filesystem.h"
31 #include "InputFiles.h"
32 #include "InputSection.h"
33 #include "LinkerScript.h"
35 #include "OutputSections.h"
36 #include "ScriptParser.h"
38 #include "SymbolTable.h"
39 #include "SyntheticSections.h"
43 #include "lld/Config/Version.h"
44 #include "lld/Driver/Driver.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/StringSwitch.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Compression.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/TarWriter.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/raw_ostream.h"
57 using namespace llvm::ELF;
58 using namespace llvm::object;
59 using namespace llvm::sys;
62 using namespace lld::elf;
64 Configuration *elf::Config;
65 LinkerDriver *elf::Driver;
67 BumpPtrAllocator elf::BAlloc;
68 StringSaver elf::Saver{BAlloc};
69 std::vector<SpecificAllocBase *> elf::SpecificAllocBase::Instances;
71 static void setConfigs();
73 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
78 InputSections.clear();
81 Config = make<Configuration>();
82 Driver = make<LinkerDriver>();
83 Script = make<LinkerScript>();
85 Driver->main(Args, CanExitEarly);
90 // Parses a linker -m option.
91 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
94 if (S.endswith("_fbsd")) {
96 OSABI = ELFOSABI_FREEBSD;
99 std::pair<ELFKind, uint16_t> Ret =
100 StringSwitch<std::pair<ELFKind, uint16_t>>(S)
101 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
102 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
103 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
104 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
105 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
106 .Case("elf32ppc", {ELF32BEKind, EM_PPC})
107 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
108 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
109 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
110 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
111 .Case("elf_i386", {ELF32LEKind, EM_386})
112 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
113 .Default({ELFNoneKind, EM_NONE});
115 if (Ret.first == ELFNoneKind) {
116 if (S == "i386pe" || S == "i386pep" || S == "thumb2pe")
117 error("Windows targets are not supported on the ELF frontend: " + Emul);
119 error("unknown emulation: " + Emul);
121 return std::make_tuple(Ret.first, Ret.second, OSABI);
124 // Returns slices of MB by parsing MB as an archive file.
125 // Each slice consists of a member file in the archive.
126 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
127 MemoryBufferRef MB) {
128 std::unique_ptr<Archive> File =
129 check(Archive::create(MB),
130 MB.getBufferIdentifier() + ": failed to parse archive");
132 std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
133 Error Err = Error::success();
134 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
136 check(COrErr, MB.getBufferIdentifier() +
137 ": could not get the child of the archive");
138 MemoryBufferRef MBRef =
139 check(C.getMemoryBufferRef(),
140 MB.getBufferIdentifier() +
141 ": could not get the buffer for a child of the archive");
142 V.push_back(std::make_pair(MBRef, C.getChildOffset()));
145 fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
146 toString(std::move(Err)));
148 // Take ownership of memory buffers created for members of thin archives.
149 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
150 make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
155 // Opens a file and create a file object. Path has to be resolved already.
156 void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
157 using namespace sys::fs;
159 Optional<MemoryBufferRef> Buffer = readFile(Path);
160 if (!Buffer.hasValue())
162 MemoryBufferRef MBRef = *Buffer;
165 Files.push_back(make<BinaryFile>(MBRef));
169 switch (identify_magic(MBRef.getBuffer())) {
170 case file_magic::unknown:
171 readLinkerScript(MBRef);
173 case file_magic::archive: {
174 // Handle -whole-archive.
175 if (InWholeArchive) {
176 for (const auto &P : getArchiveMembers(MBRef))
177 Files.push_back(createObjectFile(P.first, Path, P.second));
181 std::unique_ptr<Archive> File =
182 check(Archive::create(MBRef), Path + ": failed to parse archive");
184 // If an archive file has no symbol table, it is likely that a user
185 // is attempting LTO and using a default ar command that doesn't
186 // understand the LLVM bitcode file. It is a pretty common error, so
187 // we'll handle it as if it had a symbol table.
188 if (!File->isEmpty() && !File->hasSymbolTable()) {
189 for (const auto &P : getArchiveMembers(MBRef))
190 Files.push_back(make<LazyObjectFile>(P.first, Path, P.second));
194 // Handle the regular case.
195 Files.push_back(make<ArchiveFile>(std::move(File)));
198 case file_magic::elf_shared_object:
199 if (Config->Relocatable) {
200 error("attempted static link of dynamic object " + Path);
203 // DSOs usually have DT_SONAME tags in their ELF headers, and the
204 // sonames are used to identify DSOs. But if they are missing,
205 // they are identified by filenames. We don't know whether the new
206 // file has a DT_SONAME or not because we haven't parsed it yet.
207 // Here, we set the default soname for the file because we might
210 // If a file was specified by -lfoo, the directory part is not
211 // significant, as a user did not specify it. This behavior is
212 // compatible with GNU.
213 Files.push_back(createSharedFile(
214 MBRef, WithLOption ? sys::path::filename(Path) : Path));
218 Files.push_back(make<LazyObjectFile>(MBRef, "", 0));
220 Files.push_back(createObjectFile(MBRef));
224 // Add a given library by searching it from input search paths.
225 void LinkerDriver::addLibrary(StringRef Name) {
226 if (Optional<std::string> Path = searchLibrary(Name))
227 addFile(*Path, /*WithLOption=*/true);
229 error("unable to find library -l" + Name);
232 // This function is called on startup. We need this for LTO since
233 // LTO calls LLVM functions to compile bitcode files to native code.
234 // Technically this can be delayed until we read bitcode files, but
235 // we don't bother to do lazily because the initialization is fast.
236 static void initLLVM(opt::InputArgList &Args) {
237 InitializeAllTargets();
238 InitializeAllTargetMCs();
239 InitializeAllAsmPrinters();
240 InitializeAllAsmParsers();
242 // Parse and evaluate -mllvm options.
243 std::vector<const char *> V;
244 V.push_back("lld (LLVM option parsing)");
245 for (auto *Arg : Args.filtered(OPT_mllvm))
246 V.push_back(Arg->getValue());
247 cl::ParseCommandLineOptions(V.size(), V.data());
250 // Some command line options or some combinations of them are not allowed.
251 // This function checks for such errors.
252 static void checkOptions(opt::InputArgList &Args) {
253 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
254 // table which is a relatively new feature.
255 if (Config->EMachine == EM_MIPS && Config->GnuHash)
256 error("the .gnu.hash section is not compatible with the MIPS target.");
258 if (Config->Pie && Config->Shared)
259 error("-shared and -pie may not be used together");
261 if (!Config->Shared && !Config->AuxiliaryList.empty())
262 error("-f may not be used without -shared");
264 if (Config->Relocatable) {
266 error("-r and -shared may not be used together");
267 if (Config->GcSections)
268 error("-r and --gc-sections may not be used together");
270 error("-r and --icf may not be used together");
272 error("-r and -pie may not be used together");
276 static int getInteger(opt::InputArgList &Args, unsigned Key, int Default) {
278 if (auto *Arg = Args.getLastArg(Key)) {
279 StringRef S = Arg->getValue();
280 if (!to_integer(S, V, 10))
281 error(Arg->getSpelling() + ": number expected, but got " + S);
286 static const char *getReproduceOption(opt::InputArgList &Args) {
287 if (auto *Arg = Args.getLastArg(OPT_reproduce))
288 return Arg->getValue();
289 return getenv("LLD_REPRODUCE");
292 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
293 for (auto *Arg : Args.filtered(OPT_z))
294 if (Key == Arg->getValue())
299 static uint64_t getZOptionValue(opt::InputArgList &Args, StringRef Key,
301 for (auto *Arg : Args.filtered(OPT_z)) {
302 std::pair<StringRef, StringRef> KV = StringRef(Arg->getValue()).split('=');
303 if (KV.first == Key) {
305 if (!to_integer(KV.second, Result))
306 error("invalid " + Key + ": " + KV.second);
313 void LinkerDriver::main(ArrayRef<const char *> ArgsArr, bool CanExitEarly) {
315 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
317 // Interpret this flag early because error() depends on them.
318 Config->ErrorLimit = getInteger(Args, OPT_error_limit, 20);
321 if (Args.hasArg(OPT_help)) {
322 printHelp(ArgsArr[0]);
326 // Handle -v or -version.
328 // A note about "compatible with GNU linkers" message: this is a hack for
329 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
330 // still the newest version in March 2017) or earlier to recognize LLD as
331 // a GNU compatible linker. As long as an output for the -v option
332 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
334 // This is somewhat ugly hack, but in reality, we had no choice other
335 // than doing this. Considering the very long release cycle of Libtool,
336 // it is not easy to improve it to recognize LLD as a GNU compatible
337 // linker in a timely manner. Even if we can make it, there are still a
338 // lot of "configure" scripts out there that are generated by old version
339 // of Libtool. We cannot convince every software developer to migrate to
340 // the latest version and re-generate scripts. So we have this hack.
341 if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
342 message(getLLDVersion() + " (compatible with GNU linkers)");
344 // ld.bfd always exits after printing out the version string.
345 // ld.gold proceeds if a given option is -v. Because gold's behavior
346 // is more permissive than ld.bfd, we chose what gold does here.
347 if (Args.hasArg(OPT_version))
350 Config->ExitEarly = CanExitEarly && !Args.hasArg(OPT_full_shutdown);
352 if (const char *Path = getReproduceOption(Args)) {
353 // Note that --reproduce is a debug option so you can ignore it
354 // if you are trying to understand the whole picture of the code.
355 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
356 TarWriter::create(Path, path::stem(Path));
358 Tar = ErrOrWriter->get();
359 Tar->append("response.txt", createResponseFile(Args));
360 Tar->append("version.txt", getLLDVersion() + "\n");
361 make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
363 error(Twine("--reproduce: failed to open ") + Path + ": " +
364 toString(ErrOrWriter.takeError()));
377 switch (Config->EKind) {
391 llvm_unreachable("unknown Config->EKind");
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 std::vector<StringRef> getArgs(opt::InputArgList &Args, int Id) {
403 std::vector<StringRef> V;
404 for (auto *Arg : Args.filtered(Id))
405 V.push_back(Arg->getValue());
409 static std::string getRpath(opt::InputArgList &Args) {
410 std::vector<StringRef> V = getArgs(Args, OPT_rpath);
411 return llvm::join(V.begin(), V.end(), ":");
414 // Determines what we should do if there are remaining unresolved
415 // symbols after the name resolution.
416 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
417 // -noinhibit-exec or -r imply some default values.
418 if (Args.hasArg(OPT_noinhibit_exec))
419 return UnresolvedPolicy::WarnAll;
420 if (Args.hasArg(OPT_relocatable))
421 return UnresolvedPolicy::IgnoreAll;
423 UnresolvedPolicy ErrorOrWarn = getArg(Args, OPT_error_unresolved_symbols,
424 OPT_warn_unresolved_symbols, true)
425 ? UnresolvedPolicy::ReportError
426 : UnresolvedPolicy::Warn;
428 // Process the last of -unresolved-symbols, -no-undefined or -z defs.
429 for (auto *Arg : llvm::reverse(Args)) {
430 switch (Arg->getOption().getID()) {
431 case OPT_unresolved_symbols: {
432 StringRef S = Arg->getValue();
433 if (S == "ignore-all" || S == "ignore-in-object-files")
434 return UnresolvedPolicy::Ignore;
435 if (S == "ignore-in-shared-libs" || S == "report-all")
437 error("unknown --unresolved-symbols value: " + S);
440 case OPT_no_undefined:
443 if (StringRef(Arg->getValue()) == "defs")
449 // -shared implies -unresolved-symbols=ignore-all because missing
450 // symbols are likely to be resolved at runtime using other DSOs.
452 return UnresolvedPolicy::Ignore;
456 static Target2Policy getTarget2(opt::InputArgList &Args) {
457 StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
459 return Target2Policy::Rel;
461 return Target2Policy::Abs;
463 return Target2Policy::GotRel;
464 error("unknown --target2 option: " + S);
465 return Target2Policy::GotRel;
468 static bool isOutputFormatBinary(opt::InputArgList &Args) {
469 if (auto *Arg = Args.getLastArg(OPT_oformat)) {
470 StringRef S = Arg->getValue();
473 error("unknown --oformat value: " + S);
478 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
479 if (Args.hasArg(OPT_relocatable))
480 return DiscardPolicy::None;
483 Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
485 return DiscardPolicy::Default;
486 if (Arg->getOption().getID() == OPT_discard_all)
487 return DiscardPolicy::All;
488 if (Arg->getOption().getID() == OPT_discard_locals)
489 return DiscardPolicy::Locals;
490 return DiscardPolicy::None;
493 static StringRef getDynamicLinker(opt::InputArgList &Args) {
494 auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
495 if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
497 return Arg->getValue();
500 static StripPolicy getStrip(opt::InputArgList &Args) {
501 if (Args.hasArg(OPT_relocatable))
502 return StripPolicy::None;
504 auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
506 return StripPolicy::None;
507 if (Arg->getOption().getID() == OPT_strip_all)
508 return StripPolicy::All;
509 return StripPolicy::Debug;
512 static uint64_t parseSectionAddress(StringRef S, opt::Arg *Arg) {
514 if (S.startswith("0x"))
516 if (!to_integer(S, VA, 16))
517 error("invalid argument: " + toString(Arg));
521 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
522 StringMap<uint64_t> Ret;
523 for (auto *Arg : Args.filtered(OPT_section_start)) {
526 std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
527 Ret[Name] = parseSectionAddress(Addr, Arg);
530 if (auto *Arg = Args.getLastArg(OPT_Ttext))
531 Ret[".text"] = parseSectionAddress(Arg->getValue(), Arg);
532 if (auto *Arg = Args.getLastArg(OPT_Tdata))
533 Ret[".data"] = parseSectionAddress(Arg->getValue(), Arg);
534 if (auto *Arg = Args.getLastArg(OPT_Tbss))
535 Ret[".bss"] = parseSectionAddress(Arg->getValue(), Arg);
539 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
540 StringRef S = Args.getLastArgValue(OPT_sort_section);
541 if (S == "alignment")
542 return SortSectionPolicy::Alignment;
544 return SortSectionPolicy::Name;
546 error("unknown --sort-section rule: " + S);
547 return SortSectionPolicy::Default;
550 static std::pair<bool, bool> getHashStyle(opt::InputArgList &Args) {
551 StringRef S = Args.getLastArgValue(OPT_hash_style, "sysv");
553 return {true, false};
555 return {false, true};
557 error("unknown -hash-style: " + S);
561 // Parse --build-id or --build-id=<style>. We handle "tree" as a
562 // synonym for "sha1" because all our hash functions including
563 // -build-id=sha1 are actually tree hashes for performance reasons.
564 static std::pair<BuildIdKind, std::vector<uint8_t>>
565 getBuildId(opt::InputArgList &Args) {
566 auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
568 return {BuildIdKind::None, {}};
570 if (Arg->getOption().getID() == OPT_build_id)
571 return {BuildIdKind::Fast, {}};
573 StringRef S = Arg->getValue();
575 return {BuildIdKind::Md5, {}};
576 if (S == "sha1" || S == "tree")
577 return {BuildIdKind::Sha1, {}};
579 return {BuildIdKind::Uuid, {}};
580 if (S.startswith("0x"))
581 return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
584 error("unknown --build-id style: " + S);
585 return {BuildIdKind::None, {}};
588 static std::vector<StringRef> getLines(MemoryBufferRef MB) {
589 SmallVector<StringRef, 0> Arr;
590 MB.getBuffer().split(Arr, '\n');
592 std::vector<StringRef> Ret;
593 for (StringRef S : Arr) {
601 static bool getCompressDebugSections(opt::InputArgList &Args) {
602 StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
606 error("unknown --compress-debug-sections value: " + S);
607 if (!zlib::isAvailable())
608 error("--compress-debug-sections: zlib is not available");
612 // Initializes Config members by the command line options.
613 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
614 Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
615 Config->AuxiliaryList = getArgs(Args, OPT_auxiliary);
616 Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
617 Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
618 Config->CompressDebugSections = getCompressDebugSections(Args);
619 Config->DefineCommon = getArg(Args, OPT_define_common, OPT_no_define_common,
620 !Args.hasArg(OPT_relocatable));
621 Config->Demangle = getArg(Args, OPT_demangle, OPT_no_demangle, true);
622 Config->DisableVerify = Args.hasArg(OPT_disable_verify);
623 Config->Discard = getDiscard(Args);
624 Config->DynamicLinker = getDynamicLinker(Args);
625 Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
626 Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
627 Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
628 Config->Entry = Args.getLastArgValue(OPT_entry);
629 Config->ExportDynamic =
630 getArg(Args, OPT_export_dynamic, OPT_no_export_dynamic, false);
631 Config->FatalWarnings =
632 getArg(Args, OPT_fatal_warnings, OPT_no_fatal_warnings, false);
633 Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
634 Config->GcSections = getArg(Args, OPT_gc_sections, OPT_no_gc_sections, false);
635 Config->GdbIndex = Args.hasArg(OPT_gdb_index);
636 Config->ICF = Args.hasArg(OPT_icf);
637 Config->Init = Args.getLastArgValue(OPT_init, "_init");
638 Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
639 Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
640 Config->LTOO = getInteger(Args, OPT_lto_O, 2);
641 Config->LTOPartitions = getInteger(Args, OPT_lto_partitions, 1);
642 Config->MapFile = Args.getLastArgValue(OPT_Map);
643 Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
644 Config->NoUndefinedVersion = Args.hasArg(OPT_no_undefined_version);
645 Config->Nostdlib = Args.hasArg(OPT_nostdlib);
646 Config->OFormatBinary = isOutputFormatBinary(Args);
647 Config->Omagic = Args.hasArg(OPT_omagic);
648 Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
649 Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
650 Config->Optimize = getInteger(Args, OPT_O, 1);
651 Config->OutputFile = Args.getLastArgValue(OPT_o);
652 Config->Pie = getArg(Args, OPT_pie, OPT_nopie, false);
653 Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
654 Config->Rpath = getRpath(Args);
655 Config->Relocatable = Args.hasArg(OPT_relocatable);
656 Config->SaveTemps = Args.hasArg(OPT_save_temps);
657 Config->SearchPaths = getArgs(Args, OPT_L);
658 Config->SectionStartMap = getSectionStartMap(Args);
659 Config->Shared = Args.hasArg(OPT_shared);
660 Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
661 Config->SoName = Args.getLastArgValue(OPT_soname);
662 Config->SortSection = getSortSection(Args);
663 Config->Strip = getStrip(Args);
664 Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
665 Config->Target1Rel = getArg(Args, OPT_target1_rel, OPT_target1_abs, false);
666 Config->Target2 = getTarget2(Args);
667 Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
668 Config->ThinLTOCachePolicy = check(
669 parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
670 "--thinlto-cache-policy: invalid cache policy");
671 Config->ThinLTOJobs = getInteger(Args, OPT_thinlto_jobs, -1u);
672 Config->Threads = getArg(Args, OPT_threads, OPT_no_threads, true);
673 Config->Trace = Args.hasArg(OPT_trace);
674 Config->Undefined = getArgs(Args, OPT_undefined);
675 Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
676 Config->Verbose = Args.hasArg(OPT_verbose);
677 Config->WarnCommon = Args.hasArg(OPT_warn_common);
678 Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
679 Config->ZExecstack = hasZOption(Args, "execstack");
680 Config->ZNocopyreloc = hasZOption(Args, "nocopyreloc");
681 Config->ZNodelete = hasZOption(Args, "nodelete");
682 Config->ZNodlopen = hasZOption(Args, "nodlopen");
683 Config->ZNow = hasZOption(Args, "now");
684 Config->ZOrigin = hasZOption(Args, "origin");
685 Config->ZRelro = !hasZOption(Args, "norelro");
686 Config->ZRodynamic = hasZOption(Args, "rodynamic");
687 Config->ZStackSize = getZOptionValue(Args, "stack-size", 0);
688 Config->ZText = !hasZOption(Args, "notext");
689 Config->ZWxneeded = hasZOption(Args, "wxneeded");
691 if (Config->LTOO > 3)
692 error("invalid optimization level for LTO: " +
693 Args.getLastArgValue(OPT_lto_O));
694 if (Config->LTOPartitions == 0)
695 error("--lto-partitions: number of threads must be > 0");
696 if (Config->ThinLTOJobs == 0)
697 error("--thinlto-jobs: number of threads must be > 0");
699 if (auto *Arg = Args.getLastArg(OPT_m)) {
700 // Parse ELF{32,64}{LE,BE} and CPU type.
701 StringRef S = Arg->getValue();
702 std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
704 Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
705 Config->Emulation = S;
708 if (Args.hasArg(OPT_print_map))
709 Config->MapFile = "-";
711 // --omagic is an option to create old-fashioned executables in which
712 // .text segments are writable. Today, the option is still in use to
713 // create special-purpose programs such as boot loaders. It doesn't
714 // make sense to create PT_GNU_RELRO for such executables.
716 Config->ZRelro = false;
718 std::tie(Config->SysvHash, Config->GnuHash) = getHashStyle(Args);
719 std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
721 if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
722 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
723 Config->SymbolOrderingFile = getLines(*Buffer);
725 // If --retain-symbol-file is used, we'll keep only the symbols listed in
726 // the file and discard all others.
727 if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
728 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
729 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
730 for (StringRef S : getLines(*Buffer))
731 Config->VersionScriptGlobals.push_back(
732 {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
735 bool HasExportDynamic =
736 getArg(Args, OPT_export_dynamic, OPT_no_export_dynamic, false);
738 // Parses -dynamic-list and -export-dynamic-symbol. They make some
739 // symbols private. Note that -export-dynamic takes precedence over them
740 // as it says all symbols should be exported.
741 if (!HasExportDynamic) {
742 for (auto *Arg : Args.filtered(OPT_dynamic_list))
743 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
744 readDynamicList(*Buffer);
746 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
747 Config->VersionScriptGlobals.push_back(
748 {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
750 // Dynamic lists are a simplified linker script that doesn't need the
751 // "global:" and implicitly ends with a "local:*". Set the variables
752 // needed to simulate that.
753 if (Args.hasArg(OPT_dynamic_list) ||
754 Args.hasArg(OPT_export_dynamic_symbol)) {
755 Config->ExportDynamic = true;
757 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
761 if (auto *Arg = Args.getLastArg(OPT_version_script))
762 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
763 readVersionScript(*Buffer);
766 // Some Config members do not directly correspond to any particular
767 // command line options, but computed based on other Config values.
768 // This function initialize such members. See Config.h for the details
770 static void setConfigs() {
771 ELFKind Kind = Config->EKind;
772 uint16_t Machine = Config->EMachine;
774 // There is an ILP32 ABI for x86-64, although it's not very popular.
775 // It is called the x32 ABI.
776 bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64);
778 Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
779 Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind);
780 Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind);
782 Config->IsLE ? support::endianness::little : support::endianness::big;
783 Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS);
784 Config->IsRela = Config->Is64 || IsX32 || Config->MipsN32Abi;
785 Config->Pic = Config->Pie || Config->Shared;
786 Config->Wordsize = Config->Is64 ? 8 : 4;
789 // Returns a value of "-format" option.
790 static bool getBinaryOption(StringRef S) {
793 if (S == "elf" || S == "default")
795 error("unknown -format value: " + S +
796 " (supported formats: elf, default, binary)");
800 void LinkerDriver::createFiles(opt::InputArgList &Args) {
801 for (auto *Arg : Args) {
802 switch (Arg->getOption().getID()) {
804 addLibrary(Arg->getValue());
807 addFile(Arg->getValue(), /*WithLOption=*/false);
809 case OPT_alias_script_T:
811 if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue()))
812 readLinkerScript(*MB);
815 Config->AsNeeded = true;
818 InBinary = getBinaryOption(Arg->getValue());
820 case OPT_no_as_needed:
821 Config->AsNeeded = false;
824 Config->Static = true;
827 Config->Static = false;
829 case OPT_whole_archive:
830 InWholeArchive = true;
832 case OPT_no_whole_archive:
833 InWholeArchive = false;
844 if (Files.empty() && ErrorCount == 0)
845 error("no input files");
848 // If -m <machine_type> was not given, infer it from object files.
849 void LinkerDriver::inferMachineType() {
850 if (Config->EKind != ELFNoneKind)
853 for (InputFile *F : Files) {
854 if (F->EKind == ELFNoneKind)
856 Config->EKind = F->EKind;
857 Config->EMachine = F->EMachine;
858 Config->OSABI = F->OSABI;
859 Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
862 error("target emulation unknown: -m or at least one .o file required");
865 // Parse -z max-page-size=<value>. The default value is defined by
867 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
869 getZOptionValue(Args, "max-page-size", Target->DefaultMaxPageSize);
870 if (!isPowerOf2_64(Val))
871 error("max-page-size: value isn't a power of 2");
875 // Parses -image-base option.
876 static uint64_t getImageBase(opt::InputArgList &Args) {
877 // Use default if no -image-base option is given.
878 // Because we are using "Target" here, this function
879 // has to be called after the variable is initialized.
880 auto *Arg = Args.getLastArg(OPT_image_base);
882 return Config->Pic ? 0 : Target->DefaultImageBase;
884 StringRef S = Arg->getValue();
886 if (!to_integer(S, V)) {
887 error("-image-base: number expected, but got " + S);
890 if ((V % Config->MaxPageSize) != 0)
891 warn("-image-base: address isn't multiple of page size: " + S);
895 // Parses --defsym=alias option.
896 static std::vector<std::pair<StringRef, StringRef>>
897 getDefsym(opt::InputArgList &Args) {
898 std::vector<std::pair<StringRef, StringRef>> Ret;
899 for (auto *Arg : Args.filtered(OPT_defsym)) {
902 std::tie(From, To) = StringRef(Arg->getValue()).split('=');
903 if (!isValidCIdentifier(To))
904 error("--defsym: symbol name expected, but got " + To);
905 Ret.push_back({From, To});
910 // Do actual linking. Note that when this function is called,
911 // all linker scripts have already been parsed.
912 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
913 SymbolTable<ELFT> Symtab;
914 elf::Symtab<ELFT>::X = &Symtab;
915 Target = createTarget();
917 Config->MaxPageSize = getMaxPageSize(Args);
918 Config->ImageBase = getImageBase(Args);
920 // Default output filename is "a.out" by the Unix tradition.
921 if (Config->OutputFile.empty())
922 Config->OutputFile = "a.out";
924 // Fail early if the output file or map file is not writable. If a user has a
925 // long link, e.g. due to a large LTO link, they do not wish to run it and
926 // find that it failed because there was a mistake in their command-line.
927 if (auto E = tryCreateFile(Config->OutputFile))
928 error("cannot open output file " + Config->OutputFile + ": " + E.message());
929 if (auto E = tryCreateFile(Config->MapFile))
930 error("cannot open map file " + Config->MapFile + ": " + E.message());
934 // Use default entry point name if no name was given via the command
935 // line nor linker scripts. For some reason, MIPS entry point name is
936 // different from others.
937 Config->WarnMissingEntry =
938 (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
939 if (Config->Entry.empty() && !Config->Relocatable)
940 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
942 // Handle --trace-symbol.
943 for (auto *Arg : Args.filtered(OPT_trace_symbol))
944 Symtab.trace(Arg->getValue());
946 // Add all files to the symbol table. This will add almost all
947 // symbols that we need to the symbol table.
948 for (InputFile *F : Files)
951 // If an entry symbol is in a static archive, pull out that file now
952 // to complete the symbol table. After this, no new names except a
953 // few linker-synthesized ones will be added to the symbol table.
954 if (Symtab.find(Config->Entry))
955 Symtab.addUndefined(Config->Entry);
957 // Return if there were name resolution errors.
961 Symtab.scanUndefinedFlags();
962 Symtab.scanShlibUndefined();
963 Symtab.scanVersionScript();
965 // Create wrapped symbols for -wrap option.
966 for (auto *Arg : Args.filtered(OPT_wrap))
967 Symtab.addSymbolWrap(Arg->getValue());
969 // Create alias symbols for -defsym option.
970 for (std::pair<StringRef, StringRef> &Def : getDefsym(Args))
971 Symtab.addSymbolAlias(Def.first, Def.second);
973 Symtab.addCombinedLTOObject();
977 // Some symbols (such as __ehdr_start) are defined lazily only when there
978 // are undefined symbols for them, so we add these to trigger that logic.
979 for (StringRef Sym : Script->Opt.ReferencedSymbols)
980 Symtab.addUndefined(Sym);
982 // Apply symbol renames for -wrap and -defsym
983 Symtab.applySymbolRenames();
985 // Now that we have a complete list of input files.
986 // Beyond this point, no new files are added.
987 // Aggregate all input sections into one place.
988 for (elf::ObjectFile<ELFT> *F : Symtab.getObjectFiles())
989 for (InputSectionBase *S : F->getSections())
990 if (S && S != &InputSection::Discarded)
991 InputSections.push_back(S);
992 for (BinaryFile *F : Symtab.getBinaryFiles())
993 for (InputSectionBase *S : F->getSections())
994 InputSections.push_back(cast<InputSection>(S));
996 // This adds a .comment section containing a version string. We have to add it
997 // before decompressAndMergeSections because the .comment section is a
998 // mergeable section.
999 if (!Config->Relocatable)
1000 InputSections.push_back(createCommentSection<ELFT>());
1002 // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1003 // and identical code folding.
1004 if (Config->GcSections)
1006 decompressAndMergeSections();
1010 // Write the result to the file.
1011 writeResult<ELFT>();