1 //===- Driver.cpp ---------------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // The driver drives the entire linking process. It is responsible for
10 // parsing command line options and doing whatever it is instructed to do.
12 // One notable thing in the LLD's driver when compared to other linkers is
13 // that the LLD's driver is agnostic on the host operating system.
14 // Other linkers usually have implicit default values (such as a dynamic
15 // linker path or library paths) for each host OS.
17 // I don't think implicit default values are useful because they are
18 // usually explicitly specified by the compiler driver. They can even
19 // be harmful when you are doing cross-linking. Therefore, in LLD, we
20 // simply trust the compiler driver to pass all required options and
21 // don't try to make effort on our side.
23 //===----------------------------------------------------------------------===//
28 #include "InputFiles.h"
29 #include "InputSection.h"
30 #include "LinkerScript.h"
32 #include "OutputSections.h"
33 #include "ScriptParser.h"
34 #include "SymbolTable.h"
36 #include "SyntheticSections.h"
39 #include "lld/Common/Args.h"
40 #include "lld/Common/Driver.h"
41 #include "lld/Common/ErrorHandler.h"
42 #include "lld/Common/Filesystem.h"
43 #include "lld/Common/Memory.h"
44 #include "lld/Common/Strings.h"
45 #include "lld/Common/TargetOptionsCommandFlags.h"
46 #include "lld/Common/Threads.h"
47 #include "lld/Common/Version.h"
48 #include "llvm/ADT/SetVector.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSwitch.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compression.h"
53 #include "llvm/Support/GlobPattern.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;
66 using namespace llvm::support;
69 using namespace lld::elf;
71 Configuration *elf::config;
72 LinkerDriver *elf::driver;
74 static void setConfigs(opt::InputArgList &args);
75 static void readConfigs(opt::InputArgList &args);
77 bool elf::link(ArrayRef<const char *> args, bool canExitEarly,
79 errorHandler().logName = args::getFilenameWithoutExe(args[0]);
80 errorHandler().errorLimitExceededMsg =
81 "too many errors emitted, stopping now (use "
82 "-error-limit=0 to see all errors)";
83 errorHandler().errorOS = &error;
84 errorHandler().exitEarly = canExitEarly;
85 errorHandler().colorDiagnostics = error.has_colors();
87 inputSections.clear();
88 outputSections.clear();
94 config = make<Configuration>();
95 driver = make<LinkerDriver>();
96 script = make<LinkerScript>();
97 symtab = make<SymbolTable>();
100 memset(&in, 0, sizeof(in));
102 partitions = {Partition()};
104 SharedFile::vernauxNum = 0;
106 config->progName = args[0];
110 // Exit immediately if we don't need to return to the caller.
111 // This saves time because the overhead of calling destructors
112 // for all globally-allocated objects is not negligible.
114 exitLld(errorCount() ? 1 : 0);
117 return !errorCount();
120 // Parses a linker -m option.
121 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
124 if (s.endswith("_fbsd")) {
126 osabi = ELFOSABI_FREEBSD;
129 std::pair<ELFKind, uint16_t> ret =
130 StringSwitch<std::pair<ELFKind, uint16_t>>(s)
131 .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
132 {ELF64LEKind, EM_AARCH64})
133 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
134 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
135 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
136 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
137 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
138 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
139 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
140 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
141 .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
142 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
143 .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
144 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
145 .Case("elf_i386", {ELF32LEKind, EM_386})
146 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
147 .Default({ELFNoneKind, EM_NONE});
149 if (ret.first == ELFNoneKind)
150 error("unknown emulation: " + emul);
151 return std::make_tuple(ret.first, ret.second, osabi);
154 // Returns slices of MB by parsing MB as an archive file.
155 // Each slice consists of a member file in the archive.
156 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
157 MemoryBufferRef mb) {
158 std::unique_ptr<Archive> file =
159 CHECK(Archive::create(mb),
160 mb.getBufferIdentifier() + ": failed to parse archive");
162 std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
163 Error err = Error::success();
164 bool addToTar = file->isThin() && tar;
165 for (const ErrorOr<Archive::Child> &cOrErr : file->children(err)) {
167 CHECK(cOrErr, mb.getBufferIdentifier() +
168 ": could not get the child of the archive");
169 MemoryBufferRef mbref =
170 CHECK(c.getMemoryBufferRef(),
171 mb.getBufferIdentifier() +
172 ": could not get the buffer for a child of the archive");
174 tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
175 v.push_back(std::make_pair(mbref, c.getChildOffset()));
178 fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
179 toString(std::move(err)));
181 // Take ownership of memory buffers created for members of thin archives.
182 for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
183 make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
188 // Opens a file and create a file object. Path has to be resolved already.
189 void LinkerDriver::addFile(StringRef path, bool withLOption) {
190 using namespace sys::fs;
192 Optional<MemoryBufferRef> buffer = readFile(path);
193 if (!buffer.hasValue())
195 MemoryBufferRef mbref = *buffer;
197 if (config->formatBinary) {
198 files.push_back(make<BinaryFile>(mbref));
202 switch (identify_magic(mbref.getBuffer())) {
203 case file_magic::unknown:
204 readLinkerScript(mbref);
206 case file_magic::archive: {
207 // Handle -whole-archive.
208 if (inWholeArchive) {
209 for (const auto &p : getArchiveMembers(mbref))
210 files.push_back(createObjectFile(p.first, path, p.second));
214 std::unique_ptr<Archive> file =
215 CHECK(Archive::create(mbref), path + ": failed to parse archive");
217 // If an archive file has no symbol table, it is likely that a user
218 // is attempting LTO and using a default ar command that doesn't
219 // understand the LLVM bitcode file. It is a pretty common error, so
220 // we'll handle it as if it had a symbol table.
221 if (!file->isEmpty() && !file->hasSymbolTable()) {
222 // Check if all members are bitcode files. If not, ignore, which is the
223 // default action without the LTO hack described above.
224 for (const std::pair<MemoryBufferRef, uint64_t> &p :
225 getArchiveMembers(mbref))
226 if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) {
227 error(path + ": archive has no index; run ranlib to add one");
231 for (const std::pair<MemoryBufferRef, uint64_t> &p :
232 getArchiveMembers(mbref))
233 files.push_back(make<LazyObjFile>(p.first, path, p.second));
237 // Handle the regular case.
238 files.push_back(make<ArchiveFile>(std::move(file)));
241 case file_magic::elf_shared_object:
242 if (config->isStatic || config->relocatable) {
243 error("attempted static link of dynamic object " + path);
247 // DSOs usually have DT_SONAME tags in their ELF headers, and the
248 // sonames are used to identify DSOs. But if they are missing,
249 // they are identified by filenames. We don't know whether the new
250 // file has a DT_SONAME or not because we haven't parsed it yet.
251 // Here, we set the default soname for the file because we might
254 // If a file was specified by -lfoo, the directory part is not
255 // significant, as a user did not specify it. This behavior is
256 // compatible with GNU.
258 make<SharedFile>(mbref, withLOption ? path::filename(path) : path));
260 case file_magic::bitcode:
261 case file_magic::elf_relocatable:
263 files.push_back(make<LazyObjFile>(mbref, "", 0));
265 files.push_back(createObjectFile(mbref));
268 error(path + ": unknown file type");
272 // Add a given library by searching it from input search paths.
273 void LinkerDriver::addLibrary(StringRef name) {
274 if (Optional<std::string> path = searchLibrary(name))
275 addFile(*path, /*withLOption=*/true);
277 error("unable to find library -l" + name);
280 // This function is called on startup. We need this for LTO since
281 // LTO calls LLVM functions to compile bitcode files to native code.
282 // Technically this can be delayed until we read bitcode files, but
283 // we don't bother to do lazily because the initialization is fast.
284 static void initLLVM() {
285 InitializeAllTargets();
286 InitializeAllTargetMCs();
287 InitializeAllAsmPrinters();
288 InitializeAllAsmParsers();
291 // Some command line options or some combinations of them are not allowed.
292 // This function checks for such errors.
293 static void checkOptions() {
294 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
295 // table which is a relatively new feature.
296 if (config->emachine == EM_MIPS && config->gnuHash)
297 error("the .gnu.hash section is not compatible with the MIPS target");
299 if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
300 error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
302 if (config->tocOptimize && config->emachine != EM_PPC64)
303 error("--toc-optimize is only supported on the PowerPC64 target");
305 if (config->pie && config->shared)
306 error("-shared and -pie may not be used together");
308 if (!config->shared && !config->filterList.empty())
309 error("-F may not be used without -shared");
311 if (!config->shared && !config->auxiliaryList.empty())
312 error("-f may not be used without -shared");
314 if (!config->relocatable && !config->defineCommon)
315 error("-no-define-common not supported in non relocatable output");
317 if (config->zText && config->zIfuncNoplt)
318 error("-z text and -z ifunc-noplt may not be used together");
320 if (config->relocatable) {
322 error("-r and -shared may not be used together");
323 if (config->gcSections)
324 error("-r and --gc-sections may not be used together");
325 if (config->gdbIndex)
326 error("-r and --gdb-index may not be used together");
327 if (config->icf != ICFLevel::None)
328 error("-r and --icf may not be used together");
330 error("-r and -pie may not be used together");
333 if (config->executeOnly) {
334 if (config->emachine != EM_AARCH64)
335 error("-execute-only is only supported on AArch64 targets");
337 if (config->singleRoRx && !script->hasSectionsCommand)
338 error("-execute-only and -no-rosegment cannot be used together");
341 if (config->zRetpolineplt && config->requireCET)
342 error("--require-cet may not be used with -z retpolineplt");
344 if (config->emachine != EM_AARCH64) {
346 error("--pac-plt only supported on AArch64");
347 if (config->forceBTI)
348 error("--force-bti only supported on AArch64");
352 static const char *getReproduceOption(opt::InputArgList &args) {
353 if (auto *arg = args.getLastArg(OPT_reproduce))
354 return arg->getValue();
355 return getenv("LLD_REPRODUCE");
358 static bool hasZOption(opt::InputArgList &args, StringRef key) {
359 for (auto *arg : args.filtered(OPT_z))
360 if (key == arg->getValue())
365 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
367 for (auto *arg : args.filtered_reverse(OPT_z)) {
368 if (k1 == arg->getValue())
370 if (k2 == arg->getValue())
376 static bool isKnownZFlag(StringRef s) {
377 return s == "combreloc" || s == "copyreloc" || s == "defs" ||
378 s == "execstack" || s == "global" || s == "hazardplt" ||
379 s == "ifunc-noplt" || s == "initfirst" || s == "interpose" ||
380 s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
381 s == "nocombreloc" || s == "nocopyreloc" || s == "nodefaultlib" ||
382 s == "nodelete" || s == "nodlopen" || s == "noexecstack" ||
383 s == "nokeep-text-section-prefix" || s == "norelro" || s == "notext" ||
384 s == "now" || s == "origin" || s == "relro" || s == "retpolineplt" ||
385 s == "rodynamic" || s == "text" || s == "wxneeded" ||
386 s.startswith("common-page-size") || s.startswith("max-page-size=") ||
387 s.startswith("stack-size=");
390 // Report an error for an unknown -z option.
391 static void checkZOptions(opt::InputArgList &args) {
392 for (auto *arg : args.filtered(OPT_z))
393 if (!isKnownZFlag(arg->getValue()))
394 error("unknown -z value: " + StringRef(arg->getValue()));
397 void LinkerDriver::main(ArrayRef<const char *> argsArr) {
399 opt::InputArgList args = parser.parse(argsArr.slice(1));
401 // Interpret this flag early because error() depends on them.
402 errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
406 if (args.hasArg(OPT_help)) {
411 // Handle -v or -version.
413 // A note about "compatible with GNU linkers" message: this is a hack for
414 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
415 // still the newest version in March 2017) or earlier to recognize LLD as
416 // a GNU compatible linker. As long as an output for the -v option
417 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
419 // This is somewhat ugly hack, but in reality, we had no choice other
420 // than doing this. Considering the very long release cycle of Libtool,
421 // it is not easy to improve it to recognize LLD as a GNU compatible
422 // linker in a timely manner. Even if we can make it, there are still a
423 // lot of "configure" scripts out there that are generated by old version
424 // of Libtool. We cannot convince every software developer to migrate to
425 // the latest version and re-generate scripts. So we have this hack.
426 if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
427 message(getLLDVersion() + " (compatible with GNU linkers)");
429 if (const char *path = getReproduceOption(args)) {
430 // Note that --reproduce is a debug option so you can ignore it
431 // if you are trying to understand the whole picture of the code.
432 Expected<std::unique_ptr<TarWriter>> errOrWriter =
433 TarWriter::create(path, path::stem(path));
435 tar = std::move(*errOrWriter);
436 tar->append("response.txt", createResponseFile(args));
437 tar->append("version.txt", getLLDVersion() + "\n");
439 error("--reproduce: " + toString(errOrWriter.takeError()));
445 // The behavior of -v or --version is a bit strange, but this is
446 // needed for compatibility with GNU linkers.
447 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
449 if (args.hasArg(OPT_version))
463 // The Target instance handles target-specific stuff, such as applying
464 // relocations or writing a PLT section. It also contains target-dependent
465 // values such as a default image base address.
466 target = getTarget();
468 switch (config->ekind) {
482 llvm_unreachable("unknown Config->EKind");
486 static std::string getRpath(opt::InputArgList &args) {
487 std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
488 return llvm::join(v.begin(), v.end(), ":");
491 // Determines what we should do if there are remaining unresolved
492 // symbols after the name resolution.
493 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &args) {
494 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
495 OPT_warn_unresolved_symbols, true)
496 ? UnresolvedPolicy::ReportError
497 : UnresolvedPolicy::Warn;
499 // Process the last of -unresolved-symbols, -no-undefined or -z defs.
500 for (auto *arg : llvm::reverse(args)) {
501 switch (arg->getOption().getID()) {
502 case OPT_unresolved_symbols: {
503 StringRef s = arg->getValue();
504 if (s == "ignore-all" || s == "ignore-in-object-files")
505 return UnresolvedPolicy::Ignore;
506 if (s == "ignore-in-shared-libs" || s == "report-all")
508 error("unknown --unresolved-symbols value: " + s);
511 case OPT_no_undefined:
514 if (StringRef(arg->getValue()) == "defs")
520 // -shared implies -unresolved-symbols=ignore-all because missing
521 // symbols are likely to be resolved at runtime using other DSOs.
523 return UnresolvedPolicy::Ignore;
527 static Target2Policy getTarget2(opt::InputArgList &args) {
528 StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
530 return Target2Policy::Rel;
532 return Target2Policy::Abs;
534 return Target2Policy::GotRel;
535 error("unknown --target2 option: " + s);
536 return Target2Policy::GotRel;
539 static bool isOutputFormatBinary(opt::InputArgList &args) {
540 StringRef s = args.getLastArgValue(OPT_oformat, "elf");
543 if (!s.startswith("elf"))
544 error("unknown --oformat value: " + s);
548 static DiscardPolicy getDiscard(opt::InputArgList &args) {
549 if (args.hasArg(OPT_relocatable))
550 return DiscardPolicy::None;
553 args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
555 return DiscardPolicy::Default;
556 if (arg->getOption().getID() == OPT_discard_all)
557 return DiscardPolicy::All;
558 if (arg->getOption().getID() == OPT_discard_locals)
559 return DiscardPolicy::Locals;
560 return DiscardPolicy::None;
563 static StringRef getDynamicLinker(opt::InputArgList &args) {
564 auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
565 if (!arg || arg->getOption().getID() == OPT_no_dynamic_linker)
567 return arg->getValue();
570 static ICFLevel getICF(opt::InputArgList &args) {
571 auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
572 if (!arg || arg->getOption().getID() == OPT_icf_none)
573 return ICFLevel::None;
574 if (arg->getOption().getID() == OPT_icf_safe)
575 return ICFLevel::Safe;
576 return ICFLevel::All;
579 static StripPolicy getStrip(opt::InputArgList &args) {
580 if (args.hasArg(OPT_relocatable))
581 return StripPolicy::None;
583 auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
585 return StripPolicy::None;
586 if (arg->getOption().getID() == OPT_strip_all)
587 return StripPolicy::All;
588 return StripPolicy::Debug;
591 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
592 const opt::Arg &arg) {
594 if (s.startswith("0x"))
596 if (!to_integer(s, va, 16))
597 error("invalid argument: " + arg.getAsString(args));
601 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
602 StringMap<uint64_t> ret;
603 for (auto *arg : args.filtered(OPT_section_start)) {
606 std::tie(name, addr) = StringRef(arg->getValue()).split('=');
607 ret[name] = parseSectionAddress(addr, args, *arg);
610 if (auto *arg = args.getLastArg(OPT_Ttext))
611 ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
612 if (auto *arg = args.getLastArg(OPT_Tdata))
613 ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
614 if (auto *arg = args.getLastArg(OPT_Tbss))
615 ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
619 static SortSectionPolicy getSortSection(opt::InputArgList &args) {
620 StringRef s = args.getLastArgValue(OPT_sort_section);
621 if (s == "alignment")
622 return SortSectionPolicy::Alignment;
624 return SortSectionPolicy::Name;
626 error("unknown --sort-section rule: " + s);
627 return SortSectionPolicy::Default;
630 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
631 StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
633 return OrphanHandlingPolicy::Warn;
635 return OrphanHandlingPolicy::Error;
637 error("unknown --orphan-handling mode: " + s);
638 return OrphanHandlingPolicy::Place;
641 // Parse --build-id or --build-id=<style>. We handle "tree" as a
642 // synonym for "sha1" because all our hash functions including
643 // -build-id=sha1 are actually tree hashes for performance reasons.
644 static std::pair<BuildIdKind, std::vector<uint8_t>>
645 getBuildId(opt::InputArgList &args) {
646 auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
648 return {BuildIdKind::None, {}};
650 if (arg->getOption().getID() == OPT_build_id)
651 return {BuildIdKind::Fast, {}};
653 StringRef s = arg->getValue();
655 return {BuildIdKind::Fast, {}};
657 return {BuildIdKind::Md5, {}};
658 if (s == "sha1" || s == "tree")
659 return {BuildIdKind::Sha1, {}};
661 return {BuildIdKind::Uuid, {}};
662 if (s.startswith("0x"))
663 return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
666 error("unknown --build-id style: " + s);
667 return {BuildIdKind::None, {}};
670 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
671 StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
673 return {true, false};
675 return {false, true};
676 if (s == "android+relr")
680 error("unknown -pack-dyn-relocs format: " + s);
681 return {false, false};
684 static void readCallGraph(MemoryBufferRef mb) {
685 // Build a map from symbol name to section
686 DenseMap<StringRef, Symbol *> map;
687 for (InputFile *file : objectFiles)
688 for (Symbol *sym : file->getSymbols())
689 map[sym->getName()] = sym;
691 auto findSection = [&](StringRef name) -> InputSectionBase * {
692 Symbol *sym = map.lookup(name);
694 if (config->warnSymbolOrdering)
695 warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
698 maybeWarnUnorderableSymbol(sym);
700 if (Defined *dr = dyn_cast_or_null<Defined>(sym))
701 return dyn_cast_or_null<InputSectionBase>(dr->section);
705 for (StringRef line : args::getLines(mb)) {
706 SmallVector<StringRef, 3> fields;
707 line.split(fields, ' ');
710 if (fields.size() != 3 || !to_integer(fields[2], count)) {
711 error(mb.getBufferIdentifier() + ": parse error");
715 if (InputSectionBase *from = findSection(fields[0]))
716 if (InputSectionBase *to = findSection(fields[1]))
717 config->callGraphProfile[std::make_pair(from, to)] += count;
721 template <class ELFT> static void readCallGraphsFromObjectFiles() {
722 for (auto file : objectFiles) {
723 auto *obj = cast<ObjFile<ELFT>>(file);
725 for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
726 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
727 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
728 if (!fromSym || !toSym)
731 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
732 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
734 config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
739 static bool getCompressDebugSections(opt::InputArgList &args) {
740 StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
744 error("unknown --compress-debug-sections value: " + s);
745 if (!zlib::isAvailable())
746 error("--compress-debug-sections: zlib is not available");
750 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
752 auto *arg = args.getLastArg(id);
756 StringRef s = arg->getValue();
757 std::pair<StringRef, StringRef> ret = s.split(';');
758 if (ret.second.empty())
759 error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
763 // Parse the symbol ordering file and warn for any duplicate entries.
764 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
765 SetVector<StringRef> names;
766 for (StringRef s : args::getLines(mb))
767 if (!names.insert(s) && config->warnSymbolOrdering)
768 warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
770 return names.takeVector();
773 static void parseClangOption(StringRef opt, const Twine &msg) {
775 raw_string_ostream os(err);
777 const char *argv[] = {config->progName.data(), opt.data()};
778 if (cl::ParseCommandLineOptions(2, argv, "", &os))
781 error(msg + ": " + StringRef(err).trim());
784 // Initializes Config members by the command line options.
785 static void readConfigs(opt::InputArgList &args) {
786 errorHandler().verbose = args.hasArg(OPT_verbose);
787 errorHandler().fatalWarnings =
788 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
789 errorHandler().vsDiagnostics =
790 args.hasArg(OPT_visual_studio_diagnostics_format, false);
791 threadsEnabled = args.hasFlag(OPT_threads, OPT_no_threads, true);
793 config->allowMultipleDefinition =
794 args.hasFlag(OPT_allow_multiple_definition,
795 OPT_no_allow_multiple_definition, false) ||
796 hasZOption(args, "muldefs");
797 config->allowShlibUndefined =
798 args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined,
799 args.hasArg(OPT_shared));
800 config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
801 config->bsymbolic = args.hasArg(OPT_Bsymbolic);
802 config->bsymbolicFunctions = args.hasArg(OPT_Bsymbolic_functions);
803 config->checkSections =
804 args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
805 config->chroot = args.getLastArgValue(OPT_chroot);
806 config->compressDebugSections = getCompressDebugSections(args);
807 config->cref = args.hasFlag(OPT_cref, OPT_no_cref, false);
808 config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
809 !args.hasArg(OPT_relocatable));
810 config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
811 config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
812 config->disableVerify = args.hasArg(OPT_disable_verify);
813 config->discard = getDiscard(args);
814 config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
815 config->dynamicLinker = getDynamicLinker(args);
817 args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
818 config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
819 config->emitRelocs = args.hasArg(OPT_emit_relocs);
820 config->callGraphProfileSort = args.hasFlag(
821 OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
822 config->enableNewDtags =
823 args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
824 config->entry = args.getLastArgValue(OPT_entry);
825 config->executeOnly =
826 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
827 config->exportDynamic =
828 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
829 config->filterList = args::getStrings(args, OPT_filter);
830 config->fini = args.getLastArgValue(OPT_fini, "_fini");
831 config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419);
832 config->forceBTI = args.hasArg(OPT_force_bti);
833 config->requireCET = args.hasArg(OPT_require_cet);
834 config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
835 config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
836 config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
837 config->icf = getICF(args);
838 config->ignoreDataAddressEquality =
839 args.hasArg(OPT_ignore_data_address_equality);
840 config->ignoreFunctionAddressEquality =
841 args.hasArg(OPT_ignore_function_address_equality);
842 config->init = args.getLastArgValue(OPT_init, "_init");
843 config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
844 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
845 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
846 config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
847 config->ltoNewPassManager = args.hasArg(OPT_lto_new_pass_manager);
848 config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
849 config->ltoo = args::getInteger(args, OPT_lto_O, 2);
850 config->ltoObjPath = args.getLastArgValue(OPT_plugin_opt_obj_path_eq);
851 config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
852 config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
853 config->mapFile = args.getLastArgValue(OPT_Map);
854 config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
855 config->mergeArmExidx =
856 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
857 config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
858 config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
859 config->nostdlib = args.hasArg(OPT_nostdlib);
860 config->oFormatBinary = isOutputFormatBinary(args);
861 config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
862 config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
863 config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
864 config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
865 config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
866 config->optimize = args::getInteger(args, OPT_O, 1);
867 config->orphanHandling = getOrphanHandling(args);
868 config->outputFile = args.getLastArgValue(OPT_o);
869 config->pacPlt = args.hasArg(OPT_pac_plt);
870 config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
871 config->printIcfSections =
872 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
873 config->printGcSections =
874 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
875 config->printSymbolOrder =
876 args.getLastArgValue(OPT_print_symbol_order);
877 config->rpath = getRpath(args);
878 config->relocatable = args.hasArg(OPT_relocatable);
879 config->saveTemps = args.hasArg(OPT_save_temps);
880 config->searchPaths = args::getStrings(args, OPT_library_path);
881 config->sectionStartMap = getSectionStartMap(args);
882 config->shared = args.hasArg(OPT_shared);
883 config->singleRoRx = args.hasArg(OPT_no_rosegment);
884 config->soName = args.getLastArgValue(OPT_soname);
885 config->sortSection = getSortSection(args);
886 config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
887 config->strip = getStrip(args);
888 config->sysroot = args.getLastArgValue(OPT_sysroot);
889 config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
890 config->target2 = getTarget2(args);
891 config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
892 config->thinLTOCachePolicy = CHECK(
893 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
894 "--thinlto-cache-policy: invalid cache policy");
895 config->thinLTOEmitImportsFiles =
896 args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files);
897 config->thinLTOIndexOnly = args.hasArg(OPT_plugin_opt_thinlto_index_only) ||
898 args.hasArg(OPT_plugin_opt_thinlto_index_only_eq);
899 config->thinLTOIndexOnlyArg =
900 args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq);
901 config->thinLTOJobs = args::getInteger(args, OPT_thinlto_jobs, -1u);
902 config->thinLTOObjectSuffixReplace =
903 getOldNewOptions(args, OPT_plugin_opt_thinlto_object_suffix_replace_eq);
904 config->thinLTOPrefixReplace =
905 getOldNewOptions(args, OPT_plugin_opt_thinlto_prefix_replace_eq);
906 config->trace = args.hasArg(OPT_trace);
907 config->undefined = args::getStrings(args, OPT_undefined);
908 config->undefinedVersion =
909 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
910 config->useAndroidRelrTags = args.hasFlag(
911 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
912 config->unresolvedSymbols = getUnresolvedSymbolPolicy(args);
913 config->warnBackrefs =
914 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
915 config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
916 config->warnIfuncTextrel =
917 args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
918 config->warnSymbolOrdering =
919 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
920 config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
921 config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
922 config->zExecstack = getZFlag(args, "execstack", "noexecstack", false);
923 config->zGlobal = hasZOption(args, "global");
924 config->zHazardplt = hasZOption(args, "hazardplt");
925 config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
926 config->zInitfirst = hasZOption(args, "initfirst");
927 config->zInterpose = hasZOption(args, "interpose");
928 config->zKeepTextSectionPrefix = getZFlag(
929 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
930 config->zNodefaultlib = hasZOption(args, "nodefaultlib");
931 config->zNodelete = hasZOption(args, "nodelete");
932 config->zNodlopen = hasZOption(args, "nodlopen");
933 config->zNow = getZFlag(args, "now", "lazy", false);
934 config->zOrigin = hasZOption(args, "origin");
935 config->zRelro = getZFlag(args, "relro", "norelro", true);
936 config->zRetpolineplt = hasZOption(args, "retpolineplt");
937 config->zRodynamic = hasZOption(args, "rodynamic");
938 config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
939 config->zText = getZFlag(args, "text", "notext", true);
940 config->zWxneeded = hasZOption(args, "wxneeded");
942 // Parse LTO options.
943 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
944 parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
947 for (auto *arg : args.filtered(OPT_plugin_opt))
948 parseClangOption(arg->getValue(), arg->getSpelling());
950 // Parse -mllvm options.
951 for (auto *arg : args.filtered(OPT_mllvm))
952 parseClangOption(arg->getValue(), arg->getSpelling());
954 if (config->ltoo > 3)
955 error("invalid optimization level for LTO: " + Twine(config->ltoo));
956 if (config->ltoPartitions == 0)
957 error("--lto-partitions: number of threads must be > 0");
958 if (config->thinLTOJobs == 0)
959 error("--thinlto-jobs: number of threads must be > 0");
961 if (config->splitStackAdjustSize < 0)
962 error("--split-stack-adjust-size: size must be >= 0");
964 // Parse ELF{32,64}{LE,BE} and CPU type.
965 if (auto *arg = args.getLastArg(OPT_m)) {
966 StringRef s = arg->getValue();
967 std::tie(config->ekind, config->emachine, config->osabi) =
970 (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
971 config->emulation = s;
974 // Parse -hash-style={sysv,gnu,both}.
975 if (auto *arg = args.getLastArg(OPT_hash_style)) {
976 StringRef s = arg->getValue();
978 config->sysvHash = true;
980 config->gnuHash = true;
981 else if (s == "both")
982 config->sysvHash = config->gnuHash = true;
984 error("unknown -hash-style: " + s);
987 if (args.hasArg(OPT_print_map))
988 config->mapFile = "-";
990 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
991 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
993 if (config->nmagic || config->omagic)
994 config->zRelro = false;
996 std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
998 std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
999 getPackDynRelocs(args);
1001 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1002 if (args.hasArg(OPT_call_graph_ordering_file))
1003 error("--symbol-ordering-file and --call-graph-order-file "
1004 "may not be used together");
1005 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1006 config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1007 // Also need to disable CallGraphProfileSort to prevent
1008 // LLD order symbols with CGProfile
1009 config->callGraphProfileSort = false;
1013 // If --retain-symbol-file is used, we'll keep only the symbols listed in
1014 // the file and discard all others.
1015 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1016 config->defaultSymbolVersion = VER_NDX_LOCAL;
1017 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1018 for (StringRef s : args::getLines(*buffer))
1019 config->versionScriptGlobals.push_back(
1020 {s, /*IsExternCpp*/ false, /*HasWildcard*/ false});
1023 bool hasExportDynamic =
1024 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
1026 // Parses -dynamic-list and -export-dynamic-symbol. They make some
1027 // symbols private. Note that -export-dynamic takes precedence over them
1028 // as it says all symbols should be exported.
1029 if (!hasExportDynamic) {
1030 for (auto *arg : args.filtered(OPT_dynamic_list))
1031 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1032 readDynamicList(*buffer);
1034 for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1035 config->dynamicList.push_back(
1036 {arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
1039 // If --export-dynamic-symbol=foo is given and symbol foo is defined in
1040 // an object file in an archive file, that object file should be pulled
1041 // out and linked. (It doesn't have to behave like that from technical
1042 // point of view, but this is needed for compatibility with GNU.)
1043 for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1044 config->undefined.push_back(arg->getValue());
1046 for (auto *arg : args.filtered(OPT_version_script))
1047 if (Optional<std::string> path = searchScript(arg->getValue())) {
1048 if (Optional<MemoryBufferRef> buffer = readFile(*path))
1049 readVersionScript(*buffer);
1051 error(Twine("cannot find version script ") + arg->getValue());
1055 // Some Config members do not directly correspond to any particular
1056 // command line options, but computed based on other Config values.
1057 // This function initialize such members. See Config.h for the details
1059 static void setConfigs(opt::InputArgList &args) {
1060 ELFKind k = config->ekind;
1061 uint16_t m = config->emachine;
1063 config->copyRelocs = (config->relocatable || config->emitRelocs);
1064 config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1065 config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1066 config->endianness = config->isLE ? endianness::little : endianness::big;
1067 config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1068 config->isPic = config->pie || config->shared;
1069 config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1070 config->wordsize = config->is64 ? 8 : 4;
1072 // ELF defines two different ways to store relocation addends as shown below:
1074 // Rel: Addends are stored to the location where relocations are applied.
1075 // Rela: Addends are stored as part of relocation entry.
1077 // In other words, Rela makes it easy to read addends at the price of extra
1078 // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
1079 // different mechanisms in the first place, but this is how the spec is
1082 // You cannot choose which one, Rel or Rela, you want to use. Instead each
1083 // ABI defines which one you need to use. The following expression expresses
1085 config->isRela = m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON ||
1086 m == EM_PPC || m == EM_PPC64 || m == EM_RISCV ||
1089 // If the output uses REL relocations we must store the dynamic relocation
1090 // addends to the output sections. We also store addends for RELA relocations
1091 // if --apply-dynamic-relocs is used.
1092 // We default to not writing the addends when using RELA relocations since
1093 // any standard conforming tool can find it in r_addend.
1094 config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1095 OPT_no_apply_dynamic_relocs, false) ||
1098 config->tocOptimize =
1099 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1102 // Returns a value of "-format" option.
1103 static bool isFormatBinary(StringRef s) {
1106 if (s == "elf" || s == "default")
1108 error("unknown -format value: " + s +
1109 " (supported formats: elf, default, binary)");
1113 void LinkerDriver::createFiles(opt::InputArgList &args) {
1114 // For --{push,pop}-state.
1115 std::vector<std::tuple<bool, bool, bool>> stack;
1117 // Iterate over argv to process input files and positional arguments.
1118 for (auto *arg : args) {
1119 switch (arg->getOption().getID()) {
1121 addLibrary(arg->getValue());
1124 addFile(arg->getValue(), /*withLOption=*/false);
1129 std::tie(from, to) = StringRef(arg->getValue()).split('=');
1130 if (from.empty() || to.empty())
1131 error("-defsym: syntax error: " + StringRef(arg->getValue()));
1133 readDefsym(from, MemoryBufferRef(to, "-defsym"));
1137 if (Optional<std::string> path = searchScript(arg->getValue())) {
1138 if (Optional<MemoryBufferRef> mb = readFile(*path))
1139 readLinkerScript(*mb);
1142 error(Twine("cannot find linker script ") + arg->getValue());
1145 config->asNeeded = true;
1148 config->formatBinary = isFormatBinary(arg->getValue());
1150 case OPT_no_as_needed:
1151 config->asNeeded = false;
1156 config->isStatic = true;
1159 config->isStatic = false;
1161 case OPT_whole_archive:
1162 inWholeArchive = true;
1164 case OPT_no_whole_archive:
1165 inWholeArchive = false;
1167 case OPT_just_symbols:
1168 if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1169 files.push_back(createObjectFile(*mb));
1170 files.back()->justSymbols = true;
1173 case OPT_start_group:
1174 if (InputFile::isInGroup)
1175 error("nested --start-group");
1176 InputFile::isInGroup = true;
1179 if (!InputFile::isInGroup)
1180 error("stray --end-group");
1181 InputFile::isInGroup = false;
1182 ++InputFile::nextGroupId;
1186 error("nested --start-lib");
1187 if (InputFile::isInGroup)
1188 error("may not nest --start-lib in --start-group");
1190 InputFile::isInGroup = true;
1194 error("stray --end-lib");
1196 InputFile::isInGroup = false;
1197 ++InputFile::nextGroupId;
1199 case OPT_push_state:
1200 stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1203 if (stack.empty()) {
1204 error("unbalanced --push-state/--pop-state");
1207 std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1213 if (files.empty() && errorCount() == 0)
1214 error("no input files");
1217 // If -m <machine_type> was not given, infer it from object files.
1218 void LinkerDriver::inferMachineType() {
1219 if (config->ekind != ELFNoneKind)
1222 for (InputFile *f : files) {
1223 if (f->ekind == ELFNoneKind)
1225 config->ekind = f->ekind;
1226 config->emachine = f->emachine;
1227 config->osabi = f->osabi;
1228 config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1231 error("target emulation unknown: -m or at least one .o file required");
1234 // Parse -z max-page-size=<value>. The default value is defined by
1236 static uint64_t getMaxPageSize(opt::InputArgList &args) {
1237 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1238 target->defaultMaxPageSize);
1239 if (!isPowerOf2_64(val))
1240 error("max-page-size: value isn't a power of 2");
1241 if (config->nmagic || config->omagic) {
1242 if (val != target->defaultMaxPageSize)
1243 warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1249 // Parse -z common-page-size=<value>. The default value is defined by
1251 static uint64_t getCommonPageSize(opt::InputArgList &args) {
1252 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1253 target->defaultCommonPageSize);
1254 if (!isPowerOf2_64(val))
1255 error("common-page-size: value isn't a power of 2");
1256 if (config->nmagic || config->omagic) {
1257 if (val != target->defaultCommonPageSize)
1258 warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1261 // commonPageSize can't be larger than maxPageSize.
1262 if (val > config->maxPageSize)
1263 val = config->maxPageSize;
1267 // Parses -image-base option.
1268 static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1269 // Because we are using "Config->maxPageSize" here, this function has to be
1270 // called after the variable is initialized.
1271 auto *arg = args.getLastArg(OPT_image_base);
1275 StringRef s = arg->getValue();
1277 if (!to_integer(s, v)) {
1278 error("-image-base: number expected, but got " + s);
1281 if ((v % config->maxPageSize) != 0)
1282 warn("-image-base: address isn't multiple of page size: " + s);
1286 // Parses `--exclude-libs=lib,lib,...`.
1287 // The library names may be delimited by commas or colons.
1288 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1289 DenseSet<StringRef> ret;
1290 for (auto *arg : args.filtered(OPT_exclude_libs)) {
1291 StringRef s = arg->getValue();
1293 size_t pos = s.find_first_of(",:");
1294 if (pos == StringRef::npos)
1296 ret.insert(s.substr(0, pos));
1297 s = s.substr(pos + 1);
1304 // Handles the -exclude-libs option. If a static library file is specified
1305 // by the -exclude-libs option, all public symbols from the archive become
1306 // private unless otherwise specified by version scripts or something.
1307 // A special library name "ALL" means all archive files.
1309 // This is not a popular option, but some programs such as bionic libc use it.
1310 static void excludeLibs(opt::InputArgList &args) {
1311 DenseSet<StringRef> libs = getExcludeLibs(args);
1312 bool all = libs.count("ALL");
1314 auto visit = [&](InputFile *file) {
1315 if (!file->archiveName.empty())
1316 if (all || libs.count(path::filename(file->archiveName)))
1317 for (Symbol *sym : file->getSymbols())
1318 if (!sym->isLocal() && sym->file == file)
1319 sym->versionId = VER_NDX_LOCAL;
1322 for (InputFile *file : objectFiles)
1325 for (BitcodeFile *file : bitcodeFiles)
1329 // Force Sym to be entered in the output. Used for -u or equivalent.
1330 static void handleUndefined(Symbol *sym) {
1331 // Since a symbol may not be used inside the program, LTO may
1332 // eliminate it. Mark the symbol as "used" to prevent it.
1333 sym->isUsedInRegularObj = true;
1339 // As an extention to GNU linkers, lld supports a variant of `-u`
1340 // which accepts wildcard patterns. All symbols that match a given
1341 // pattern are handled as if they were given by `-u`.
1342 static void handleUndefinedGlob(StringRef arg) {
1343 Expected<GlobPattern> pat = GlobPattern::create(arg);
1345 error("--undefined-glob: " + toString(pat.takeError()));
1349 std::vector<Symbol *> syms;
1350 symtab->forEachSymbol([&](Symbol *sym) {
1351 // Calling Sym->fetch() from here is not safe because it may
1352 // add new symbols to the symbol table, invalidating the
1353 // current iterator. So we just keep a note.
1354 if (pat->match(sym->getName()))
1355 syms.push_back(sym);
1358 for (Symbol *sym : syms)
1359 handleUndefined(sym);
1362 static void handleLibcall(StringRef name) {
1363 Symbol *sym = symtab->find(name);
1364 if (!sym || !sym->isLazy())
1368 if (auto *lo = dyn_cast<LazyObject>(sym))
1371 mb = cast<LazyArchive>(sym)->getMemberBuffer();
1377 // Replaces common symbols with defined symbols reside in .bss sections.
1378 // This function is called after all symbol names are resolved. As a
1379 // result, the passes after the symbol resolution won't see any
1380 // symbols of type CommonSymbol.
1381 static void replaceCommonSymbols() {
1382 symtab->forEachSymbol([](Symbol *sym) {
1383 auto *s = dyn_cast<CommonSymbol>(sym);
1387 auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1388 bss->file = s->file;
1390 inputSections.push_back(bss);
1391 s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
1392 /*value=*/0, s->size, bss});
1396 // If all references to a DSO happen to be weak, the DSO is not added
1397 // to DT_NEEDED. If that happens, we need to eliminate shared symbols
1398 // created from the DSO. Otherwise, they become dangling references
1399 // that point to a non-existent DSO.
1400 static void demoteSharedSymbols() {
1401 symtab->forEachSymbol([](Symbol *sym) {
1402 auto *s = dyn_cast<SharedSymbol>(sym);
1403 if (!s || s->getFile().isNeeded)
1406 bool used = s->used;
1407 s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type});
1412 // The section referred to by `s` is considered address-significant. Set the
1413 // keepUnique flag on the section if appropriate.
1414 static void markAddrsig(Symbol *s) {
1415 if (auto *d = dyn_cast_or_null<Defined>(s))
1417 // We don't need to keep text sections unique under --icf=all even if they
1418 // are address-significant.
1419 if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
1420 d->section->keepUnique = true;
1423 // Record sections that define symbols mentioned in --keep-unique <symbol>
1424 // and symbols referred to by address-significance tables. These sections are
1425 // ineligible for ICF.
1426 template <class ELFT>
1427 static void findKeepUniqueSections(opt::InputArgList &args) {
1428 for (auto *arg : args.filtered(OPT_keep_unique)) {
1429 StringRef name = arg->getValue();
1430 auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1431 if (!d || !d->section) {
1432 warn("could not find symbol " + name + " to keep unique");
1435 d->section->keepUnique = true;
1438 // --icf=all --ignore-data-address-equality means that we can ignore
1439 // the dynsym and address-significance tables entirely.
1440 if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
1443 // Symbols in the dynsym could be address-significant in other executables
1444 // or DSOs, so we conservatively mark them as address-significant.
1445 symtab->forEachSymbol([&](Symbol *sym) {
1446 if (sym->includeInDynsym())
1450 // Visit the address-significance table in each object file and mark each
1451 // referenced symbol as address-significant.
1452 for (InputFile *f : objectFiles) {
1453 auto *obj = cast<ObjFile<ELFT>>(f);
1454 ArrayRef<Symbol *> syms = obj->getSymbols();
1455 if (obj->addrsigSec) {
1456 ArrayRef<uint8_t> contents =
1457 check(obj->getObj().getSectionContents(obj->addrsigSec));
1458 const uint8_t *cur = contents.begin();
1459 while (cur != contents.end()) {
1462 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1464 fatal(toString(f) + ": could not decode addrsig section: " + err);
1465 markAddrsig(syms[symIndex]);
1469 // If an object file does not have an address-significance table,
1470 // conservatively mark all of its symbols as address-significant.
1471 for (Symbol *s : syms)
1477 // This function reads a symbol partition specification section. These sections
1478 // are used to control which partition a symbol is allocated to. See
1479 // https://lld.llvm.org/Partitions.html for more details on partitions.
1480 template <typename ELFT>
1481 static void readSymbolPartitionSection(InputSectionBase *s) {
1482 // Read the relocation that refers to the partition's entry point symbol.
1484 if (s->areRelocsRela)
1485 sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]);
1487 sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]);
1488 if (!isa<Defined>(sym) || !sym->includeInDynsym())
1491 StringRef partName = reinterpret_cast<const char *>(s->data().data());
1492 for (Partition &part : partitions) {
1493 if (part.name == partName) {
1494 sym->partition = part.getNumber();
1499 // Forbid partitions from being used on incompatible targets, and forbid them
1500 // from being used together with various linker features that assume a single
1501 // set of output sections.
1502 if (script->hasSectionsCommand)
1503 error(toString(s->file) +
1504 ": partitions cannot be used with the SECTIONS command");
1505 if (script->hasPhdrsCommands())
1506 error(toString(s->file) +
1507 ": partitions cannot be used with the PHDRS command");
1508 if (!config->sectionStartMap.empty())
1509 error(toString(s->file) + ": partitions cannot be used with "
1510 "--section-start, -Ttext, -Tdata or -Tbss");
1511 if (config->emachine == EM_MIPS)
1512 error(toString(s->file) + ": partitions cannot be used on this target");
1514 // Impose a limit of no more than 254 partitions. This limit comes from the
1515 // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1516 // the amount of space devoted to the partition number in RankFlags.
1517 if (partitions.size() == 254)
1518 fatal("may not have more than 254 partitions");
1520 partitions.emplace_back();
1521 Partition &newPart = partitions.back();
1522 newPart.name = partName;
1523 sym->partition = newPart.getNumber();
1526 static Symbol *addUndefined(StringRef name) {
1527 return symtab->addSymbol(
1528 Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
1531 // This function is where all the optimizations of link-time
1532 // optimization takes place. When LTO is in use, some input files are
1533 // not in native object file format but in the LLVM bitcode format.
1534 // This function compiles bitcode files into a few big native files
1535 // using LLVM functions and replaces bitcode symbols with the results.
1536 // Because all bitcode files that the program consists of are passed to
1537 // the compiler at once, it can do a whole-program optimization.
1538 template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1539 // Compile bitcode files and replace bitcode symbols.
1540 lto.reset(new BitcodeCompiler);
1541 for (BitcodeFile *file : bitcodeFiles)
1544 for (InputFile *file : lto->compile()) {
1545 auto *obj = cast<ObjFile<ELFT>>(file);
1546 obj->parse(/*ignoreComdats=*/true);
1547 for (Symbol *sym : obj->getGlobalSymbols())
1548 sym->parseSymbolVersion();
1549 objectFiles.push_back(file);
1553 // The --wrap option is a feature to rename symbols so that you can write
1554 // wrappers for existing functions. If you pass `-wrap=foo`, all
1555 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1556 // expected to write `wrap_foo` function as a wrapper). The original
1557 // symbol becomes accessible as `real_foo`, so you can call that from your
1560 // This data structure is instantiated for each -wrap option.
1561 struct WrappedSymbol {
1567 // Handles -wrap option.
1569 // This function instantiates wrapper symbols. At this point, they seem
1570 // like they are not being used at all, so we explicitly set some flags so
1571 // that LTO won't eliminate them.
1572 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
1573 std::vector<WrappedSymbol> v;
1574 DenseSet<StringRef> seen;
1576 for (auto *arg : args.filtered(OPT_wrap)) {
1577 StringRef name = arg->getValue();
1578 if (!seen.insert(name).second)
1581 Symbol *sym = symtab->find(name);
1585 Symbol *real = addUndefined(saver.save("__real_" + name));
1586 Symbol *wrap = addUndefined(saver.save("__wrap_" + name));
1587 v.push_back({sym, real, wrap});
1589 // We want to tell LTO not to inline symbols to be overwritten
1590 // because LTO doesn't know the final symbol contents after renaming.
1591 real->canInline = false;
1592 sym->canInline = false;
1594 // Tell LTO not to eliminate these symbols.
1595 sym->isUsedInRegularObj = true;
1596 wrap->isUsedInRegularObj = true;
1601 // Do renaming for -wrap by updating pointers to symbols.
1603 // When this function is executed, only InputFiles and symbol table
1604 // contain pointers to symbol objects. We visit them to replace pointers,
1605 // so that wrapped symbols are swapped as instructed by the command line.
1606 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
1607 DenseMap<Symbol *, Symbol *> map;
1608 for (const WrappedSymbol &w : wrapped) {
1609 map[w.sym] = w.wrap;
1610 map[w.real] = w.sym;
1613 // Update pointers in input files.
1614 parallelForEach(objectFiles, [&](InputFile *file) {
1615 MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
1616 for (size_t i = 0, e = syms.size(); i != e; ++i)
1617 if (Symbol *s = map.lookup(syms[i]))
1621 // Update pointers in the symbol table.
1622 for (const WrappedSymbol &w : wrapped)
1623 symtab->wrap(w.sym, w.real, w.wrap);
1626 // To enable CET (x86's hardware-assited control flow enforcement), each
1627 // source file must be compiled with -fcf-protection. Object files compiled
1628 // with the flag contain feature flags indicating that they are compatible
1629 // with CET. We enable the feature only when all object files are compatible
1632 // This function returns the merged feature flags. If 0, we cannot enable CET.
1633 // This is also the case with AARCH64's BTI and PAC which use the similar
1634 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
1636 // Note that the CET-aware PLT is not implemented yet. We do error
1638 template <class ELFT> static uint32_t getAndFeatures() {
1639 if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
1640 config->emachine != EM_AARCH64)
1644 for (InputFile *f : objectFiles) {
1645 uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1646 if (config->forceBTI && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
1647 warn(toString(f) + ": --force-bti: file does not have BTI property");
1648 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1649 } else if (!features && config->requireCET)
1650 error(toString(f) + ": --require-cet: file is not compatible with CET");
1654 // Force enable pointer authentication Plt, we don't warn in this case as
1655 // this does not require support in the object for correctness.
1657 ret |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1662 static const char *libcallRoutineNames[] = {
1663 #define HANDLE_LIBCALL(code, name) name,
1664 #include "llvm/IR/RuntimeLibcalls.def"
1665 #undef HANDLE_LIBCALL
1668 // Do actual linking. Note that when this function is called,
1669 // all linker scripts have already been parsed.
1670 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1671 // If a -hash-style option was not given, set to a default value,
1672 // which varies depending on the target.
1673 if (!args.hasArg(OPT_hash_style)) {
1674 if (config->emachine == EM_MIPS)
1675 config->sysvHash = true;
1677 config->sysvHash = config->gnuHash = true;
1680 // Default output filename is "a.out" by the Unix tradition.
1681 if (config->outputFile.empty())
1682 config->outputFile = "a.out";
1684 // Fail early if the output file or map file is not writable. If a user has a
1685 // long link, e.g. due to a large LTO link, they do not wish to run it and
1686 // find that it failed because there was a mistake in their command-line.
1687 if (auto e = tryCreateFile(config->outputFile))
1688 error("cannot open output file " + config->outputFile + ": " + e.message());
1689 if (auto e = tryCreateFile(config->mapFile))
1690 error("cannot open map file " + config->mapFile + ": " + e.message());
1694 // Use default entry point name if no name was given via the command
1695 // line nor linker scripts. For some reason, MIPS entry point name is
1696 // different from others.
1697 config->warnMissingEntry =
1698 (!config->entry.empty() || (!config->shared && !config->relocatable));
1699 if (config->entry.empty() && !config->relocatable)
1700 config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
1702 // Handle --trace-symbol.
1703 for (auto *arg : args.filtered(OPT_trace_symbol))
1704 symtab->insert(arg->getValue())->traced = true;
1706 // Add all files to the symbol table. This will add almost all
1707 // symbols that we need to the symbol table. This process might
1708 // add files to the link, via autolinking, these files are always
1709 // appended to the Files vector.
1710 for (size_t i = 0; i < files.size(); ++i)
1711 parseFile(files[i]);
1713 // Now that we have every file, we can decide if we will need a
1714 // dynamic symbol table.
1715 // We need one if we were asked to export dynamic symbols or if we are
1716 // producing a shared library.
1717 // We also need one if any shared libraries are used and for pie executables
1718 // (probably because the dynamic linker needs it).
1719 config->hasDynSymTab =
1720 !sharedFiles.empty() || config->isPic || config->exportDynamic;
1722 // Some symbols (such as __ehdr_start) are defined lazily only when there
1723 // are undefined symbols for them, so we add these to trigger that logic.
1724 for (StringRef name : script->referencedSymbols)
1727 // Handle the `--undefined <sym>` options.
1728 for (StringRef arg : config->undefined)
1729 if (Symbol *sym = symtab->find(arg))
1730 handleUndefined(sym);
1732 // If an entry symbol is in a static archive, pull out that file now.
1733 if (Symbol *sym = symtab->find(config->entry))
1734 handleUndefined(sym);
1736 // Handle the `--undefined-glob <pattern>` options.
1737 for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
1738 handleUndefinedGlob(pat);
1740 // If any of our inputs are bitcode files, the LTO code generator may create
1741 // references to certain library functions that might not be explicit in the
1742 // bitcode file's symbol table. If any of those library functions are defined
1743 // in a bitcode file in an archive member, we need to arrange to use LTO to
1744 // compile those archive members by adding them to the link beforehand.
1746 // However, adding all libcall symbols to the link can have undesired
1747 // consequences. For example, the libgcc implementation of
1748 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1749 // that aborts the program if the Linux kernel does not support 64-bit
1750 // atomics, which would prevent the program from running even if it does not
1751 // use 64-bit atomics.
1753 // Therefore, we only add libcall symbols to the link before LTO if we have
1754 // to, i.e. if the symbol's definition is in bitcode. Any other required
1755 // libcall symbols will be added to the link after LTO when we add the LTO
1756 // object file to the link.
1757 if (!bitcodeFiles.empty())
1758 for (const char *s : libcallRoutineNames)
1761 // Return if there were name resolution errors.
1765 // Now when we read all script files, we want to finalize order of linker
1766 // script commands, which can be not yet final because of INSERT commands.
1767 script->processInsertCommands();
1769 // We want to declare linker script's symbols early,
1770 // so that we can version them.
1771 // They also might be exported if referenced by DSOs.
1772 script->declareSymbols();
1774 // Handle the -exclude-libs option.
1775 if (args.hasArg(OPT_exclude_libs))
1778 // Create elfHeader early. We need a dummy section in
1779 // addReservedSymbols to mark the created symbols as not absolute.
1780 Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1781 Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
1783 // Create wrapped symbols for -wrap option.
1784 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
1786 // We need to create some reserved symbols such as _end. Create them.
1787 if (!config->relocatable)
1788 addReservedSymbols();
1790 // Apply version scripts.
1792 // For a relocatable output, version scripts don't make sense, and
1793 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1794 // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1795 if (!config->relocatable)
1796 symtab->scanVersionScript();
1798 // Do link-time optimization if given files are LLVM bitcode files.
1799 // This compiles bitcode files into real object files.
1801 // With this the symbol table should be complete. After this, no new names
1802 // except a few linker-synthesized ones will be added to the symbol table.
1803 compileBitcodeFiles<ELFT>();
1807 // If -thinlto-index-only is given, we should create only "index
1808 // files" and not object files. Index file creation is already done
1809 // in addCombinedLTOObject, so we are done if that's the case.
1810 if (config->thinLTOIndexOnly)
1813 // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1814 // an output file in bitcode and exit, so that you can just get a
1815 // combined bitcode file.
1816 if (config->emitLLVM)
1819 // Apply symbol renames for -wrap.
1820 if (!wrapped.empty())
1821 wrapSymbols(wrapped);
1823 // Now that we have a complete list of input files.
1824 // Beyond this point, no new files are added.
1825 // Aggregate all input sections into one place.
1826 for (InputFile *f : objectFiles)
1827 for (InputSectionBase *s : f->getSections())
1828 if (s && s != &InputSection::discarded)
1829 inputSections.push_back(s);
1830 for (BinaryFile *f : binaryFiles)
1831 for (InputSectionBase *s : f->getSections())
1832 inputSections.push_back(cast<InputSection>(s));
1834 llvm::erase_if(inputSections, [](InputSectionBase *s) {
1835 if (s->type == SHT_LLVM_SYMPART) {
1836 readSymbolPartitionSection<ELFT>(s);
1840 // We do not want to emit debug sections if --strip-all
1841 // or -strip-debug are given.
1842 return config->strip != StripPolicy::None &&
1843 (s->name.startswith(".debug") || s->name.startswith(".zdebug"));
1846 // Now that the number of partitions is fixed, save a pointer to the main
1848 mainPart = &partitions[0];
1850 // Read .note.gnu.property sections from input object files which
1851 // contain a hint to tweak linker's and loader's behaviors.
1852 config->andFeatures = getAndFeatures<ELFT>();
1854 // The Target instance handles target-specific stuff, such as applying
1855 // relocations or writing a PLT section. It also contains target-dependent
1856 // values such as a default image base address.
1857 target = getTarget();
1859 config->eflags = target->calcEFlags();
1860 // maxPageSize (sometimes called abi page size) is the maximum page size that
1861 // the output can be run on. For example if the OS can use 4k or 64k page
1862 // sizes then maxPageSize must be 64k for the output to be useable on both.
1863 // All important alignment decisions must use this value.
1864 config->maxPageSize = getMaxPageSize(args);
1865 // commonPageSize is the most common page size that the output will be run on.
1866 // For example if an OS can use 4k or 64k page sizes and 4k is more common
1867 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
1868 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
1869 // is limited to writing trap instructions on the last executable segment.
1870 config->commonPageSize = getCommonPageSize(args);
1872 config->imageBase = getImageBase(args);
1874 if (config->emachine == EM_ARM) {
1875 // FIXME: These warnings can be removed when lld only uses these features
1876 // when the input objects have been compiled with an architecture that
1878 if (config->armHasBlx == false)
1879 warn("lld uses blx instruction, no object with architecture supporting "
1880 "feature detected");
1883 // This adds a .comment section containing a version string. We have to add it
1884 // before mergeSections because the .comment section is a mergeable section.
1885 if (!config->relocatable)
1886 inputSections.push_back(createCommentSection());
1888 // Replace common symbols with regular symbols.
1889 replaceCommonSymbols();
1891 // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1892 // and identical code folding.
1893 splitSections<ELFT>();
1895 demoteSharedSymbols();
1897 if (config->icf != ICFLevel::None) {
1898 findKeepUniqueSections<ELFT>(args);
1902 // Read the callgraph now that we know what was gced or icfed
1903 if (config->callGraphProfileSort) {
1904 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
1905 if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1906 readCallGraph(*buffer);
1907 readCallGraphsFromObjectFiles<ELFT>();
1910 // Write the result to the file.
1911 writeResult<ELFT>();