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"
34 #include "OutputSections.h"
35 #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/Strings.h"
46 #include "lld/Common/TargetOptionsCommandFlags.h"
47 #include "lld/Common/Threads.h"
48 #include "lld/Common/Version.h"
49 #include "llvm/ADT/SetVector.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/StringSwitch.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compression.h"
54 #include "llvm/Support/LEB128.h"
55 #include "llvm/Support/Path.h"
56 #include "llvm/Support/TarWriter.h"
57 #include "llvm/Support/TargetSelect.h"
58 #include "llvm/Support/raw_ostream.h"
63 using namespace llvm::ELF;
64 using namespace llvm::object;
65 using namespace llvm::sys;
68 using namespace lld::elf;
70 Configuration *elf::Config;
71 LinkerDriver *elf::Driver;
73 static void setConfigs(opt::InputArgList &Args);
75 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
77 errorHandler().LogName = sys::path::filename(Args[0]);
78 errorHandler().ErrorLimitExceededMsg =
79 "too many errors emitted, stopping now (use "
80 "-error-limit=0 to see all errors)";
81 errorHandler().ErrorOS = &Error;
82 errorHandler().ExitEarly = CanExitEarly;
83 errorHandler().ColorDiagnostics = Error.has_colors();
85 InputSections.clear();
86 OutputSections.clear();
93 Config = make<Configuration>();
94 Driver = make<LinkerDriver>();
95 Script = make<LinkerScript>();
96 Symtab = make<SymbolTable>();
97 Config->ProgName = Args[0];
101 // Exit immediately if we don't need to return to the caller.
102 // This saves time because the overhead of calling destructors
103 // for all globally-allocated objects is not negligible.
105 exitLld(errorCount() ? 1 : 0);
108 return !errorCount();
111 // Parses a linker -m option.
112 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
115 if (S.endswith("_fbsd")) {
117 OSABI = ELFOSABI_FREEBSD;
120 std::pair<ELFKind, uint16_t> Ret =
121 StringSwitch<std::pair<ELFKind, uint16_t>>(S)
122 .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
123 {ELF64LEKind, EM_AARCH64})
124 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
125 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
126 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
127 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
128 .Case("elf32ppc", {ELF32BEKind, EM_PPC})
129 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
130 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
131 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
132 .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
133 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
134 .Case("elf_i386", {ELF32LEKind, EM_386})
135 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
136 .Default({ELFNoneKind, EM_NONE});
138 if (Ret.first == ELFNoneKind)
139 error("unknown emulation: " + Emul);
140 return std::make_tuple(Ret.first, Ret.second, OSABI);
143 // Returns slices of MB by parsing MB as an archive file.
144 // Each slice consists of a member file in the archive.
145 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
146 MemoryBufferRef MB) {
147 std::unique_ptr<Archive> File =
148 CHECK(Archive::create(MB),
149 MB.getBufferIdentifier() + ": failed to parse archive");
151 std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
152 Error Err = Error::success();
153 bool AddToTar = File->isThin() && Tar;
154 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
156 CHECK(COrErr, MB.getBufferIdentifier() +
157 ": could not get the child of the archive");
158 MemoryBufferRef MBRef =
159 CHECK(C.getMemoryBufferRef(),
160 MB.getBufferIdentifier() +
161 ": could not get the buffer for a child of the archive");
163 Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer());
164 V.push_back(std::make_pair(MBRef, C.getChildOffset()));
167 fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
168 toString(std::move(Err)));
170 // Take ownership of memory buffers created for members of thin archives.
171 for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
172 make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
177 // Opens a file and create a file object. Path has to be resolved already.
178 void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
179 using namespace sys::fs;
181 Optional<MemoryBufferRef> Buffer = readFile(Path);
182 if (!Buffer.hasValue())
184 MemoryBufferRef MBRef = *Buffer;
187 Files.push_back(make<BinaryFile>(MBRef));
191 switch (identify_magic(MBRef.getBuffer())) {
192 case file_magic::unknown:
193 readLinkerScript(MBRef);
195 case file_magic::archive: {
196 // Handle -whole-archive.
197 if (InWholeArchive) {
198 for (const auto &P : getArchiveMembers(MBRef))
199 Files.push_back(createObjectFile(P.first, Path, P.second));
203 std::unique_ptr<Archive> File =
204 CHECK(Archive::create(MBRef), Path + ": failed to parse archive");
206 // If an archive file has no symbol table, it is likely that a user
207 // is attempting LTO and using a default ar command that doesn't
208 // understand the LLVM bitcode file. It is a pretty common error, so
209 // we'll handle it as if it had a symbol table.
210 if (!File->isEmpty() && !File->hasSymbolTable()) {
211 for (const auto &P : getArchiveMembers(MBRef))
212 Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
216 // Handle the regular case.
217 Files.push_back(make<ArchiveFile>(std::move(File)));
220 case file_magic::elf_shared_object:
221 if (Config->Relocatable) {
222 error("attempted static link of dynamic object " + Path);
226 // DSOs usually have DT_SONAME tags in their ELF headers, and the
227 // sonames are used to identify DSOs. But if they are missing,
228 // they are identified by filenames. We don't know whether the new
229 // file has a DT_SONAME or not because we haven't parsed it yet.
230 // Here, we set the default soname for the file because we might
233 // If a file was specified by -lfoo, the directory part is not
234 // significant, as a user did not specify it. This behavior is
235 // compatible with GNU.
237 createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path));
239 case file_magic::bitcode:
240 case file_magic::elf_relocatable:
242 Files.push_back(make<LazyObjFile>(MBRef, "", 0));
244 Files.push_back(createObjectFile(MBRef));
247 error(Path + ": unknown file type");
251 // Add a given library by searching it from input search paths.
252 void LinkerDriver::addLibrary(StringRef Name) {
253 if (Optional<std::string> Path = searchLibrary(Name))
254 addFile(*Path, /*WithLOption=*/true);
256 error("unable to find library -l" + Name);
259 // This function is called on startup. We need this for LTO since
260 // LTO calls LLVM functions to compile bitcode files to native code.
261 // Technically this can be delayed until we read bitcode files, but
262 // we don't bother to do lazily because the initialization is fast.
263 static void initLLVM() {
264 InitializeAllTargets();
265 InitializeAllTargetMCs();
266 InitializeAllAsmPrinters();
267 InitializeAllAsmParsers();
270 // Some command line options or some combinations of them are not allowed.
271 // This function checks for such errors.
272 static void checkOptions(opt::InputArgList &Args) {
273 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
274 // table which is a relatively new feature.
275 if (Config->EMachine == EM_MIPS && Config->GnuHash)
276 error("the .gnu.hash section is not compatible with the MIPS target.");
278 if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64)
279 error("--fix-cortex-a53-843419 is only supported on AArch64 targets.");
281 if (Config->Pie && Config->Shared)
282 error("-shared and -pie may not be used together");
284 if (!Config->Shared && !Config->FilterList.empty())
285 error("-F may not be used without -shared");
287 if (!Config->Shared && !Config->AuxiliaryList.empty())
288 error("-f may not be used without -shared");
290 if (!Config->Relocatable && !Config->DefineCommon)
291 error("-no-define-common not supported in non relocatable output");
293 if (Config->Relocatable) {
295 error("-r and -shared may not be used together");
296 if (Config->GcSections)
297 error("-r and --gc-sections may not be used together");
298 if (Config->GdbIndex)
299 error("-r and --gdb-index may not be used together");
300 if (Config->ICF != ICFLevel::None)
301 error("-r and --icf may not be used together");
303 error("-r and -pie may not be used together");
307 static const char *getReproduceOption(opt::InputArgList &Args) {
308 if (auto *Arg = Args.getLastArg(OPT_reproduce))
309 return Arg->getValue();
310 return getenv("LLD_REPRODUCE");
313 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
314 for (auto *Arg : Args.filtered(OPT_z))
315 if (Key == Arg->getValue())
320 static bool getZFlag(opt::InputArgList &Args, StringRef K1, StringRef K2,
322 for (auto *Arg : Args.filtered_reverse(OPT_z)) {
323 if (K1 == Arg->getValue())
325 if (K2 == Arg->getValue())
331 static bool isKnown(StringRef S) {
332 return S == "combreloc" || S == "copyreloc" || S == "defs" ||
333 S == "execstack" || S == "hazardplt" || S == "initfirst" ||
334 S == "keep-text-section-prefix" || S == "lazy" || S == "muldefs" ||
335 S == "nocombreloc" || S == "nocopyreloc" || S == "nodelete" ||
336 S == "nodlopen" || S == "noexecstack" ||
337 S == "nokeep-text-section-prefix" || S == "norelro" || S == "notext" ||
338 S == "now" || S == "origin" || S == "relro" || S == "retpolineplt" ||
339 S == "rodynamic" || S == "text" || S == "wxneeded" ||
340 S.startswith("max-page-size=") || S.startswith("stack-size=");
343 // Report an error for an unknown -z option.
344 static void checkZOptions(opt::InputArgList &Args) {
345 for (auto *Arg : Args.filtered(OPT_z))
346 if (!isKnown(Arg->getValue()))
347 error("unknown -z value: " + StringRef(Arg->getValue()));
350 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
352 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
354 // Interpret this flag early because error() depends on them.
355 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
358 if (Args.hasArg(OPT_help)) {
363 // Handle -v or -version.
365 // A note about "compatible with GNU linkers" message: this is a hack for
366 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
367 // still the newest version in March 2017) or earlier to recognize LLD as
368 // a GNU compatible linker. As long as an output for the -v option
369 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
371 // This is somewhat ugly hack, but in reality, we had no choice other
372 // than doing this. Considering the very long release cycle of Libtool,
373 // it is not easy to improve it to recognize LLD as a GNU compatible
374 // linker in a timely manner. Even if we can make it, there are still a
375 // lot of "configure" scripts out there that are generated by old version
376 // of Libtool. We cannot convince every software developer to migrate to
377 // the latest version and re-generate scripts. So we have this hack.
378 if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
379 message(getLLDVersion() + " (compatible with GNU linkers)");
381 // The behavior of -v or --version is a bit strange, but this is
382 // needed for compatibility with GNU linkers.
383 if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT))
385 if (Args.hasArg(OPT_version))
388 if (const char *Path = getReproduceOption(Args)) {
389 // Note that --reproduce is a debug option so you can ignore it
390 // if you are trying to understand the whole picture of the code.
391 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
392 TarWriter::create(Path, path::stem(Path));
394 Tar = ErrOrWriter->get();
395 Tar->append("response.txt", createResponseFile(Args));
396 Tar->append("version.txt", getLLDVersion() + "\n");
397 make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
399 error(Twine("--reproduce: failed to open ") + Path + ": " +
400 toString(ErrOrWriter.takeError()));
417 switch (Config->EKind) {
431 llvm_unreachable("unknown Config->EKind");
435 static std::string getRpath(opt::InputArgList &Args) {
436 std::vector<StringRef> V = args::getStrings(Args, OPT_rpath);
437 return llvm::join(V.begin(), V.end(), ":");
440 // Determines what we should do if there are remaining unresolved
441 // symbols after the name resolution.
442 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
443 if (Args.hasArg(OPT_relocatable))
444 return UnresolvedPolicy::IgnoreAll;
446 UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols,
447 OPT_warn_unresolved_symbols, true)
448 ? UnresolvedPolicy::ReportError
449 : UnresolvedPolicy::Warn;
451 // Process the last of -unresolved-symbols, -no-undefined or -z defs.
452 for (auto *Arg : llvm::reverse(Args)) {
453 switch (Arg->getOption().getID()) {
454 case OPT_unresolved_symbols: {
455 StringRef S = Arg->getValue();
456 if (S == "ignore-all" || S == "ignore-in-object-files")
457 return UnresolvedPolicy::Ignore;
458 if (S == "ignore-in-shared-libs" || S == "report-all")
460 error("unknown --unresolved-symbols value: " + S);
463 case OPT_no_undefined:
466 if (StringRef(Arg->getValue()) == "defs")
472 // -shared implies -unresolved-symbols=ignore-all because missing
473 // symbols are likely to be resolved at runtime using other DSOs.
475 return UnresolvedPolicy::Ignore;
479 static Target2Policy getTarget2(opt::InputArgList &Args) {
480 StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
482 return Target2Policy::Rel;
484 return Target2Policy::Abs;
486 return Target2Policy::GotRel;
487 error("unknown --target2 option: " + S);
488 return Target2Policy::GotRel;
491 static bool isOutputFormatBinary(opt::InputArgList &Args) {
492 if (auto *Arg = Args.getLastArg(OPT_oformat)) {
493 StringRef S = Arg->getValue();
496 error("unknown --oformat value: " + S);
501 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
502 if (Args.hasArg(OPT_relocatable))
503 return DiscardPolicy::None;
506 Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
508 return DiscardPolicy::Default;
509 if (Arg->getOption().getID() == OPT_discard_all)
510 return DiscardPolicy::All;
511 if (Arg->getOption().getID() == OPT_discard_locals)
512 return DiscardPolicy::Locals;
513 return DiscardPolicy::None;
516 static StringRef getDynamicLinker(opt::InputArgList &Args) {
517 auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
518 if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
520 return Arg->getValue();
523 static ICFLevel getICF(opt::InputArgList &Args) {
524 auto *Arg = Args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
525 if (!Arg || Arg->getOption().getID() == OPT_icf_none)
526 return ICFLevel::None;
527 if (Arg->getOption().getID() == OPT_icf_safe)
528 return ICFLevel::Safe;
529 return ICFLevel::All;
532 static StripPolicy getStrip(opt::InputArgList &Args) {
533 if (Args.hasArg(OPT_relocatable))
534 return StripPolicy::None;
536 auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
538 return StripPolicy::None;
539 if (Arg->getOption().getID() == OPT_strip_all)
540 return StripPolicy::All;
541 return StripPolicy::Debug;
544 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) {
546 if (S.startswith("0x"))
548 if (!to_integer(S, VA, 16))
549 error("invalid argument: " + toString(Arg));
553 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
554 StringMap<uint64_t> Ret;
555 for (auto *Arg : Args.filtered(OPT_section_start)) {
558 std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
559 Ret[Name] = parseSectionAddress(Addr, *Arg);
562 if (auto *Arg = Args.getLastArg(OPT_Ttext))
563 Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg);
564 if (auto *Arg = Args.getLastArg(OPT_Tdata))
565 Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg);
566 if (auto *Arg = Args.getLastArg(OPT_Tbss))
567 Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg);
571 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
572 StringRef S = Args.getLastArgValue(OPT_sort_section);
573 if (S == "alignment")
574 return SortSectionPolicy::Alignment;
576 return SortSectionPolicy::Name;
578 error("unknown --sort-section rule: " + S);
579 return SortSectionPolicy::Default;
582 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) {
583 StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place");
585 return OrphanHandlingPolicy::Warn;
587 return OrphanHandlingPolicy::Error;
589 error("unknown --orphan-handling mode: " + S);
590 return OrphanHandlingPolicy::Place;
593 // Parse --build-id or --build-id=<style>. We handle "tree" as a
594 // synonym for "sha1" because all our hash functions including
595 // -build-id=sha1 are actually tree hashes for performance reasons.
596 static std::pair<BuildIdKind, std::vector<uint8_t>>
597 getBuildId(opt::InputArgList &Args) {
598 auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
600 return {BuildIdKind::None, {}};
602 if (Arg->getOption().getID() == OPT_build_id)
603 return {BuildIdKind::Fast, {}};
605 StringRef S = Arg->getValue();
607 return {BuildIdKind::Fast, {}};
609 return {BuildIdKind::Md5, {}};
610 if (S == "sha1" || S == "tree")
611 return {BuildIdKind::Sha1, {}};
613 return {BuildIdKind::Uuid, {}};
614 if (S.startswith("0x"))
615 return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
618 error("unknown --build-id style: " + S);
619 return {BuildIdKind::None, {}};
622 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &Args) {
623 StringRef S = Args.getLastArgValue(OPT_pack_dyn_relocs, "none");
625 return {true, false};
627 return {false, true};
628 if (S == "android+relr")
632 error("unknown -pack-dyn-relocs format: " + S);
633 return {false, false};
636 static void readCallGraph(MemoryBufferRef MB) {
637 // Build a map from symbol name to section
638 DenseMap<StringRef, const Symbol *> SymbolNameToSymbol;
639 for (InputFile *File : ObjectFiles)
640 for (Symbol *Sym : File->getSymbols())
641 SymbolNameToSymbol[Sym->getName()] = Sym;
643 for (StringRef L : args::getLines(MB)) {
644 SmallVector<StringRef, 3> Fields;
645 L.split(Fields, ' ');
647 if (Fields.size() != 3 || !to_integer(Fields[2], Count))
648 fatal(MB.getBufferIdentifier() + ": parse error");
649 const Symbol *FromSym = SymbolNameToSymbol.lookup(Fields[0]);
650 const Symbol *ToSym = SymbolNameToSymbol.lookup(Fields[1]);
651 if (Config->WarnSymbolOrdering) {
653 warn(MB.getBufferIdentifier() + ": no such symbol: " + Fields[0]);
655 warn(MB.getBufferIdentifier() + ": no such symbol: " + Fields[1]);
657 if (!FromSym || !ToSym || Count == 0)
659 warnUnorderableSymbol(FromSym);
660 warnUnorderableSymbol(ToSym);
661 const Defined *FromSymD = dyn_cast<Defined>(FromSym);
662 const Defined *ToSymD = dyn_cast<Defined>(ToSym);
663 if (!FromSymD || !ToSymD)
665 const auto *FromSB = dyn_cast_or_null<InputSectionBase>(FromSymD->Section);
666 const auto *ToSB = dyn_cast_or_null<InputSectionBase>(ToSymD->Section);
667 if (!FromSB || !ToSB)
669 Config->CallGraphProfile[std::make_pair(FromSB, ToSB)] += Count;
673 static bool getCompressDebugSections(opt::InputArgList &Args) {
674 StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
678 error("unknown --compress-debug-sections value: " + S);
679 if (!zlib::isAvailable())
680 error("--compress-debug-sections: zlib is not available");
684 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &Args,
686 auto *Arg = Args.getLastArg(Id);
690 StringRef S = Arg->getValue();
691 std::pair<StringRef, StringRef> Ret = S.split(';');
692 if (Ret.second.empty())
693 error(Arg->getSpelling() + " expects 'old;new' format, but got " + S);
697 // Parse the symbol ordering file and warn for any duplicate entries.
698 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef MB) {
699 SetVector<StringRef> Names;
700 for (StringRef S : args::getLines(MB))
701 if (!Names.insert(S) && Config->WarnSymbolOrdering)
702 warn(MB.getBufferIdentifier() + ": duplicate ordered symbol: " + S);
704 return Names.takeVector();
707 static void parseClangOption(StringRef Opt, const Twine &Msg) {
709 raw_string_ostream OS(Err);
711 const char *Argv[] = {Config->ProgName.data(), Opt.data()};
712 if (cl::ParseCommandLineOptions(2, Argv, "", &OS))
715 error(Msg + ": " + StringRef(Err).trim());
718 // Initializes Config members by the command line options.
719 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
720 errorHandler().Verbose = Args.hasArg(OPT_verbose);
721 errorHandler().FatalWarnings =
722 Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
723 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
725 Config->AllowMultipleDefinition =
726 Args.hasFlag(OPT_allow_multiple_definition,
727 OPT_no_allow_multiple_definition, false) ||
728 hasZOption(Args, "muldefs");
729 Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary);
730 Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
731 Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
732 Config->CheckSections =
733 Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
734 Config->Chroot = Args.getLastArgValue(OPT_chroot);
735 Config->CompressDebugSections = getCompressDebugSections(Args);
736 Config->Cref = Args.hasFlag(OPT_cref, OPT_no_cref, false);
737 Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common,
738 !Args.hasArg(OPT_relocatable));
739 Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
740 Config->DisableVerify = Args.hasArg(OPT_disable_verify);
741 Config->Discard = getDiscard(Args);
742 Config->DwoDir = Args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
743 Config->DynamicLinker = getDynamicLinker(Args);
745 Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
746 Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
747 Config->EnableNewDtags =
748 Args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
749 Config->Entry = Args.getLastArgValue(OPT_entry);
750 Config->ExportDynamic =
751 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
752 Config->FilterList = args::getStrings(Args, OPT_filter);
753 Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
754 Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419);
755 Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
756 Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
757 Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
758 Config->ICF = getICF(Args);
759 Config->IgnoreDataAddressEquality =
760 Args.hasArg(OPT_ignore_data_address_equality);
761 Config->IgnoreFunctionAddressEquality =
762 Args.hasArg(OPT_ignore_function_address_equality);
763 Config->Init = Args.getLastArgValue(OPT_init, "_init");
764 Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
765 Config->LTODebugPassManager = Args.hasArg(OPT_lto_debug_pass_manager);
766 Config->LTONewPassManager = Args.hasArg(OPT_lto_new_pass_manager);
767 Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
768 Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
769 Config->LTOObjPath = Args.getLastArgValue(OPT_plugin_opt_obj_path_eq);
770 Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
771 Config->LTOSampleProfile = Args.getLastArgValue(OPT_lto_sample_profile);
772 Config->MapFile = Args.getLastArgValue(OPT_Map);
773 Config->MipsGotSize = args::getInteger(Args, OPT_mips_got_size, 0xfff0);
774 Config->MergeArmExidx =
775 Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
776 Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
777 Config->Nostdlib = Args.hasArg(OPT_nostdlib);
778 Config->OFormatBinary = isOutputFormatBinary(Args);
779 Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false);
780 Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
781 Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
782 Config->Optimize = args::getInteger(Args, OPT_O, 1);
783 Config->OrphanHandling = getOrphanHandling(Args);
784 Config->OutputFile = Args.getLastArgValue(OPT_o);
785 Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false);
786 Config->PrintIcfSections =
787 Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
788 Config->PrintGcSections =
789 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
790 Config->Rpath = getRpath(Args);
791 Config->Relocatable = Args.hasArg(OPT_relocatable);
792 Config->SaveTemps = Args.hasArg(OPT_save_temps);
793 Config->SearchPaths = args::getStrings(Args, OPT_library_path);
794 Config->SectionStartMap = getSectionStartMap(Args);
795 Config->Shared = Args.hasArg(OPT_shared);
796 Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
797 Config->SoName = Args.getLastArgValue(OPT_soname);
798 Config->SortSection = getSortSection(Args);
799 Config->Strip = getStrip(Args);
800 Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
801 Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
802 Config->Target2 = getTarget2(Args);
803 Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
804 Config->ThinLTOCachePolicy = CHECK(
805 parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
806 "--thinlto-cache-policy: invalid cache policy");
807 Config->ThinLTOEmitImportsFiles =
808 Args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files);
809 Config->ThinLTOIndexOnly = Args.hasArg(OPT_plugin_opt_thinlto_index_only) ||
810 Args.hasArg(OPT_plugin_opt_thinlto_index_only_eq);
811 Config->ThinLTOIndexOnlyArg =
812 Args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq);
813 Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
814 Config->ThinLTOObjectSuffixReplace =
815 getOldNewOptions(Args, OPT_plugin_opt_thinlto_object_suffix_replace_eq);
816 Config->ThinLTOPrefixReplace =
817 getOldNewOptions(Args, OPT_plugin_opt_thinlto_prefix_replace_eq);
818 Config->Trace = Args.hasArg(OPT_trace);
819 Config->Undefined = args::getStrings(Args, OPT_undefined);
820 Config->UndefinedVersion =
821 Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
822 Config->UseAndroidRelrTags = Args.hasFlag(
823 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
824 Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
825 Config->WarnBackrefs =
826 Args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
827 Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
828 Config->WarnSymbolOrdering =
829 Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
830 Config->ZCombreloc = getZFlag(Args, "combreloc", "nocombreloc", true);
831 Config->ZCopyreloc = getZFlag(Args, "copyreloc", "nocopyreloc", true);
832 Config->ZExecstack = getZFlag(Args, "execstack", "noexecstack", false);
833 Config->ZHazardplt = hasZOption(Args, "hazardplt");
834 Config->ZInitfirst = hasZOption(Args, "initfirst");
835 Config->ZKeepTextSectionPrefix = getZFlag(
836 Args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
837 Config->ZNodelete = hasZOption(Args, "nodelete");
838 Config->ZNodlopen = hasZOption(Args, "nodlopen");
839 Config->ZNow = getZFlag(Args, "now", "lazy", false);
840 Config->ZOrigin = hasZOption(Args, "origin");
841 Config->ZRelro = getZFlag(Args, "relro", "norelro", true);
842 Config->ZRetpolineplt = hasZOption(Args, "retpolineplt");
843 Config->ZRodynamic = hasZOption(Args, "rodynamic");
844 Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
845 Config->ZText = getZFlag(Args, "text", "notext", true);
846 Config->ZWxneeded = hasZOption(Args, "wxneeded");
848 // Parse LTO options.
849 if (auto *Arg = Args.getLastArg(OPT_plugin_opt_mcpu_eq))
850 parseClangOption(Saver.save("-mcpu=" + StringRef(Arg->getValue())),
853 for (auto *Arg : Args.filtered(OPT_plugin_opt))
854 parseClangOption(Arg->getValue(), Arg->getSpelling());
856 // Parse -mllvm options.
857 for (auto *Arg : Args.filtered(OPT_mllvm))
858 parseClangOption(Arg->getValue(), Arg->getSpelling());
860 if (Config->LTOO > 3)
861 error("invalid optimization level for LTO: " + Twine(Config->LTOO));
862 if (Config->LTOPartitions == 0)
863 error("--lto-partitions: number of threads must be > 0");
864 if (Config->ThinLTOJobs == 0)
865 error("--thinlto-jobs: number of threads must be > 0");
867 // Parse ELF{32,64}{LE,BE} and CPU type.
868 if (auto *Arg = Args.getLastArg(OPT_m)) {
869 StringRef S = Arg->getValue();
870 std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
872 Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
873 Config->Emulation = S;
876 // Parse -hash-style={sysv,gnu,both}.
877 if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
878 StringRef S = Arg->getValue();
880 Config->SysvHash = true;
882 Config->GnuHash = true;
883 else if (S == "both")
884 Config->SysvHash = Config->GnuHash = true;
886 error("unknown -hash-style: " + S);
889 if (Args.hasArg(OPT_print_map))
890 Config->MapFile = "-";
892 // --omagic is an option to create old-fashioned executables in which
893 // .text segments are writable. Today, the option is still in use to
894 // create special-purpose programs such as boot loaders. It doesn't
895 // make sense to create PT_GNU_RELRO for such executables.
897 Config->ZRelro = false;
899 std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
901 std::tie(Config->AndroidPackDynRelocs, Config->RelrPackDynRelocs) =
902 getPackDynRelocs(Args);
904 if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
905 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
906 Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer);
908 // If --retain-symbol-file is used, we'll keep only the symbols listed in
909 // the file and discard all others.
910 if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
911 Config->DefaultSymbolVersion = VER_NDX_LOCAL;
912 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
913 for (StringRef S : args::getLines(*Buffer))
914 Config->VersionScriptGlobals.push_back(
915 {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
918 bool HasExportDynamic =
919 Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
921 // Parses -dynamic-list and -export-dynamic-symbol. They make some
922 // symbols private. Note that -export-dynamic takes precedence over them
923 // as it says all symbols should be exported.
924 if (!HasExportDynamic) {
925 for (auto *Arg : Args.filtered(OPT_dynamic_list))
926 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
927 readDynamicList(*Buffer);
929 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
930 Config->DynamicList.push_back(
931 {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
934 // If --export-dynamic-symbol=foo is given and symbol foo is defined in
935 // an object file in an archive file, that object file should be pulled
936 // out and linked. (It doesn't have to behave like that from technical
937 // point of view, but this is needed for compatibility with GNU.)
938 for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
939 Config->Undefined.push_back(Arg->getValue());
941 for (auto *Arg : Args.filtered(OPT_version_script))
942 if (Optional<std::string> Path = searchScript(Arg->getValue())) {
943 if (Optional<MemoryBufferRef> Buffer = readFile(*Path))
944 readVersionScript(*Buffer);
946 error(Twine("cannot find version script ") + Arg->getValue());
950 // Some Config members do not directly correspond to any particular
951 // command line options, but computed based on other Config values.
952 // This function initialize such members. See Config.h for the details
954 static void setConfigs(opt::InputArgList &Args) {
955 ELFKind Kind = Config->EKind;
956 uint16_t Machine = Config->EMachine;
958 Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
959 Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind);
960 Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind);
962 Config->IsLE ? support::endianness::little : support::endianness::big;
963 Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS);
964 Config->Pic = Config->Pie || Config->Shared;
965 Config->Wordsize = Config->Is64 ? 8 : 4;
967 // There is an ILP32 ABI for x86-64, although it's not very popular.
968 // It is called the x32 ABI.
969 bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64);
971 // ELF defines two different ways to store relocation addends as shown below:
973 // Rel: Addends are stored to the location where relocations are applied.
974 // Rela: Addends are stored as part of relocation entry.
976 // In other words, Rela makes it easy to read addends at the price of extra
977 // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
978 // different mechanisms in the first place, but this is how the spec is
981 // You cannot choose which one, Rel or Rela, you want to use. Instead each
982 // ABI defines which one you need to use. The following expression expresses
985 (Config->Is64 || IsX32 || Machine == EM_PPC) && Machine != EM_MIPS;
987 // If the output uses REL relocations we must store the dynamic relocation
988 // addends to the output sections. We also store addends for RELA relocations
989 // if --apply-dynamic-relocs is used.
990 // We default to not writing the addends when using RELA relocations since
991 // any standard conforming tool can find it in r_addend.
992 Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs,
993 OPT_no_apply_dynamic_relocs, false) ||
997 // Returns a value of "-format" option.
998 static bool getBinaryOption(StringRef S) {
1001 if (S == "elf" || S == "default")
1003 error("unknown -format value: " + S +
1004 " (supported formats: elf, default, binary)");
1008 void LinkerDriver::createFiles(opt::InputArgList &Args) {
1009 // For --{push,pop}-state.
1010 std::vector<std::tuple<bool, bool, bool>> Stack;
1012 // Iterate over argv to process input files and positional arguments.
1013 for (auto *Arg : Args) {
1014 switch (Arg->getOption().getUnaliasedOption().getID()) {
1016 addLibrary(Arg->getValue());
1019 addFile(Arg->getValue(), /*WithLOption=*/false);
1024 std::tie(From, To) = StringRef(Arg->getValue()).split('=');
1025 readDefsym(From, MemoryBufferRef(To, "-defsym"));
1029 if (Optional<std::string> Path = searchScript(Arg->getValue())) {
1030 if (Optional<MemoryBufferRef> MB = readFile(*Path))
1031 readLinkerScript(*MB);
1034 error(Twine("cannot find linker script ") + Arg->getValue());
1037 Config->AsNeeded = true;
1040 InBinary = getBinaryOption(Arg->getValue());
1042 case OPT_no_as_needed:
1043 Config->AsNeeded = false;
1046 Config->Static = true;
1049 Config->Static = false;
1051 case OPT_whole_archive:
1052 InWholeArchive = true;
1054 case OPT_no_whole_archive:
1055 InWholeArchive = false;
1057 case OPT_just_symbols:
1058 if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue())) {
1059 Files.push_back(createObjectFile(*MB));
1060 Files.back()->JustSymbols = true;
1063 case OPT_start_group:
1064 if (InputFile::IsInGroup)
1065 error("nested --start-group");
1066 InputFile::IsInGroup = true;
1069 if (!InputFile::IsInGroup)
1070 error("stray --end-group");
1071 InputFile::IsInGroup = false;
1072 ++InputFile::NextGroupId;
1076 error("nested --start-lib");
1077 if (InputFile::IsInGroup)
1078 error("may not nest --start-lib in --start-group");
1080 InputFile::IsInGroup = true;
1084 error("stray --end-lib");
1086 InputFile::IsInGroup = false;
1087 ++InputFile::NextGroupId;
1089 case OPT_push_state:
1090 Stack.emplace_back(Config->AsNeeded, Config->Static, InWholeArchive);
1093 if (Stack.empty()) {
1094 error("unbalanced --push-state/--pop-state");
1097 std::tie(Config->AsNeeded, Config->Static, InWholeArchive) = Stack.back();
1103 if (Files.empty() && errorCount() == 0)
1104 error("no input files");
1107 // If -m <machine_type> was not given, infer it from object files.
1108 void LinkerDriver::inferMachineType() {
1109 if (Config->EKind != ELFNoneKind)
1112 for (InputFile *F : Files) {
1113 if (F->EKind == ELFNoneKind)
1115 Config->EKind = F->EKind;
1116 Config->EMachine = F->EMachine;
1117 Config->OSABI = F->OSABI;
1118 Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
1121 error("target emulation unknown: -m or at least one .o file required");
1124 // Parse -z max-page-size=<value>. The default value is defined by
1126 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
1127 uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
1128 Target->DefaultMaxPageSize);
1129 if (!isPowerOf2_64(Val))
1130 error("max-page-size: value isn't a power of 2");
1134 // Parses -image-base option.
1135 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
1136 // Because we are using "Config->MaxPageSize" here, this function has to be
1137 // called after the variable is initialized.
1138 auto *Arg = Args.getLastArg(OPT_image_base);
1142 StringRef S = Arg->getValue();
1144 if (!to_integer(S, V)) {
1145 error("-image-base: number expected, but got " + S);
1148 if ((V % Config->MaxPageSize) != 0)
1149 warn("-image-base: address isn't multiple of page size: " + S);
1153 // Parses `--exclude-libs=lib,lib,...`.
1154 // The library names may be delimited by commas or colons.
1155 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
1156 DenseSet<StringRef> Ret;
1157 for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
1158 StringRef S = Arg->getValue();
1160 size_t Pos = S.find_first_of(",:");
1161 if (Pos == StringRef::npos)
1163 Ret.insert(S.substr(0, Pos));
1164 S = S.substr(Pos + 1);
1171 // Handles the -exclude-libs option. If a static library file is specified
1172 // by the -exclude-libs option, all public symbols from the archive become
1173 // private unless otherwise specified by version scripts or something.
1174 // A special library name "ALL" means all archive files.
1176 // This is not a popular option, but some programs such as bionic libc use it.
1177 template <class ELFT>
1178 static void excludeLibs(opt::InputArgList &Args) {
1179 DenseSet<StringRef> Libs = getExcludeLibs(Args);
1180 bool All = Libs.count("ALL");
1182 auto Visit = [&](InputFile *File) {
1183 if (!File->ArchiveName.empty())
1184 if (All || Libs.count(path::filename(File->ArchiveName)))
1185 for (Symbol *Sym : File->getSymbols())
1186 if (!Sym->isLocal() && Sym->File == File)
1187 Sym->VersionId = VER_NDX_LOCAL;
1190 for (InputFile *File : ObjectFiles)
1193 for (BitcodeFile *File : BitcodeFiles)
1197 // Force Sym to be entered in the output. Used for -u or equivalent.
1198 template <class ELFT> static void handleUndefined(StringRef Name) {
1199 Symbol *Sym = Symtab->find(Name);
1203 // Since symbol S may not be used inside the program, LTO may
1204 // eliminate it. Mark the symbol as "used" to prevent it.
1205 Sym->IsUsedInRegularObj = true;
1208 Symtab->fetchLazy<ELFT>(Sym);
1211 template <class ELFT> static bool shouldDemote(Symbol &Sym) {
1212 // If all references to a DSO happen to be weak, the DSO is not added to
1213 // DT_NEEDED. If that happens, we need to eliminate shared symbols created
1214 // from the DSO. Otherwise, they become dangling references that point to a
1215 // non-existent DSO.
1216 if (auto *S = dyn_cast<SharedSymbol>(&Sym))
1217 return !S->getFile<ELFT>().IsNeeded;
1219 // We are done processing archives, so lazy symbols that were used but not
1220 // found can be converted to undefined. We could also just delete the other
1221 // lazy symbols, but that seems to be more work than it is worth.
1222 return Sym.isLazy() && Sym.IsUsedInRegularObj;
1225 // Some files, such as .so or files between -{start,end}-lib may be removed
1226 // after their symbols are added to the symbol table. If that happens, we
1227 // need to remove symbols that refer files that no longer exist, so that
1228 // they won't appear in the symbol table of the output file.
1230 // We remove symbols by demoting them to undefined symbol.
1231 template <class ELFT> static void demoteSymbols() {
1232 for (Symbol *Sym : Symtab->getSymbols()) {
1233 if (shouldDemote<ELFT>(*Sym)) {
1234 bool Used = Sym->Used;
1235 replaceSymbol<Undefined>(Sym, nullptr, Sym->getName(), Sym->Binding,
1236 Sym->StOther, Sym->Type);
1242 // The section referred to by S is considered address-significant. Set the
1243 // KeepUnique flag on the section if appropriate.
1244 static void markAddrsig(Symbol *S) {
1245 if (auto *D = dyn_cast_or_null<Defined>(S))
1247 // We don't need to keep text sections unique under --icf=all even if they
1248 // are address-significant.
1249 if (Config->ICF == ICFLevel::Safe || !(D->Section->Flags & SHF_EXECINSTR))
1250 D->Section->KeepUnique = true;
1253 // Record sections that define symbols mentioned in --keep-unique <symbol>
1254 // and symbols referred to by address-significance tables. These sections are
1255 // ineligible for ICF.
1256 template <class ELFT>
1257 static void findKeepUniqueSections(opt::InputArgList &Args) {
1258 for (auto *Arg : Args.filtered(OPT_keep_unique)) {
1259 StringRef Name = Arg->getValue();
1260 auto *D = dyn_cast_or_null<Defined>(Symtab->find(Name));
1261 if (!D || !D->Section) {
1262 warn("could not find symbol " + Name + " to keep unique");
1265 D->Section->KeepUnique = true;
1268 // --icf=all --ignore-data-address-equality means that we can ignore
1269 // the dynsym and address-significance tables entirely.
1270 if (Config->ICF == ICFLevel::All && Config->IgnoreDataAddressEquality)
1273 // Symbols in the dynsym could be address-significant in other executables
1274 // or DSOs, so we conservatively mark them as address-significant.
1275 for (Symbol *S : Symtab->getSymbols())
1276 if (S->includeInDynsym())
1279 // Visit the address-significance table in each object file and mark each
1280 // referenced symbol as address-significant.
1281 for (InputFile *F : ObjectFiles) {
1282 auto *Obj = cast<ObjFile<ELFT>>(F);
1283 ArrayRef<Symbol *> Syms = Obj->getSymbols();
1284 if (Obj->AddrsigSec) {
1285 ArrayRef<uint8_t> Contents =
1286 check(Obj->getObj().getSectionContents(Obj->AddrsigSec));
1287 const uint8_t *Cur = Contents.begin();
1288 while (Cur != Contents.end()) {
1291 uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
1293 fatal(toString(F) + ": could not decode addrsig section: " + Err);
1294 markAddrsig(Syms[SymIndex]);
1298 // If an object file does not have an address-significance table,
1299 // conservatively mark all of its symbols as address-significant.
1300 for (Symbol *S : Syms)
1306 // Do actual linking. Note that when this function is called,
1307 // all linker scripts have already been parsed.
1308 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1309 Target = getTarget();
1311 Config->MaxPageSize = getMaxPageSize(Args);
1312 Config->ImageBase = getImageBase(Args);
1314 // If a -hash-style option was not given, set to a default value,
1315 // which varies depending on the target.
1316 if (!Args.hasArg(OPT_hash_style)) {
1317 if (Config->EMachine == EM_MIPS)
1318 Config->SysvHash = true;
1320 Config->SysvHash = Config->GnuHash = true;
1323 // Default output filename is "a.out" by the Unix tradition.
1324 if (Config->OutputFile.empty())
1325 Config->OutputFile = "a.out";
1327 // Fail early if the output file or map file is not writable. If a user has a
1328 // long link, e.g. due to a large LTO link, they do not wish to run it and
1329 // find that it failed because there was a mistake in their command-line.
1330 if (auto E = tryCreateFile(Config->OutputFile))
1331 error("cannot open output file " + Config->OutputFile + ": " + E.message());
1332 if (auto E = tryCreateFile(Config->MapFile))
1333 error("cannot open map file " + Config->MapFile + ": " + E.message());
1337 // Use default entry point name if no name was given via the command
1338 // line nor linker scripts. For some reason, MIPS entry point name is
1339 // different from others.
1340 Config->WarnMissingEntry =
1341 (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
1342 if (Config->Entry.empty() && !Config->Relocatable)
1343 Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
1345 // Handle --trace-symbol.
1346 for (auto *Arg : Args.filtered(OPT_trace_symbol))
1347 Symtab->trace(Arg->getValue());
1349 // Add all files to the symbol table. This will add almost all
1350 // symbols that we need to the symbol table.
1351 for (InputFile *F : Files)
1352 Symtab->addFile<ELFT>(F);
1354 // Now that we have every file, we can decide if we will need a
1355 // dynamic symbol table.
1356 // We need one if we were asked to export dynamic symbols or if we are
1357 // producing a shared library.
1358 // We also need one if any shared libraries are used and for pie executables
1359 // (probably because the dynamic linker needs it).
1360 Config->HasDynSymTab =
1361 !SharedFiles.empty() || Config->Pic || Config->ExportDynamic;
1363 // Some symbols (such as __ehdr_start) are defined lazily only when there
1364 // are undefined symbols for them, so we add these to trigger that logic.
1365 for (StringRef Sym : Script->ReferencedSymbols)
1366 Symtab->addUndefined<ELFT>(Sym);
1368 // Handle the `--undefined <sym>` options.
1369 for (StringRef S : Config->Undefined)
1370 handleUndefined<ELFT>(S);
1372 // If an entry symbol is in a static archive, pull out that file now
1373 // to complete the symbol table. After this, no new names except a
1374 // few linker-synthesized ones will be added to the symbol table.
1375 handleUndefined<ELFT>(Config->Entry);
1377 // Return if there were name resolution errors.
1381 // Now when we read all script files, we want to finalize order of linker
1382 // script commands, which can be not yet final because of INSERT commands.
1383 Script->processInsertCommands();
1385 // We want to declare linker script's symbols early,
1386 // so that we can version them.
1387 // They also might be exported if referenced by DSOs.
1388 Script->declareSymbols();
1390 // Handle the -exclude-libs option.
1391 if (Args.hasArg(OPT_exclude_libs))
1392 excludeLibs<ELFT>(Args);
1394 // Create ElfHeader early. We need a dummy section in
1395 // addReservedSymbols to mark the created symbols as not absolute.
1396 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1397 Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1399 // We need to create some reserved symbols such as _end. Create them.
1400 if (!Config->Relocatable)
1401 addReservedSymbols();
1403 // Apply version scripts.
1405 // For a relocatable output, version scripts don't make sense, and
1406 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1407 // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1408 if (!Config->Relocatable)
1409 Symtab->scanVersionScript();
1411 // Create wrapped symbols for -wrap option.
1412 for (auto *Arg : Args.filtered(OPT_wrap))
1413 Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1415 // Do link-time optimization if given files are LLVM bitcode files.
1416 // This compiles bitcode files into real object files.
1417 Symtab->addCombinedLTOObject<ELFT>();
1421 // If -thinlto-index-only is given, we should create only "index
1422 // files" and not object files. Index file creation is already done
1423 // in addCombinedLTOObject, so we are done if that's the case.
1424 if (Config->ThinLTOIndexOnly)
1427 // Apply symbol renames for -wrap.
1428 Symtab->applySymbolWrap();
1430 // Now that we have a complete list of input files.
1431 // Beyond this point, no new files are added.
1432 // Aggregate all input sections into one place.
1433 for (InputFile *F : ObjectFiles)
1434 for (InputSectionBase *S : F->getSections())
1435 if (S && S != &InputSection::Discarded)
1436 InputSections.push_back(S);
1437 for (BinaryFile *F : BinaryFiles)
1438 for (InputSectionBase *S : F->getSections())
1439 InputSections.push_back(cast<InputSection>(S));
1441 // We do not want to emit debug sections if --strip-all
1442 // or -strip-debug are given.
1443 if (Config->Strip != StripPolicy::None)
1444 llvm::erase_if(InputSections, [](InputSectionBase *S) {
1445 return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1448 Config->EFlags = Target->calcEFlags();
1450 if (Config->EMachine == EM_ARM) {
1451 // FIXME: These warnings can be removed when lld only uses these features
1452 // when the input objects have been compiled with an architecture that
1454 if (Config->ARMHasBlx == false)
1455 warn("lld uses blx instruction, no object with architecture supporting "
1456 "feature detected.");
1457 if (Config->ARMJ1J2BranchEncoding == false)
1458 warn("lld uses extended branch encoding, no object with architecture "
1459 "supporting feature detected.");
1460 if (Config->ARMHasMovtMovw == false)
1461 warn("lld may use movt/movw, no object with architecture supporting "
1462 "feature detected.");
1465 // This adds a .comment section containing a version string. We have to add it
1466 // before decompressAndMergeSections because the .comment section is a
1467 // mergeable section.
1468 if (!Config->Relocatable)
1469 InputSections.push_back(createCommentSection());
1471 // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1472 // and identical code folding.
1473 decompressSections();
1474 splitSections<ELFT>();
1476 demoteSymbols<ELFT>();
1478 if (Config->ICF != ICFLevel::None) {
1479 findKeepUniqueSections<ELFT>(Args);
1483 // Read the callgraph now that we know what was gced or icfed
1484 if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1485 if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1486 readCallGraph(*Buffer);
1488 // Write the result to the file.
1489 writeResult<ELFT>();