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 //===----------------------------------------------------------------------===//
28 #include "Filesystem.h"
30 #include "InputFiles.h"
31 #include "InputSection.h"
32 #include "LinkerScript.h"
33 #include "OutputSections.h"
34 #include "ScriptParser.h"
36 #include "SymbolTable.h"
38 #include "SyntheticSections.h"
41 #include "lld/Common/Args.h"
42 #include "lld/Common/Driver.h"
43 #include "lld/Common/ErrorHandler.h"
44 #include "lld/Common/Memory.h"
45 #include "lld/Common/Threads.h"
46 #include "lld/Common/Version.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/ADT/StringSwitch.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compression.h"
51 #include "llvm/Support/Path.h"
52 #include "llvm/Support/TarWriter.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/raw_ostream.h"
59 using namespace llvm::ELF;
60 using namespace llvm::object;
61 using namespace llvm::sys;
64 using namespace lld::elf;
66 Configuration *elf::Config;
67 LinkerDriver *elf::Driver;
69 static void setConfigs();
71 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
73 errorHandler().LogName = Args[0];
74 errorHandler().ErrorLimitExceededMsg =
75 "too many errors emitted, stopping now (use "
76 "-error-limit=0 to see all errors)";
77 errorHandler().ErrorOS = &Error;
78 errorHandler().ColorDiagnostics = Error.has_colors();
79 InputSections.clear();
80 OutputSections.clear();
87 Config = make<Configuration>();
88 Driver = make<LinkerDriver>();
89 Script = make<LinkerScript>();
90 Symtab = make<SymbolTable>();
91 Config->Argv = {Args.begin(), Args.end()};
93 Driver->main(Args, CanExitEarly);
95 // Exit immediately if we don't need to return to the caller.
96 // This saves time because the overhead of calling destructors
97 // for all globally-allocated objects is not negligible.
98 if (Config->ExitEarly)
99 exitLld(errorCount() ? 1 : 0);
102 return !errorCount();
105 // Parses a linker -m option.
106 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
109 if (S.endswith("_fbsd")) {
111 OSABI = ELFOSABI_FREEBSD;
114 std::pair<ELFKind, uint16_t> Ret =
115 StringSwitch<std::pair<ELFKind, uint16_t>>(S)
116 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
117 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
118 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
119 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
120 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
121 .Case("elf32ppc", {ELF32BEKind, EM_PPC})
122 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
123 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
124 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
125 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
126 .Case("elf_i386", {ELF32LEKind, EM_386})
127 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
128 .Default({ELFNoneKind, EM_NONE});
130 if (Ret.first == ELFNoneKind)
131 error("unknown emulation: " + Emul);
132 return std::make_tuple(Ret.first, Ret.second, OSABI);
135 // Returns slices of MB by parsing MB as an archive file.
136 // Each slice consists of a member file in the archive.
137 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
138 MemoryBufferRef MB) {
139 std::unique_ptr<Archive> File =
140 CHECK(Archive::create(MB),
141 MB.getBufferIdentifier() + ": failed to parse archive");
143 std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
144 Error Err = Error::success();
145 bool AddToTar = File->isThin() && Tar;
146 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
148 CHECK(COrErr, MB.getBufferIdentifier() +
149 ": could not get the child of the archive");
150 MemoryBufferRef MBRef =
151 CHECK(C.getMemoryBufferRef(),
152 MB.getBufferIdentifier() +
153 ": could not get the buffer for a child of the archive");
155 Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer());
156 V.push_back(std::make_pair(MBRef, C.getChildOffset()));
159 fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
160 toString(std::move(Err)));
162 // Take ownership of memory buffers created for members of thin archives.
163 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
164 make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
169 // Opens a file and create a file object. Path has to be resolved already.
170 void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
171 using namespace sys::fs;
173 Optional<MemoryBufferRef> Buffer = readFile(Path);
174 if (!Buffer.hasValue())
176 MemoryBufferRef MBRef = *Buffer;
179 Files.push_back(make<BinaryFile>(MBRef));
183 switch (identify_magic(MBRef.getBuffer())) {
184 case file_magic::unknown:
185 readLinkerScript(MBRef);
187 case file_magic::archive: {
188 // Handle -whole-archive.
189 if (InWholeArchive) {
190 for (const auto &P : getArchiveMembers(MBRef))
191 Files.push_back(createObjectFile(P.first, Path, P.second));
195 std::unique_ptr<Archive> File =
196 CHECK(Archive::create(MBRef), Path + ": failed to parse archive");
198 // If an archive file has no symbol table, it is likely that a user
199 // is attempting LTO and using a default ar command that doesn't
200 // understand the LLVM bitcode file. It is a pretty common error, so
201 // we'll handle it as if it had a symbol table.
202 if (!File->isEmpty() && !File->hasSymbolTable()) {
203 for (const auto &P : getArchiveMembers(MBRef))
204 Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
208 // Handle the regular case.
209 Files.push_back(make<ArchiveFile>(std::move(File)));
212 case file_magic::elf_shared_object:
213 if (Config->Relocatable) {
214 error("attempted static link of dynamic object " + Path);
218 // DSOs usually have DT_SONAME tags in their ELF headers, and the
219 // sonames are used to identify DSOs. But if they are missing,
220 // they are identified by filenames. We don't know whether the new
221 // file has a DT_SONAME or not because we haven't parsed it yet.
222 // Here, we set the default soname for the file because we might
225 // If a file was specified by -lfoo, the directory part is not
226 // significant, as a user did not specify it. This behavior is
227 // compatible with GNU.
229 createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path));
233 Files.push_back(make<LazyObjFile>(MBRef, "", 0));
235 Files.push_back(createObjectFile(MBRef));
239 // Add a given library by searching it from input search paths.
240 void LinkerDriver::addLibrary(StringRef Name) {
241 if (Optional<std::string> Path = searchLibrary(Name))
242 addFile(*Path, /*WithLOption=*/true);
244 error("unable to find library -l" + Name);
247 // This function is called on startup. We need this for LTO since
248 // LTO calls LLVM functions to compile bitcode files to native code.
249 // Technically this can be delayed until we read bitcode files, but
250 // we don't bother to do lazily because the initialization is fast.
251 static void initLLVM(opt::InputArgList &Args) {
252 InitializeAllTargets();
253 InitializeAllTargetMCs();
254 InitializeAllAsmPrinters();
255 InitializeAllAsmParsers();
257 // Parse and evaluate -mllvm options.
258 std::vector<const char *> V;
259 V.push_back("lld (LLVM option parsing)");
260 for (auto *Arg : Args.filtered(OPT_mllvm))
261 V.push_back(Arg->getValue());
262 cl::ParseCommandLineOptions(V.size(), V.data());
265 // Some command line options or some combinations of them are not allowed.
266 // This function checks for such errors.
267 static void checkOptions(opt::InputArgList &Args) {
268 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
269 // table which is a relatively new feature.
270 if (Config->EMachine == EM_MIPS && Config->GnuHash)
271 error("the .gnu.hash section is not compatible with the MIPS target.");
273 if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64)
274 error("--fix-cortex-a53-843419 is only supported on AArch64 targets.");
276 if (Config->Pie && Config->Shared)
277 error("-shared and -pie may not be used together");
279 if (!Config->Shared && !Config->FilterList.empty())
280 error("-F may not be used without -shared");
282 if (!Config->Shared && !Config->AuxiliaryList.empty())
283 error("-f may not be used without -shared");
285 if (!Config->Relocatable && !Config->DefineCommon)
286 error("-no-define-common not supported in non relocatable output");
288 if (Config->Relocatable) {
290 error("-r and -shared may not be used together");
291 if (Config->GcSections)
292 error("-r and --gc-sections may not be used together");
294 error("-r and --icf may not be used together");
296 error("-r and -pie may not be used together");
300 static const char *getReproduceOption(opt::InputArgList &Args) {
301 if (auto *Arg = Args.getLastArg(OPT_reproduce))
302 return Arg->getValue();
303 return getenv("LLD_REPRODUCE");
306 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
307 for (auto *Arg : Args.filtered(OPT_z))
308 if (Key == Arg->getValue())
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 errorHandler().ErrorLimit = args::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 // The behavior of -v or --version is a bit strange, but this is
345 // needed for compatibility with GNU linkers.
346 if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT))
348 if (Args.hasArg(OPT_version))
351 Config->ExitEarly = CanExitEarly && !Args.hasArg(OPT_full_shutdown);
352 errorHandler().ExitEarly = Config->ExitEarly;
354 if (const char *Path = getReproduceOption(Args)) {
355 // Note that --reproduce is a debug option so you can ignore it
356 // if you are trying to understand the whole picture of the code.
357 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
358 TarWriter::create(Path, path::stem(Path));
360 Tar = ErrOrWriter->get();
361 Tar->append("response.txt", createResponseFile(Args));
362 Tar->append("version.txt", getLLDVersion() + "\n");
363 make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
365 error(Twine("--reproduce: failed to open ") + Path + ": " +
366 toString(ErrOrWriter.takeError()));
379 switch (Config->EKind) {
393 llvm_unreachable("unknown Config->EKind");
397 static std::string getRpath(opt::InputArgList &Args) {
398 std::vector<StringRef> V = args::getStrings(Args, OPT_rpath);
399 return llvm::join(V.begin(), V.end(), ":");
402 // Determines what we should do if there are remaining unresolved
403 // symbols after the name resolution.
404 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
405 if (Args.hasArg(OPT_relocatable))
406 return UnresolvedPolicy::IgnoreAll;
408 UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols,
409 OPT_warn_unresolved_symbols, true)
410 ? UnresolvedPolicy::ReportError
411 : UnresolvedPolicy::Warn;
413 // Process the last of -unresolved-symbols, -no-undefined or -z defs.
414 for (auto *Arg : llvm::reverse(Args)) {
415 switch (Arg->getOption().getID()) {
416 case OPT_unresolved_symbols: {
417 StringRef S = Arg->getValue();
418 if (S == "ignore-all" || S == "ignore-in-object-files")
419 return UnresolvedPolicy::Ignore;
420 if (S == "ignore-in-shared-libs" || S == "report-all")
422 error("unknown --unresolved-symbols value: " + S);
425 case OPT_no_undefined:
428 if (StringRef(Arg->getValue()) == "defs")
434 // -shared implies -unresolved-symbols=ignore-all because missing
435 // symbols are likely to be resolved at runtime using other DSOs.
437 return UnresolvedPolicy::Ignore;
441 static Target2Policy getTarget2(opt::InputArgList &Args) {
442 StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
444 return Target2Policy::Rel;
446 return Target2Policy::Abs;
448 return Target2Policy::GotRel;
449 error("unknown --target2 option: " + S);
450 return Target2Policy::GotRel;
453 static bool isOutputFormatBinary(opt::InputArgList &Args) {
454 if (auto *Arg = Args.getLastArg(OPT_oformat)) {
455 StringRef S = Arg->getValue();
458 error("unknown --oformat value: " + S);
463 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
464 if (Args.hasArg(OPT_relocatable))
465 return DiscardPolicy::None;
468 Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
470 return DiscardPolicy::Default;
471 if (Arg->getOption().getID() == OPT_discard_all)
472 return DiscardPolicy::All;
473 if (Arg->getOption().getID() == OPT_discard_locals)
474 return DiscardPolicy::Locals;
475 return DiscardPolicy::None;
478 static StringRef getDynamicLinker(opt::InputArgList &Args) {
479 auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
480 if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
482 return Arg->getValue();
485 static StripPolicy getStrip(opt::InputArgList &Args) {
486 if (Args.hasArg(OPT_relocatable))
487 return StripPolicy::None;
489 auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
491 return StripPolicy::None;
492 if (Arg->getOption().getID() == OPT_strip_all)
493 return StripPolicy::All;
494 return StripPolicy::Debug;
497 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) {
499 if (S.startswith("0x"))
501 if (!to_integer(S, VA, 16))
502 error("invalid argument: " + toString(Arg));
506 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
507 StringMap<uint64_t> Ret;
508 for (auto *Arg : Args.filtered(OPT_section_start)) {
511 std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
512 Ret[Name] = parseSectionAddress(Addr, *Arg);
515 if (auto *Arg = Args.getLastArg(OPT_Ttext))
516 Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg);
517 if (auto *Arg = Args.getLastArg(OPT_Tdata))
518 Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg);
519 if (auto *Arg = Args.getLastArg(OPT_Tbss))
520 Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg);
524 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
525 StringRef S = Args.getLastArgValue(OPT_sort_section);
526 if (S == "alignment")
527 return SortSectionPolicy::Alignment;
529 return SortSectionPolicy::Name;
531 error("unknown --sort-section rule: " + S);
532 return SortSectionPolicy::Default;
535 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) {
536 StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place");
538 return OrphanHandlingPolicy::Warn;
540 return OrphanHandlingPolicy::Error;
542 error("unknown --orphan-handling mode: " + S);
543 return OrphanHandlingPolicy::Place;
546 // Parse --build-id or --build-id=<style>. We handle "tree" as a
547 // synonym for "sha1" because all our hash functions including
548 // -build-id=sha1 are actually tree hashes for performance reasons.
549 static std::pair<BuildIdKind, std::vector<uint8_t>>
550 getBuildId(opt::InputArgList &Args) {
551 auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
553 return {BuildIdKind::None, {}};
555 if (Arg->getOption().getID() == OPT_build_id)
556 return {BuildIdKind::Fast, {}};
558 StringRef S = Arg->getValue();
560 return {BuildIdKind::Md5, {}};
561 if (S == "sha1" || S == "tree")
562 return {BuildIdKind::Sha1, {}};
564 return {BuildIdKind::Uuid, {}};
565 if (S.startswith("0x"))
566 return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
569 error("unknown --build-id style: " + S);
570 return {BuildIdKind::None, {}};
573 static bool getCompressDebugSections(opt::InputArgList &Args) {
574 StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
578 error("unknown --compress-debug-sections value: " + S);
579 if (!zlib::isAvailable())
580 error("--compress-debug-sections: zlib is not available");
584 static int parseInt(StringRef S, opt::Arg *Arg) {
586 if (!to_integer(S, V, 10))
587 error(Arg->getSpelling() + ": number expected, but got '" + S + "'");
591 // Initializes Config members by the command line options.
592 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
593 Config->AllowMultipleDefinition =
594 Args.hasArg(OPT_allow_multiple_definition) || hasZOption(Args, "muldefs");
595 Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary);
596 Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
597 Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
598 Config->Chroot = Args.getLastArgValue(OPT_chroot);
599 Config->CompressDebugSections = getCompressDebugSections(Args);
600 Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common,
601 !Args.hasArg(OPT_relocatable));
602 Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
603 Config->DisableVerify = Args.hasArg(OPT_disable_verify);
604 Config->Discard = getDiscard(Args);
605 Config->DynamicLinker = getDynamicLinker(Args);
607 Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
608 Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
609 Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
610 Config->Entry = Args.getLastArgValue(OPT_entry);
611 Config->ExportDynamic =
612 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
613 errorHandler().FatalWarnings =
614 Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
615 Config->FilterList = args::getStrings(Args, OPT_filter);
616 Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
617 Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419);
618 Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
619 Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
620 Config->ICF = Args.hasFlag(OPT_icf_all, OPT_icf_none, false);
621 Config->ICFData = Args.hasArg(OPT_icf_data);
622 Config->Init = Args.getLastArgValue(OPT_init, "_init");
623 Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
624 Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
625 Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
626 Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
627 Config->MapFile = Args.getLastArgValue(OPT_Map);
628 Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
629 Config->MergeArmExidx =
630 Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
631 Config->NoUndefinedVersion = Args.hasArg(OPT_no_undefined_version);
632 Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
633 Config->Nostdlib = Args.hasArg(OPT_nostdlib);
634 Config->OFormatBinary = isOutputFormatBinary(Args);
635 Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false);
636 Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
637 Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
638 Config->Optimize = args::getInteger(Args, OPT_O, 1);
639 Config->OrphanHandling = getOrphanHandling(Args);
640 Config->OutputFile = Args.getLastArgValue(OPT_o);
641 Config->Pie = Args.hasFlag(OPT_pie, OPT_nopie, false);
642 Config->PrintGcSections =
643 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
644 Config->Rpath = getRpath(Args);
645 Config->Relocatable = Args.hasArg(OPT_relocatable);
646 Config->SaveTemps = Args.hasArg(OPT_save_temps);
647 Config->SearchPaths = args::getStrings(Args, OPT_library_path);
648 Config->SectionStartMap = getSectionStartMap(Args);
649 Config->Shared = Args.hasArg(OPT_shared);
650 Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
651 Config->SoName = Args.getLastArgValue(OPT_soname);
652 Config->SortSection = getSortSection(Args);
653 Config->Strip = getStrip(Args);
654 Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
655 Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
656 Config->Target2 = getTarget2(Args);
657 Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
658 Config->ThinLTOCachePolicy = CHECK(
659 parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
660 "--thinlto-cache-policy: invalid cache policy");
661 Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
662 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
663 Config->Trace = Args.hasArg(OPT_trace);
664 Config->Undefined = args::getStrings(Args, OPT_undefined);
665 Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
666 Config->Verbose = Args.hasArg(OPT_verbose);
667 errorHandler().Verbose = Config->Verbose;
668 Config->WarnCommon = Args.hasArg(OPT_warn_common);
669 Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
670 Config->ZExecstack = hasZOption(Args, "execstack");
671 Config->ZHazardplt = hasZOption(Args, "hazardplt");
672 Config->ZNocopyreloc = hasZOption(Args, "nocopyreloc");
673 Config->ZNodelete = hasZOption(Args, "nodelete");
674 Config->ZNodlopen = hasZOption(Args, "nodlopen");
675 Config->ZNow = hasZOption(Args, "now");
676 Config->ZOrigin = hasZOption(Args, "origin");
677 Config->ZRelro = !hasZOption(Args, "norelro");
678 Config->ZRetpolineplt = hasZOption(Args, "retpolineplt");
679 Config->ZRodynamic = hasZOption(Args, "rodynamic");
680 Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
681 Config->ZText = !hasZOption(Args, "notext");
682 Config->ZWxneeded = hasZOption(Args, "wxneeded");
684 // Parse LTO plugin-related options for compatibility with gold.
685 for (auto *Arg : Args.filtered(OPT_plugin_opt, OPT_plugin_opt_eq)) {
686 StringRef S = Arg->getValue();
687 if (S == "disable-verify")
688 Config->DisableVerify = true;
689 else if (S == "save-temps")
690 Config->SaveTemps = true;
691 else if (S.startswith("O"))
692 Config->LTOO = parseInt(S.substr(1), Arg);
693 else if (S.startswith("lto-partitions="))
694 Config->LTOPartitions = parseInt(S.substr(15), Arg);
695 else if (S.startswith("jobs="))
696 Config->ThinLTOJobs = parseInt(S.substr(5), Arg);
697 else if (!S.startswith("/") && !S.startswith("-fresolution=") &&
698 !S.startswith("-pass-through=") && !S.startswith("mcpu=") &&
699 !S.startswith("thinlto") && S != "-function-sections" &&
700 S != "-data-sections")
701 error(Arg->getSpelling() + ": unknown option: " + S);
704 if (Config->LTOO > 3)
705 error("invalid optimization level for LTO: " + Twine(Config->LTOO));
706 if (Config->LTOPartitions == 0)
707 error("--lto-partitions: number of threads must be > 0");
708 if (Config->ThinLTOJobs == 0)
709 error("--thinlto-jobs: number of threads must be > 0");
711 // Parse ELF{32,64}{LE,BE} and CPU type.
712 if (auto *Arg = Args.getLastArg(OPT_m)) {
713 StringRef S = Arg->getValue();
714 std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
716 Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
717 Config->Emulation = S;
720 // Parse -hash-style={sysv,gnu,both}.
721 if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
722 StringRef S = Arg->getValue();
724 Config->SysvHash = true;
726 Config->GnuHash = true;
727 else if (S == "both")
728 Config->SysvHash = Config->GnuHash = true;
730 error("unknown -hash-style: " + S);
733 if (Args.hasArg(OPT_print_map))
734 Config->MapFile = "-";
736 // --omagic is an option to create old-fashioned executables in which
737 // .text segments are writable. Today, the option is still in use to
738 // create special-purpose programs such as boot loaders. It doesn't
739 // make sense to create PT_GNU_RELRO for such executables.
741 Config->ZRelro = false;
743 std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
745 if (auto *Arg = Args.getLastArg(OPT_pack_dyn_relocs_eq)) {
746 StringRef S = Arg->getValue();
748 Config->AndroidPackDynRelocs = true;
749 else if (S != "none")
750 error("unknown -pack-dyn-relocs format: " + S);
753 if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
754 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
755 Config->SymbolOrderingFile = args::getLines(*Buffer);
757 // If --retain-symbol-file is used, we'll keep only the symbols listed in
758 // the file and discard all others.
759 if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
760 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
761 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
762 for (StringRef S : args::getLines(*Buffer))
763 Config->VersionScriptGlobals.push_back(
764 {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
767 bool HasExportDynamic =
768 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
770 // Parses -dynamic-list and -export-dynamic-symbol. They make some
771 // symbols private. Note that -export-dynamic takes precedence over them
772 // as it says all symbols should be exported.
773 if (!HasExportDynamic) {
774 for (auto *Arg : Args.filtered(OPT_dynamic_list))
775 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
776 readDynamicList(*Buffer);
778 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
779 Config->DynamicList.push_back(
780 {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
783 for (auto *Arg : Args.filtered(OPT_version_script))
784 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
785 readVersionScript(*Buffer);
788 // Some Config members do not directly correspond to any particular
789 // command line options, but computed based on other Config values.
790 // This function initialize such members. See Config.h for the details
792 static void setConfigs() {
793 ELFKind Kind = Config->EKind;
794 uint16_t Machine = Config->EMachine;
796 // There is an ILP32 ABI for x86-64, although it's not very popular.
797 // It is called the x32 ABI.
798 bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64);
800 Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
801 Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind);
802 Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind);
804 Config->IsLE ? support::endianness::little : support::endianness::big;
805 Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS);
806 Config->IsRela = Config->Is64 || IsX32 || Config->MipsN32Abi;
807 Config->Pic = Config->Pie || Config->Shared;
808 Config->Wordsize = Config->Is64 ? 8 : 4;
811 // Returns a value of "-format" option.
812 static bool getBinaryOption(StringRef S) {
815 if (S == "elf" || S == "default")
817 error("unknown -format value: " + S +
818 " (supported formats: elf, default, binary)");
822 void LinkerDriver::createFiles(opt::InputArgList &Args) {
823 for (auto *Arg : Args) {
824 switch (Arg->getOption().getUnaliasedOption().getID()) {
826 addLibrary(Arg->getValue());
829 addFile(Arg->getValue(), /*WithLOption=*/false);
832 if (Optional<std::string> Path = searchLinkerScript(Arg->getValue())) {
833 if (Optional<MemoryBufferRef> MB = readFile(*Path))
834 readLinkerScript(*MB);
837 error(Twine("cannot find linker script ") + Arg->getValue());
840 Config->AsNeeded = true;
843 InBinary = getBinaryOption(Arg->getValue());
845 case OPT_no_as_needed:
846 Config->AsNeeded = false;
849 Config->Static = true;
852 Config->Static = false;
854 case OPT_whole_archive:
855 InWholeArchive = true;
857 case OPT_no_whole_archive:
858 InWholeArchive = false;
869 if (Files.empty() && errorCount() == 0)
870 error("no input files");
873 // If -m <machine_type> was not given, infer it from object files.
874 void LinkerDriver::inferMachineType() {
875 if (Config->EKind != ELFNoneKind)
878 for (InputFile *F : Files) {
879 if (F->EKind == ELFNoneKind)
881 Config->EKind = F->EKind;
882 Config->EMachine = F->EMachine;
883 Config->OSABI = F->OSABI;
884 Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
887 error("target emulation unknown: -m or at least one .o file required");
890 // Parse -z max-page-size=<value>. The default value is defined by
892 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
893 uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
894 Target->DefaultMaxPageSize);
895 if (!isPowerOf2_64(Val))
896 error("max-page-size: value isn't a power of 2");
900 // Parses -image-base option.
901 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
902 // Because we are using "Config->MaxPageSize" here, this function has to be
903 // called after the variable is initialized.
904 auto *Arg = Args.getLastArg(OPT_image_base);
908 StringRef S = Arg->getValue();
910 if (!to_integer(S, V)) {
911 error("-image-base: number expected, but got " + S);
914 if ((V % Config->MaxPageSize) != 0)
915 warn("-image-base: address isn't multiple of page size: " + S);
919 // Parses `--exclude-libs=lib,lib,...`.
920 // The library names may be delimited by commas or colons.
921 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
922 DenseSet<StringRef> Ret;
923 for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
924 StringRef S = Arg->getValue();
926 size_t Pos = S.find_first_of(",:");
927 if (Pos == StringRef::npos)
929 Ret.insert(S.substr(0, Pos));
930 S = S.substr(Pos + 1);
937 static Optional<StringRef> getArchiveName(InputFile *File) {
938 if (isa<ArchiveFile>(File))
939 return File->getName();
940 if (!File->ArchiveName.empty())
941 return File->ArchiveName;
945 // Handles the -exclude-libs option. If a static library file is specified
946 // by the -exclude-libs option, all public symbols from the archive become
947 // private unless otherwise specified by version scripts or something.
948 // A special library name "ALL" means all archive files.
950 // This is not a popular option, but some programs such as bionic libc use it.
951 template <class ELFT>
952 static void excludeLibs(opt::InputArgList &Args, ArrayRef<InputFile *> Files) {
953 DenseSet<StringRef> Libs = getExcludeLibs(Args);
954 bool All = Libs.count("ALL");
956 for (InputFile *File : Files)
957 if (Optional<StringRef> Archive = getArchiveName(File))
958 if (All || Libs.count(path::filename(*Archive)))
959 for (Symbol *Sym : File->getSymbols())
961 Sym->VersionId = VER_NDX_LOCAL;
964 // Do actual linking. Note that when this function is called,
965 // all linker scripts have already been parsed.
966 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
967 Target = getTarget();
969 Config->MaxPageSize = getMaxPageSize(Args);
970 Config->ImageBase = getImageBase(Args);
972 // If a -hash-style option was not given, set to a default value,
973 // which varies depending on the target.
974 if (!Args.hasArg(OPT_hash_style)) {
975 if (Config->EMachine == EM_MIPS)
976 Config->SysvHash = true;
978 Config->SysvHash = Config->GnuHash = true;
981 // Default output filename is "a.out" by the Unix tradition.
982 if (Config->OutputFile.empty())
983 Config->OutputFile = "a.out";
985 // Fail early if the output file or map file is not writable. If a user has a
986 // long link, e.g. due to a large LTO link, they do not wish to run it and
987 // find that it failed because there was a mistake in their command-line.
988 if (auto E = tryCreateFile(Config->OutputFile))
989 error("cannot open output file " + Config->OutputFile + ": " + E.message());
990 if (auto E = tryCreateFile(Config->MapFile))
991 error("cannot open map file " + Config->MapFile + ": " + E.message());
995 // Use default entry point name if no name was given via the command
996 // line nor linker scripts. For some reason, MIPS entry point name is
997 // different from others.
998 Config->WarnMissingEntry =
999 (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
1000 if (Config->Entry.empty() && !Config->Relocatable)
1001 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
1003 // Handle --trace-symbol.
1004 for (auto *Arg : Args.filtered(OPT_trace_symbol))
1005 Symtab->trace(Arg->getValue());
1007 // Add all files to the symbol table. This will add almost all
1008 // symbols that we need to the symbol table.
1009 for (InputFile *F : Files)
1010 Symtab->addFile<ELFT>(F);
1012 // Process -defsym option.
1013 for (auto *Arg : Args.filtered(OPT_defsym)) {
1016 std::tie(From, To) = StringRef(Arg->getValue()).split('=');
1017 readDefsym(From, MemoryBufferRef(To, "-defsym"));
1020 // Now that we have every file, we can decide if we will need a
1021 // dynamic symbol table.
1022 // We need one if we were asked to export dynamic symbols or if we are
1023 // producing a shared library.
1024 // We also need one if any shared libraries are used and for pie executables
1025 // (probably because the dynamic linker needs it).
1026 Config->HasDynSymTab =
1027 !SharedFiles.empty() || Config->Pic || Config->ExportDynamic;
1029 // Some symbols (such as __ehdr_start) are defined lazily only when there
1030 // are undefined symbols for them, so we add these to trigger that logic.
1031 for (StringRef Sym : Script->ReferencedSymbols)
1032 Symtab->addUndefined<ELFT>(Sym);
1034 // Handle the `--undefined <sym>` options.
1035 for (StringRef S : Config->Undefined)
1036 Symtab->fetchIfLazy<ELFT>(S);
1038 // If an entry symbol is in a static archive, pull out that file now
1039 // to complete the symbol table. After this, no new names except a
1040 // few linker-synthesized ones will be added to the symbol table.
1041 Symtab->fetchIfLazy<ELFT>(Config->Entry);
1043 // Return if there were name resolution errors.
1047 // Handle undefined symbols in DSOs.
1048 if (!Config->Shared)
1049 Symtab->scanShlibUndefined<ELFT>();
1051 // Handle the -exclude-libs option.
1052 if (Args.hasArg(OPT_exclude_libs))
1053 excludeLibs<ELFT>(Args, Files);
1055 // Create ElfHeader early. We need a dummy section in
1056 // addReservedSymbols to mark the created symbols as not absolute.
1057 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1058 Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1060 // We need to create some reserved symbols such as _end. Create them.
1061 if (!Config->Relocatable)
1062 addReservedSymbols();
1064 // Apply version scripts.
1066 // For a relocatable output, version scripts don't make sense, and
1067 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1068 // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1069 if (!Config->Relocatable)
1070 Symtab->scanVersionScript();
1072 // Create wrapped symbols for -wrap option.
1073 for (auto *Arg : Args.filtered(OPT_wrap))
1074 Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1076 Symtab->addCombinedLTOObject<ELFT>();
1080 // Apply symbol renames for -wrap.
1081 Symtab->applySymbolWrap();
1083 // Now that we have a complete list of input files.
1084 // Beyond this point, no new files are added.
1085 // Aggregate all input sections into one place.
1086 for (InputFile *F : ObjectFiles)
1087 for (InputSectionBase *S : F->getSections())
1088 if (S && S != &InputSection::Discarded)
1089 InputSections.push_back(S);
1090 for (BinaryFile *F : BinaryFiles)
1091 for (InputSectionBase *S : F->getSections())
1092 InputSections.push_back(cast<InputSection>(S));
1094 // We do not want to emit debug sections if --strip-all
1095 // or -strip-debug are given.
1096 if (Config->Strip != StripPolicy::None)
1097 llvm::erase_if(InputSections, [](InputSectionBase *S) {
1098 return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1101 Config->EFlags = Target->calcEFlags();
1103 if (Config->EMachine == EM_ARM) {
1104 // FIXME: These warnings can be removed when lld only uses these features
1105 // when the input objects have been compiled with an architecture that
1107 if (Config->ARMHasBlx == false)
1108 warn("lld uses blx instruction, no object with architecture supporting "
1109 "feature detected.");
1110 if (Config->ARMJ1J2BranchEncoding == false)
1111 warn("lld uses extended branch encoding, no object with architecture "
1112 "supporting feature detected.");
1113 if (Config->ARMHasMovtMovw == false)
1114 warn("lld may use movt/movw, no object with architecture supporting "
1115 "feature detected.");
1118 // This adds a .comment section containing a version string. We have to add it
1119 // before decompressAndMergeSections because the .comment section is a
1120 // mergeable section.
1121 if (!Config->Relocatable)
1122 InputSections.push_back(createCommentSection());
1124 // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1125 // and identical code folding.
1127 decompressSections();
1132 // Write the result to the file.
1133 writeResult<ELFT>();