[AMDGPU][AsmParser][NFC] Translate parsed MIMG instructions to MCInsts automatically.
[llvm-project.git] / lld / ELF / Driver.cpp
blob26283e1fac0969e35284358d6ebff2bbaf53cc32
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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 ctx.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 //===----------------------------------------------------------------------===//
25 #include "Driver.h"
26 #include "Config.h"
27 #include "ICF.h"
28 #include "InputFiles.h"
29 #include "InputSection.h"
30 #include "LTO.h"
31 #include "LinkerScript.h"
32 #include "MarkLive.h"
33 #include "OutputSections.h"
34 #include "ScriptParser.h"
35 #include "SymbolTable.h"
36 #include "Symbols.h"
37 #include "SyntheticSections.h"
38 #include "Target.h"
39 #include "Writer.h"
40 #include "lld/Common/Args.h"
41 #include "lld/Common/CommonLinkerContext.h"
42 #include "lld/Common/Driver.h"
43 #include "lld/Common/ErrorHandler.h"
44 #include "lld/Common/Filesystem.h"
45 #include "lld/Common/Memory.h"
46 #include "lld/Common/Strings.h"
47 #include "lld/Common/TargetOptionsCommandFlags.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/Config/llvm-config.h"
53 #include "llvm/LTO/LTO.h"
54 #include "llvm/Object/Archive.h"
55 #include "llvm/Remarks/HotnessThresholdParser.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Compression.h"
58 #include "llvm/Support/FileSystem.h"
59 #include "llvm/Support/GlobPattern.h"
60 #include "llvm/Support/LEB128.h"
61 #include "llvm/Support/Parallel.h"
62 #include "llvm/Support/Path.h"
63 #include "llvm/Support/TarWriter.h"
64 #include "llvm/Support/TargetSelect.h"
65 #include "llvm/Support/TimeProfiler.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include <cstdlib>
68 #include <tuple>
69 #include <utility>
71 using namespace llvm;
72 using namespace llvm::ELF;
73 using namespace llvm::object;
74 using namespace llvm::sys;
75 using namespace llvm::support;
76 using namespace lld;
77 using namespace lld::elf;
79 ConfigWrapper elf::config;
80 Ctx elf::ctx;
82 static void setConfigs(opt::InputArgList &args);
83 static void readConfigs(opt::InputArgList &args);
85 void elf::errorOrWarn(const Twine &msg) {
86 if (config->noinhibitExec)
87 warn(msg);
88 else
89 error(msg);
92 void Ctx::reset() {
93 driver = LinkerDriver();
94 memoryBuffers.clear();
95 objectFiles.clear();
96 sharedFiles.clear();
97 binaryFiles.clear();
98 bitcodeFiles.clear();
99 lazyBitcodeFiles.clear();
100 inputSections.clear();
101 ehInputSections.clear();
102 duplicates.clear();
103 nonPrevailingSyms.clear();
104 whyExtractRecords.clear();
105 backwardReferences.clear();
106 hasSympart.store(false, std::memory_order_relaxed);
107 needsTlsLd.store(false, std::memory_order_relaxed);
110 llvm::raw_fd_ostream Ctx::openAuxiliaryFile(llvm::StringRef filename,
111 std::error_code &ec) {
112 using namespace llvm::sys::fs;
113 OpenFlags flags =
114 auxiliaryFiles.insert(filename).second ? OF_None : OF_Append;
115 return {filename, ec, flags};
118 namespace lld {
119 namespace elf {
120 bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
121 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
122 // This driver-specific context will be freed later by unsafeLldMain().
123 auto *ctx = new CommonLinkerContext;
125 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
126 ctx->e.cleanupCallback = []() {
127 elf::ctx.reset();
128 symtab = SymbolTable();
130 outputSections.clear();
131 symAux.clear();
133 tar = nullptr;
134 in.reset();
136 partitions.clear();
137 partitions.emplace_back();
139 SharedFile::vernauxNum = 0;
141 ctx->e.logName = args::getFilenameWithoutExe(args[0]);
142 ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use "
143 "--error-limit=0 to see all errors)";
145 config = ConfigWrapper();
146 script = std::make_unique<LinkerScript>();
148 symAux.emplace_back();
150 partitions.clear();
151 partitions.emplace_back();
153 config->progName = args[0];
155 elf::ctx.driver.linkerMain(args);
157 return errorCount() == 0;
159 } // namespace elf
160 } // namespace lld
162 // Parses a linker -m option.
163 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
164 uint8_t osabi = 0;
165 StringRef s = emul;
166 if (s.ends_with("_fbsd")) {
167 s = s.drop_back(5);
168 osabi = ELFOSABI_FREEBSD;
171 std::pair<ELFKind, uint16_t> ret =
172 StringSwitch<std::pair<ELFKind, uint16_t>>(s)
173 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
174 .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})
175 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
176 .Cases("armelfb", "armelfb_linux_eabi", {ELF32BEKind, EM_ARM})
177 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
178 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
179 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
180 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
181 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
182 .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})
183 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
184 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
185 .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
186 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
187 .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
188 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
189 .Case("elf_i386", {ELF32LEKind, EM_386})
190 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
191 .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
192 .Case("msp430elf", {ELF32LEKind, EM_MSP430})
193 .Case("elf64_amdgpu", {ELF64LEKind, EM_AMDGPU})
194 .Default({ELFNoneKind, EM_NONE});
196 if (ret.first == ELFNoneKind)
197 error("unknown emulation: " + emul);
198 if (ret.second == EM_MSP430)
199 osabi = ELFOSABI_STANDALONE;
200 else if (ret.second == EM_AMDGPU)
201 osabi = ELFOSABI_AMDGPU_HSA;
202 return std::make_tuple(ret.first, ret.second, osabi);
205 // Returns slices of MB by parsing MB as an archive file.
206 // Each slice consists of a member file in the archive.
207 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
208 MemoryBufferRef mb) {
209 std::unique_ptr<Archive> file =
210 CHECK(Archive::create(mb),
211 mb.getBufferIdentifier() + ": failed to parse archive");
213 std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
214 Error err = Error::success();
215 bool addToTar = file->isThin() && tar;
216 for (const Archive::Child &c : file->children(err)) {
217 MemoryBufferRef mbref =
218 CHECK(c.getMemoryBufferRef(),
219 mb.getBufferIdentifier() +
220 ": could not get the buffer for a child of the archive");
221 if (addToTar)
222 tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
223 v.push_back(std::make_pair(mbref, c.getChildOffset()));
225 if (err)
226 fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
227 toString(std::move(err)));
229 // Take ownership of memory buffers created for members of thin archives.
230 std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers();
231 std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers));
233 return v;
236 static bool isBitcode(MemoryBufferRef mb) {
237 return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode;
240 // Opens a file and create a file object. Path has to be resolved already.
241 void LinkerDriver::addFile(StringRef path, bool withLOption) {
242 using namespace sys::fs;
244 std::optional<MemoryBufferRef> buffer = readFile(path);
245 if (!buffer)
246 return;
247 MemoryBufferRef mbref = *buffer;
249 if (config->formatBinary) {
250 files.push_back(make<BinaryFile>(mbref));
251 return;
254 switch (identify_magic(mbref.getBuffer())) {
255 case file_magic::unknown:
256 readLinkerScript(mbref);
257 return;
258 case file_magic::archive: {
259 auto members = getArchiveMembers(mbref);
260 if (inWholeArchive) {
261 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {
262 if (isBitcode(p.first))
263 files.push_back(make<BitcodeFile>(p.first, path, p.second, false));
264 else
265 files.push_back(createObjFile(p.first, path));
267 return;
270 archiveFiles.emplace_back(path, members.size());
272 // Handle archives and --start-lib/--end-lib using the same code path. This
273 // scans all the ELF relocatable object files and bitcode files in the
274 // archive rather than just the index file, with the benefit that the
275 // symbols are only loaded once. For many projects archives see high
276 // utilization rates and it is a net performance win. --start-lib scans
277 // symbols in the same order that llvm-ar adds them to the index, so in the
278 // common case the semantics are identical. If the archive symbol table was
279 // created in a different order, or is incomplete, this strategy has
280 // different semantics. Such output differences are considered user error.
282 // All files within the archive get the same group ID to allow mutual
283 // references for --warn-backrefs.
284 bool saved = InputFile::isInGroup;
285 InputFile::isInGroup = true;
286 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {
287 auto magic = identify_magic(p.first.getBuffer());
288 if (magic == file_magic::elf_relocatable)
289 files.push_back(createObjFile(p.first, path, true));
290 else if (magic == file_magic::bitcode)
291 files.push_back(make<BitcodeFile>(p.first, path, p.second, true));
292 else
293 warn(path + ": archive member '" + p.first.getBufferIdentifier() +
294 "' is neither ET_REL nor LLVM bitcode");
296 InputFile::isInGroup = saved;
297 if (!saved)
298 ++InputFile::nextGroupId;
299 return;
301 case file_magic::elf_shared_object: {
302 if (config->isStatic || config->relocatable) {
303 error("attempted static link of dynamic object " + path);
304 return;
307 // Shared objects are identified by soname. soname is (if specified)
308 // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
309 // the directory part is ignored. Note that path may be a temporary and
310 // cannot be stored into SharedFile::soName.
311 path = mbref.getBufferIdentifier();
312 auto *f =
313 make<SharedFile>(mbref, withLOption ? path::filename(path) : path);
314 f->init();
315 files.push_back(f);
316 return;
318 case file_magic::bitcode:
319 files.push_back(make<BitcodeFile>(mbref, "", 0, inLib));
320 break;
321 case file_magic::elf_relocatable:
322 files.push_back(createObjFile(mbref, "", inLib));
323 break;
324 default:
325 error(path + ": unknown file type");
329 // Add a given library by searching it from input search paths.
330 void LinkerDriver::addLibrary(StringRef name) {
331 if (std::optional<std::string> path = searchLibrary(name))
332 addFile(saver().save(*path), /*withLOption=*/true);
333 else
334 error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
337 // This function is called on startup. We need this for LTO since
338 // LTO calls LLVM functions to compile bitcode files to native code.
339 // Technically this can be delayed until we read bitcode files, but
340 // we don't bother to do lazily because the initialization is fast.
341 static void initLLVM() {
342 InitializeAllTargets();
343 InitializeAllTargetMCs();
344 InitializeAllAsmPrinters();
345 InitializeAllAsmParsers();
348 // Some command line options or some combinations of them are not allowed.
349 // This function checks for such errors.
350 static void checkOptions() {
351 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
352 // table which is a relatively new feature.
353 if (config->emachine == EM_MIPS && config->gnuHash)
354 error("the .gnu.hash section is not compatible with the MIPS target");
356 if (config->emachine == EM_ARM) {
357 if (!config->cmseImplib) {
358 if (!config->cmseInputLib.empty())
359 error("--in-implib may not be used without --cmse-implib");
360 if (!config->cmseOutputLib.empty())
361 error("--out-implib may not be used without --cmse-implib");
363 } else {
364 if (config->cmseImplib)
365 error("--cmse-implib is only supported on ARM targets");
366 if (!config->cmseInputLib.empty())
367 error("--in-implib is only supported on ARM targets");
368 if (!config->cmseOutputLib.empty())
369 error("--out-implib is only supported on ARM targets");
372 if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
373 error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
375 if (config->fixCortexA8 && config->emachine != EM_ARM)
376 error("--fix-cortex-a8 is only supported on ARM targets");
378 if (config->armBe8 && config->emachine != EM_ARM)
379 error("--be8 is only supported on ARM targets");
381 if (config->fixCortexA8 && !config->isLE)
382 error("--fix-cortex-a8 is not supported on big endian targets");
384 if (config->tocOptimize && config->emachine != EM_PPC64)
385 error("--toc-optimize is only supported on PowerPC64 targets");
387 if (config->pcRelOptimize && config->emachine != EM_PPC64)
388 error("--pcrel-optimize is only supported on PowerPC64 targets");
390 if (config->relaxGP && config->emachine != EM_RISCV)
391 error("--relax-gp is only supported on RISC-V targets");
393 if (config->pie && config->shared)
394 error("-shared and -pie may not be used together");
396 if (!config->shared && !config->filterList.empty())
397 error("-F may not be used without -shared");
399 if (!config->shared && !config->auxiliaryList.empty())
400 error("-f may not be used without -shared");
402 if (config->strip == StripPolicy::All && config->emitRelocs)
403 error("--strip-all and --emit-relocs may not be used together");
405 if (config->zText && config->zIfuncNoplt)
406 error("-z text and -z ifunc-noplt may not be used together");
408 if (config->relocatable) {
409 if (config->shared)
410 error("-r and -shared may not be used together");
411 if (config->gdbIndex)
412 error("-r and --gdb-index may not be used together");
413 if (config->icf != ICFLevel::None)
414 error("-r and --icf may not be used together");
415 if (config->pie)
416 error("-r and -pie may not be used together");
417 if (config->exportDynamic)
418 error("-r and --export-dynamic may not be used together");
421 if (config->executeOnly) {
422 if (config->emachine != EM_AARCH64)
423 error("--execute-only is only supported on AArch64 targets");
425 if (config->singleRoRx && !script->hasSectionsCommand)
426 error("--execute-only and --no-rosegment cannot be used together");
429 if (config->zRetpolineplt && config->zForceIbt)
430 error("-z force-ibt may not be used with -z retpolineplt");
432 if (config->emachine != EM_AARCH64) {
433 if (config->zPacPlt)
434 error("-z pac-plt only supported on AArch64");
435 if (config->zForceBti)
436 error("-z force-bti only supported on AArch64");
437 if (config->zBtiReport != "none")
438 error("-z bti-report only supported on AArch64");
441 if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
442 config->zCetReport != "none")
443 error("-z cet-report only supported on X86 and X86_64");
446 static const char *getReproduceOption(opt::InputArgList &args) {
447 if (auto *arg = args.getLastArg(OPT_reproduce))
448 return arg->getValue();
449 return getenv("LLD_REPRODUCE");
452 static bool hasZOption(opt::InputArgList &args, StringRef key) {
453 for (auto *arg : args.filtered(OPT_z))
454 if (key == arg->getValue())
455 return true;
456 return false;
459 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
460 bool Default) {
461 for (auto *arg : args.filtered_reverse(OPT_z)) {
462 if (k1 == arg->getValue())
463 return true;
464 if (k2 == arg->getValue())
465 return false;
467 return Default;
470 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
471 for (auto *arg : args.filtered_reverse(OPT_z)) {
472 StringRef v = arg->getValue();
473 if (v == "noseparate-code")
474 return SeparateSegmentKind::None;
475 if (v == "separate-code")
476 return SeparateSegmentKind::Code;
477 if (v == "separate-loadable-segments")
478 return SeparateSegmentKind::Loadable;
480 return SeparateSegmentKind::None;
483 static GnuStackKind getZGnuStack(opt::InputArgList &args) {
484 for (auto *arg : args.filtered_reverse(OPT_z)) {
485 if (StringRef("execstack") == arg->getValue())
486 return GnuStackKind::Exec;
487 if (StringRef("noexecstack") == arg->getValue())
488 return GnuStackKind::NoExec;
489 if (StringRef("nognustack") == arg->getValue())
490 return GnuStackKind::None;
493 return GnuStackKind::NoExec;
496 static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
497 for (auto *arg : args.filtered_reverse(OPT_z)) {
498 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
499 if (kv.first == "start-stop-visibility") {
500 if (kv.second == "default")
501 return STV_DEFAULT;
502 else if (kv.second == "internal")
503 return STV_INTERNAL;
504 else if (kv.second == "hidden")
505 return STV_HIDDEN;
506 else if (kv.second == "protected")
507 return STV_PROTECTED;
508 error("unknown -z start-stop-visibility= value: " + StringRef(kv.second));
511 return STV_PROTECTED;
514 constexpr const char *knownZFlags[] = {
515 "combreloc",
516 "copyreloc",
517 "defs",
518 "execstack",
519 "force-bti",
520 "force-ibt",
521 "global",
522 "hazardplt",
523 "ifunc-noplt",
524 "initfirst",
525 "interpose",
526 "keep-text-section-prefix",
527 "lazy",
528 "muldefs",
529 "nocombreloc",
530 "nocopyreloc",
531 "nodefaultlib",
532 "nodelete",
533 "nodlopen",
534 "noexecstack",
535 "nognustack",
536 "nokeep-text-section-prefix",
537 "nopack-relative-relocs",
538 "norelro",
539 "noseparate-code",
540 "nostart-stop-gc",
541 "notext",
542 "now",
543 "origin",
544 "pac-plt",
545 "pack-relative-relocs",
546 "rel",
547 "rela",
548 "relro",
549 "retpolineplt",
550 "rodynamic",
551 "separate-code",
552 "separate-loadable-segments",
553 "shstk",
554 "start-stop-gc",
555 "text",
556 "undefs",
557 "wxneeded",
560 static bool isKnownZFlag(StringRef s) {
561 return llvm::is_contained(knownZFlags, s) ||
562 s.starts_with("common-page-size=") || s.starts_with("bti-report=") ||
563 s.starts_with("cet-report=") ||
564 s.starts_with("dead-reloc-in-nonalloc=") ||
565 s.starts_with("max-page-size=") || s.starts_with("stack-size=") ||
566 s.starts_with("start-stop-visibility=");
569 // Report a warning for an unknown -z option.
570 static void checkZOptions(opt::InputArgList &args) {
571 for (auto *arg : args.filtered(OPT_z))
572 if (!isKnownZFlag(arg->getValue()))
573 warn("unknown -z value: " + StringRef(arg->getValue()));
576 constexpr const char *saveTempsValues[] = {
577 "resolution", "preopt", "promote", "internalize", "import",
578 "opt", "precodegen", "prelink", "combinedindex"};
580 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
581 ELFOptTable parser;
582 opt::InputArgList args = parser.parse(argsArr.slice(1));
584 // Interpret these flags early because error()/warn() depend on them.
585 errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
586 errorHandler().fatalWarnings =
587 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) &&
588 !args.hasArg(OPT_no_warnings);
589 errorHandler().suppressWarnings = args.hasArg(OPT_no_warnings);
590 checkZOptions(args);
592 // Handle -help
593 if (args.hasArg(OPT_help)) {
594 printHelp();
595 return;
598 // Handle -v or -version.
600 // A note about "compatible with GNU linkers" message: this is a hack for
601 // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
602 // a GNU compatible linker. See
603 // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
605 // This is somewhat ugly hack, but in reality, we had no choice other
606 // than doing this. Considering the very long release cycle of Libtool,
607 // it is not easy to improve it to recognize LLD as a GNU compatible
608 // linker in a timely manner. Even if we can make it, there are still a
609 // lot of "configure" scripts out there that are generated by old version
610 // of Libtool. We cannot convince every software developer to migrate to
611 // the latest version and re-generate scripts. So we have this hack.
612 if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
613 message(getLLDVersion() + " (compatible with GNU linkers)");
615 if (const char *path = getReproduceOption(args)) {
616 // Note that --reproduce is a debug option so you can ignore it
617 // if you are trying to understand the whole picture of the code.
618 Expected<std::unique_ptr<TarWriter>> errOrWriter =
619 TarWriter::create(path, path::stem(path));
620 if (errOrWriter) {
621 tar = std::move(*errOrWriter);
622 tar->append("response.txt", createResponseFile(args));
623 tar->append("version.txt", getLLDVersion() + "\n");
624 StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
625 if (!ltoSampleProfile.empty())
626 readFile(ltoSampleProfile);
627 } else {
628 error("--reproduce: " + toString(errOrWriter.takeError()));
632 readConfigs(args);
634 // The behavior of -v or --version is a bit strange, but this is
635 // needed for compatibility with GNU linkers.
636 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
637 return;
638 if (args.hasArg(OPT_version))
639 return;
641 // Initialize time trace profiler.
642 if (config->timeTraceEnabled)
643 timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
646 llvm::TimeTraceScope timeScope("ExecuteLinker");
648 initLLVM();
649 createFiles(args);
650 if (errorCount())
651 return;
653 inferMachineType();
654 setConfigs(args);
655 checkOptions();
656 if (errorCount())
657 return;
659 link(args);
662 if (config->timeTraceEnabled) {
663 checkError(timeTraceProfilerWrite(
664 args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
665 timeTraceProfilerCleanup();
669 static std::string getRpath(opt::InputArgList &args) {
670 SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath);
671 return llvm::join(v.begin(), v.end(), ":");
674 // Determines what we should do if there are remaining unresolved
675 // symbols after the name resolution.
676 static void setUnresolvedSymbolPolicy(opt::InputArgList &args) {
677 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
678 OPT_warn_unresolved_symbols, true)
679 ? UnresolvedPolicy::ReportError
680 : UnresolvedPolicy::Warn;
681 // -shared implies --unresolved-symbols=ignore-all because missing
682 // symbols are likely to be resolved at runtime.
683 bool diagRegular = !config->shared, diagShlib = !config->shared;
685 for (const opt::Arg *arg : args) {
686 switch (arg->getOption().getID()) {
687 case OPT_unresolved_symbols: {
688 StringRef s = arg->getValue();
689 if (s == "ignore-all") {
690 diagRegular = false;
691 diagShlib = false;
692 } else if (s == "ignore-in-object-files") {
693 diagRegular = false;
694 diagShlib = true;
695 } else if (s == "ignore-in-shared-libs") {
696 diagRegular = true;
697 diagShlib = false;
698 } else if (s == "report-all") {
699 diagRegular = true;
700 diagShlib = true;
701 } else {
702 error("unknown --unresolved-symbols value: " + s);
704 break;
706 case OPT_no_undefined:
707 diagRegular = true;
708 break;
709 case OPT_z:
710 if (StringRef(arg->getValue()) == "defs")
711 diagRegular = true;
712 else if (StringRef(arg->getValue()) == "undefs")
713 diagRegular = false;
714 break;
715 case OPT_allow_shlib_undefined:
716 diagShlib = false;
717 break;
718 case OPT_no_allow_shlib_undefined:
719 diagShlib = true;
720 break;
724 config->unresolvedSymbols =
725 diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;
726 config->unresolvedSymbolsInShlib =
727 diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;
730 static Target2Policy getTarget2(opt::InputArgList &args) {
731 StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
732 if (s == "rel")
733 return Target2Policy::Rel;
734 if (s == "abs")
735 return Target2Policy::Abs;
736 if (s == "got-rel")
737 return Target2Policy::GotRel;
738 error("unknown --target2 option: " + s);
739 return Target2Policy::GotRel;
742 static bool isOutputFormatBinary(opt::InputArgList &args) {
743 StringRef s = args.getLastArgValue(OPT_oformat, "elf");
744 if (s == "binary")
745 return true;
746 if (!s.starts_with("elf"))
747 error("unknown --oformat value: " + s);
748 return false;
751 static DiscardPolicy getDiscard(opt::InputArgList &args) {
752 auto *arg =
753 args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
754 if (!arg)
755 return DiscardPolicy::Default;
756 if (arg->getOption().getID() == OPT_discard_all)
757 return DiscardPolicy::All;
758 if (arg->getOption().getID() == OPT_discard_locals)
759 return DiscardPolicy::Locals;
760 return DiscardPolicy::None;
763 static StringRef getDynamicLinker(opt::InputArgList &args) {
764 auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
765 if (!arg)
766 return "";
767 if (arg->getOption().getID() == OPT_no_dynamic_linker) {
768 // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
769 config->noDynamicLinker = true;
770 return "";
772 return arg->getValue();
775 static int getMemtagMode(opt::InputArgList &args) {
776 StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode);
777 if (memtagModeArg.empty()) {
778 if (config->androidMemtagStack)
779 warn("--android-memtag-mode is unspecified, leaving "
780 "--android-memtag-stack a no-op");
781 else if (config->androidMemtagHeap)
782 warn("--android-memtag-mode is unspecified, leaving "
783 "--android-memtag-heap a no-op");
784 return ELF::NT_MEMTAG_LEVEL_NONE;
787 if (!config->androidMemtagHeap && !config->androidMemtagStack) {
788 error("when using --android-memtag-mode, at least one of "
789 "--android-memtag-heap or "
790 "--android-memtag-stack is required");
791 return ELF::NT_MEMTAG_LEVEL_NONE;
794 if (memtagModeArg == "sync")
795 return ELF::NT_MEMTAG_LEVEL_SYNC;
796 if (memtagModeArg == "async")
797 return ELF::NT_MEMTAG_LEVEL_ASYNC;
798 if (memtagModeArg == "none")
799 return ELF::NT_MEMTAG_LEVEL_NONE;
801 error("unknown --android-memtag-mode value: \"" + memtagModeArg +
802 "\", should be one of {async, sync, none}");
803 return ELF::NT_MEMTAG_LEVEL_NONE;
806 static ICFLevel getICF(opt::InputArgList &args) {
807 auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
808 if (!arg || arg->getOption().getID() == OPT_icf_none)
809 return ICFLevel::None;
810 if (arg->getOption().getID() == OPT_icf_safe)
811 return ICFLevel::Safe;
812 return ICFLevel::All;
815 static StripPolicy getStrip(opt::InputArgList &args) {
816 if (args.hasArg(OPT_relocatable))
817 return StripPolicy::None;
819 auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
820 if (!arg)
821 return StripPolicy::None;
822 if (arg->getOption().getID() == OPT_strip_all)
823 return StripPolicy::All;
824 return StripPolicy::Debug;
827 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
828 const opt::Arg &arg) {
829 uint64_t va = 0;
830 if (s.starts_with("0x"))
831 s = s.drop_front(2);
832 if (!to_integer(s, va, 16))
833 error("invalid argument: " + arg.getAsString(args));
834 return va;
837 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
838 StringMap<uint64_t> ret;
839 for (auto *arg : args.filtered(OPT_section_start)) {
840 StringRef name;
841 StringRef addr;
842 std::tie(name, addr) = StringRef(arg->getValue()).split('=');
843 ret[name] = parseSectionAddress(addr, args, *arg);
846 if (auto *arg = args.getLastArg(OPT_Ttext))
847 ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
848 if (auto *arg = args.getLastArg(OPT_Tdata))
849 ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
850 if (auto *arg = args.getLastArg(OPT_Tbss))
851 ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
852 return ret;
855 static SortSectionPolicy getSortSection(opt::InputArgList &args) {
856 StringRef s = args.getLastArgValue(OPT_sort_section);
857 if (s == "alignment")
858 return SortSectionPolicy::Alignment;
859 if (s == "name")
860 return SortSectionPolicy::Name;
861 if (!s.empty())
862 error("unknown --sort-section rule: " + s);
863 return SortSectionPolicy::Default;
866 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
867 StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
868 if (s == "warn")
869 return OrphanHandlingPolicy::Warn;
870 if (s == "error")
871 return OrphanHandlingPolicy::Error;
872 if (s != "place")
873 error("unknown --orphan-handling mode: " + s);
874 return OrphanHandlingPolicy::Place;
877 // Parse --build-id or --build-id=<style>. We handle "tree" as a
878 // synonym for "sha1" because all our hash functions including
879 // --build-id=sha1 are actually tree hashes for performance reasons.
880 static std::pair<BuildIdKind, SmallVector<uint8_t, 0>>
881 getBuildId(opt::InputArgList &args) {
882 auto *arg = args.getLastArg(OPT_build_id);
883 if (!arg)
884 return {BuildIdKind::None, {}};
886 StringRef s = arg->getValue();
887 if (s == "fast")
888 return {BuildIdKind::Fast, {}};
889 if (s == "md5")
890 return {BuildIdKind::Md5, {}};
891 if (s == "sha1" || s == "tree")
892 return {BuildIdKind::Sha1, {}};
893 if (s == "uuid")
894 return {BuildIdKind::Uuid, {}};
895 if (s.starts_with("0x"))
896 return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
898 if (s != "none")
899 error("unknown --build-id style: " + s);
900 return {BuildIdKind::None, {}};
903 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
904 StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
905 if (s == "android")
906 return {true, false};
907 if (s == "relr")
908 return {false, true};
909 if (s == "android+relr")
910 return {true, true};
912 if (s != "none")
913 error("unknown --pack-dyn-relocs format: " + s);
914 return {false, false};
917 static void readCallGraph(MemoryBufferRef mb) {
918 // Build a map from symbol name to section
919 DenseMap<StringRef, Symbol *> map;
920 for (ELFFileBase *file : ctx.objectFiles)
921 for (Symbol *sym : file->getSymbols())
922 map[sym->getName()] = sym;
924 auto findSection = [&](StringRef name) -> InputSectionBase * {
925 Symbol *sym = map.lookup(name);
926 if (!sym) {
927 if (config->warnSymbolOrdering)
928 warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
929 return nullptr;
931 maybeWarnUnorderableSymbol(sym);
933 if (Defined *dr = dyn_cast_or_null<Defined>(sym))
934 return dyn_cast_or_null<InputSectionBase>(dr->section);
935 return nullptr;
938 for (StringRef line : args::getLines(mb)) {
939 SmallVector<StringRef, 3> fields;
940 line.split(fields, ' ');
941 uint64_t count;
943 if (fields.size() != 3 || !to_integer(fields[2], count)) {
944 error(mb.getBufferIdentifier() + ": parse error");
945 return;
948 if (InputSectionBase *from = findSection(fields[0]))
949 if (InputSectionBase *to = findSection(fields[1]))
950 config->callGraphProfile[std::make_pair(from, to)] += count;
954 // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
955 // true and populates cgProfile and symbolIndices.
956 template <class ELFT>
957 static bool
958 processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices,
959 ArrayRef<typename ELFT::CGProfile> &cgProfile,
960 ObjFile<ELFT> *inputObj) {
961 if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
962 return false;
964 ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
965 inputObj->template getELFShdrs<ELFT>();
966 symbolIndices.clear();
967 const ELFFile<ELFT> &obj = inputObj->getObj();
968 cgProfile =
969 check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(
970 objSections[inputObj->cgProfileSectionIndex]));
972 for (size_t i = 0, e = objSections.size(); i < e; ++i) {
973 const Elf_Shdr_Impl<ELFT> &sec = objSections[i];
974 if (sec.sh_info == inputObj->cgProfileSectionIndex) {
975 if (sec.sh_type == SHT_RELA) {
976 ArrayRef<typename ELFT::Rela> relas =
977 CHECK(obj.relas(sec), "could not retrieve cg profile rela section");
978 for (const typename ELFT::Rela &rel : relas)
979 symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
980 break;
982 if (sec.sh_type == SHT_REL) {
983 ArrayRef<typename ELFT::Rel> rels =
984 CHECK(obj.rels(sec), "could not retrieve cg profile rel section");
985 for (const typename ELFT::Rel &rel : rels)
986 symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
987 break;
991 if (symbolIndices.empty())
992 warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");
993 return !symbolIndices.empty();
996 template <class ELFT> static void readCallGraphsFromObjectFiles() {
997 SmallVector<uint32_t, 32> symbolIndices;
998 ArrayRef<typename ELFT::CGProfile> cgProfile;
999 for (auto file : ctx.objectFiles) {
1000 auto *obj = cast<ObjFile<ELFT>>(file);
1001 if (!processCallGraphRelocations(symbolIndices, cgProfile, obj))
1002 continue;
1004 if (symbolIndices.size() != cgProfile.size() * 2)
1005 fatal("number of relocations doesn't match Weights");
1007 for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {
1008 const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];
1009 uint32_t fromIndex = symbolIndices[i * 2];
1010 uint32_t toIndex = symbolIndices[i * 2 + 1];
1011 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
1012 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
1013 if (!fromSym || !toSym)
1014 continue;
1016 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
1017 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
1018 if (from && to)
1019 config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
1024 static DebugCompressionType getCompressionType(StringRef s, StringRef option) {
1025 DebugCompressionType type = StringSwitch<DebugCompressionType>(s)
1026 .Case("zlib", DebugCompressionType::Zlib)
1027 .Case("zstd", DebugCompressionType::Zstd)
1028 .Default(DebugCompressionType::None);
1029 if (type == DebugCompressionType::None) {
1030 if (s != "none")
1031 error("unknown " + option + " value: " + s);
1032 } else if (const char *reason = compression::getReasonIfUnsupported(
1033 compression::formatFor(type))) {
1034 error(option + ": " + reason);
1036 return type;
1039 static StringRef getAliasSpelling(opt::Arg *arg) {
1040 if (const opt::Arg *alias = arg->getAlias())
1041 return alias->getSpelling();
1042 return arg->getSpelling();
1045 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
1046 unsigned id) {
1047 auto *arg = args.getLastArg(id);
1048 if (!arg)
1049 return {"", ""};
1051 StringRef s = arg->getValue();
1052 std::pair<StringRef, StringRef> ret = s.split(';');
1053 if (ret.second.empty())
1054 error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
1055 return ret;
1058 // Parse options of the form "old;new[;extra]".
1059 static std::tuple<StringRef, StringRef, StringRef>
1060 getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {
1061 auto [oldDir, second] = getOldNewOptions(args, id);
1062 auto [newDir, extraDir] = second.split(';');
1063 return {oldDir, newDir, extraDir};
1066 // Parse the symbol ordering file and warn for any duplicate entries.
1067 static SmallVector<StringRef, 0> getSymbolOrderingFile(MemoryBufferRef mb) {
1068 SetVector<StringRef, SmallVector<StringRef, 0>> names;
1069 for (StringRef s : args::getLines(mb))
1070 if (!names.insert(s) && config->warnSymbolOrdering)
1071 warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
1073 return names.takeVector();
1076 static bool getIsRela(opt::InputArgList &args) {
1077 // If -z rel or -z rela is specified, use the last option.
1078 for (auto *arg : args.filtered_reverse(OPT_z)) {
1079 StringRef s(arg->getValue());
1080 if (s == "rel")
1081 return false;
1082 if (s == "rela")
1083 return true;
1086 // Otherwise use the psABI defined relocation entry format.
1087 uint16_t m = config->emachine;
1088 return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC ||
1089 m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64;
1092 static void parseClangOption(StringRef opt, const Twine &msg) {
1093 std::string err;
1094 raw_string_ostream os(err);
1096 const char *argv[] = {config->progName.data(), opt.data()};
1097 if (cl::ParseCommandLineOptions(2, argv, "", &os))
1098 return;
1099 os.flush();
1100 error(msg + ": " + StringRef(err).trim());
1103 // Checks the parameter of the bti-report and cet-report options.
1104 static bool isValidReportString(StringRef arg) {
1105 return arg == "none" || arg == "warning" || arg == "error";
1108 // Process a remap pattern 'from-glob=to-file'.
1109 static bool remapInputs(StringRef line, const Twine &location) {
1110 SmallVector<StringRef, 0> fields;
1111 line.split(fields, '=');
1112 if (fields.size() != 2 || fields[1].empty()) {
1113 error(location + ": parse error, not 'from-glob=to-file'");
1114 return true;
1116 if (!hasWildcard(fields[0]))
1117 config->remapInputs[fields[0]] = fields[1];
1118 else if (Expected<GlobPattern> pat = GlobPattern::create(fields[0]))
1119 config->remapInputsWildcards.emplace_back(std::move(*pat), fields[1]);
1120 else {
1121 error(location + ": " + toString(pat.takeError()));
1122 return true;
1124 return false;
1127 // Initializes Config members by the command line options.
1128 static void readConfigs(opt::InputArgList &args) {
1129 errorHandler().verbose = args.hasArg(OPT_verbose);
1130 errorHandler().vsDiagnostics =
1131 args.hasArg(OPT_visual_studio_diagnostics_format, false);
1133 config->allowMultipleDefinition =
1134 args.hasFlag(OPT_allow_multiple_definition,
1135 OPT_no_allow_multiple_definition, false) ||
1136 hasZOption(args, "muldefs");
1137 config->androidMemtagHeap =
1138 args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false);
1139 config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack,
1140 OPT_no_android_memtag_stack, false);
1141 config->androidMemtagMode = getMemtagMode(args);
1142 config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
1143 config->armBe8 = args.hasArg(OPT_be8);
1144 if (opt::Arg *arg =
1145 args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,
1146 OPT_Bsymbolic_functions, OPT_Bsymbolic)) {
1147 if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
1148 config->bsymbolic = BsymbolicKind::NonWeakFunctions;
1149 else if (arg->getOption().matches(OPT_Bsymbolic_functions))
1150 config->bsymbolic = BsymbolicKind::Functions;
1151 else if (arg->getOption().matches(OPT_Bsymbolic))
1152 config->bsymbolic = BsymbolicKind::All;
1154 config->checkSections =
1155 args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
1156 config->chroot = args.getLastArgValue(OPT_chroot);
1157 config->compressDebugSections = getCompressionType(
1158 args.getLastArgValue(OPT_compress_debug_sections, "none"),
1159 "--compress-debug-sections");
1160 config->cref = args.hasArg(OPT_cref);
1161 config->optimizeBBJumps =
1162 args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
1163 config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
1164 config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
1165 config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
1166 config->disableVerify = args.hasArg(OPT_disable_verify);
1167 config->discard = getDiscard(args);
1168 config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
1169 config->dynamicLinker = getDynamicLinker(args);
1170 config->ehFrameHdr =
1171 args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
1172 config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
1173 config->emitRelocs = args.hasArg(OPT_emit_relocs);
1174 config->callGraphProfileSort = args.hasFlag(
1175 OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
1176 config->enableNewDtags =
1177 args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
1178 config->entry = args.getLastArgValue(OPT_entry);
1180 errorHandler().errorHandlingScript =
1181 args.getLastArgValue(OPT_error_handling_script);
1183 config->executeOnly =
1184 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
1185 config->exportDynamic =
1186 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) ||
1187 args.hasArg(OPT_shared);
1188 config->filterList = args::getStrings(args, OPT_filter);
1189 config->fini = args.getLastArgValue(OPT_fini, "_fini");
1190 config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
1191 !args.hasArg(OPT_relocatable);
1192 config->cmseImplib = args.hasArg(OPT_cmse_implib);
1193 config->cmseInputLib = args.getLastArgValue(OPT_in_implib);
1194 config->cmseOutputLib = args.getLastArgValue(OPT_out_implib);
1195 config->fixCortexA8 =
1196 args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
1197 config->fortranCommon =
1198 args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false);
1199 config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
1200 config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
1201 config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
1202 config->icf = getICF(args);
1203 config->ignoreDataAddressEquality =
1204 args.hasArg(OPT_ignore_data_address_equality);
1205 config->ignoreFunctionAddressEquality =
1206 args.hasArg(OPT_ignore_function_address_equality);
1207 config->init = args.getLastArgValue(OPT_init, "_init");
1208 config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
1209 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1210 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1211 config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1212 OPT_no_lto_pgo_warn_mismatch, true);
1213 config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
1214 config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
1215 config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
1216 config->ltoWholeProgramVisibility =
1217 args.hasFlag(OPT_lto_whole_program_visibility,
1218 OPT_no_lto_whole_program_visibility, false);
1219 config->ltoo = args::getInteger(args, OPT_lto_O, 2);
1220 if (config->ltoo > 3)
1221 error("invalid optimization level for LTO: " + Twine(config->ltoo));
1222 unsigned ltoCgo =
1223 args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo));
1224 if (auto level = CodeGenOpt::getLevel(ltoCgo))
1225 config->ltoCgo = *level;
1226 else
1227 error("invalid codegen optimization level for LTO: " + Twine(ltoCgo));
1228 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
1229 config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
1230 config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
1231 config->ltoBasicBlockSections =
1232 args.getLastArgValue(OPT_lto_basic_block_sections);
1233 config->ltoUniqueBasicBlockSectionNames =
1234 args.hasFlag(OPT_lto_unique_basic_block_section_names,
1235 OPT_no_lto_unique_basic_block_section_names, false);
1236 config->mapFile = args.getLastArgValue(OPT_Map);
1237 config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
1238 config->mergeArmExidx =
1239 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
1240 config->mmapOutputFile =
1241 args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
1242 config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
1243 config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
1244 config->nostdlib = args.hasArg(OPT_nostdlib);
1245 config->oFormatBinary = isOutputFormatBinary(args);
1246 config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
1247 config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
1248 config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file);
1250 // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1251 if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {
1252 auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());
1253 if (!resultOrErr)
1254 error(arg->getSpelling() + ": invalid argument '" + arg->getValue() +
1255 "', only integer or 'auto' is supported");
1256 else
1257 config->optRemarksHotnessThreshold = *resultOrErr;
1260 config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
1261 config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
1262 config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
1263 config->optimize = args::getInteger(args, OPT_O, 1);
1264 config->orphanHandling = getOrphanHandling(args);
1265 config->outputFile = args.getLastArgValue(OPT_o);
1266 config->packageMetadata = args.getLastArgValue(OPT_package_metadata);
1267 config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
1268 config->printIcfSections =
1269 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
1270 config->printGcSections =
1271 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
1272 config->printMemoryUsage = args.hasArg(OPT_print_memory_usage);
1273 config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
1274 config->printSymbolOrder =
1275 args.getLastArgValue(OPT_print_symbol_order);
1276 config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true);
1277 config->relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false);
1278 config->rpath = getRpath(args);
1279 config->relocatable = args.hasArg(OPT_relocatable);
1281 if (args.hasArg(OPT_save_temps)) {
1282 // --save-temps implies saving all temps.
1283 for (const char *s : saveTempsValues)
1284 config->saveTempsArgs.insert(s);
1285 } else {
1286 for (auto *arg : args.filtered(OPT_save_temps_eq)) {
1287 StringRef s = arg->getValue();
1288 if (llvm::is_contained(saveTempsValues, s))
1289 config->saveTempsArgs.insert(s);
1290 else
1291 error("unknown --save-temps value: " + s);
1295 config->searchPaths = args::getStrings(args, OPT_library_path);
1296 config->sectionStartMap = getSectionStartMap(args);
1297 config->shared = args.hasArg(OPT_shared);
1298 config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
1299 config->soName = args.getLastArgValue(OPT_soname);
1300 config->sortSection = getSortSection(args);
1301 config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
1302 config->strip = getStrip(args);
1303 config->sysroot = args.getLastArgValue(OPT_sysroot);
1304 config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
1305 config->target2 = getTarget2(args);
1306 config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
1307 config->thinLTOCachePolicy = CHECK(
1308 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
1309 "--thinlto-cache-policy: invalid cache policy");
1310 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1311 config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||
1312 args.hasArg(OPT_thinlto_index_only) ||
1313 args.hasArg(OPT_thinlto_index_only_eq);
1314 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1315 args.hasArg(OPT_thinlto_index_only_eq);
1316 config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1317 config->thinLTOObjectSuffixReplace =
1318 getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
1319 std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,
1320 config->thinLTOPrefixReplaceNativeObject) =
1321 getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace_eq);
1322 if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {
1323 if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))
1324 error("--thinlto-object-suffix-replace is not supported with "
1325 "--thinlto-emit-index-files");
1326 else if (args.hasArg(OPT_thinlto_prefix_replace_eq))
1327 error("--thinlto-prefix-replace is not supported with "
1328 "--thinlto-emit-index-files");
1330 if (!config->thinLTOPrefixReplaceNativeObject.empty() &&
1331 config->thinLTOIndexOnlyArg.empty()) {
1332 error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "
1333 "--thinlto-index-only=");
1335 config->thinLTOModulesToCompile =
1336 args::getStrings(args, OPT_thinlto_single_module_eq);
1337 config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
1338 config->timeTraceGranularity =
1339 args::getInteger(args, OPT_time_trace_granularity, 500);
1340 config->trace = args.hasArg(OPT_trace);
1341 config->undefined = args::getStrings(args, OPT_undefined);
1342 config->undefinedVersion =
1343 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false);
1344 config->unique = args.hasArg(OPT_unique);
1345 config->useAndroidRelrTags = args.hasFlag(
1346 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
1347 config->warnBackrefs =
1348 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
1349 config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
1350 config->warnSymbolOrdering =
1351 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1352 config->whyExtract = args.getLastArgValue(OPT_why_extract);
1353 config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
1354 config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
1355 config->zForceBti = hasZOption(args, "force-bti");
1356 config->zForceIbt = hasZOption(args, "force-ibt");
1357 config->zGlobal = hasZOption(args, "global");
1358 config->zGnustack = getZGnuStack(args);
1359 config->zHazardplt = hasZOption(args, "hazardplt");
1360 config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
1361 config->zInitfirst = hasZOption(args, "initfirst");
1362 config->zInterpose = hasZOption(args, "interpose");
1363 config->zKeepTextSectionPrefix = getZFlag(
1364 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
1365 config->zNodefaultlib = hasZOption(args, "nodefaultlib");
1366 config->zNodelete = hasZOption(args, "nodelete");
1367 config->zNodlopen = hasZOption(args, "nodlopen");
1368 config->zNow = getZFlag(args, "now", "lazy", false);
1369 config->zOrigin = hasZOption(args, "origin");
1370 config->zPacPlt = hasZOption(args, "pac-plt");
1371 config->zRelro = getZFlag(args, "relro", "norelro", true);
1372 config->zRetpolineplt = hasZOption(args, "retpolineplt");
1373 config->zRodynamic = hasZOption(args, "rodynamic");
1374 config->zSeparate = getZSeparate(args);
1375 config->zShstk = hasZOption(args, "shstk");
1376 config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1377 config->zStartStopGC =
1378 getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);
1379 config->zStartStopVisibility = getZStartStopVisibility(args);
1380 config->zText = getZFlag(args, "text", "notext", true);
1381 config->zWxneeded = hasZOption(args, "wxneeded");
1382 setUnresolvedSymbolPolicy(args);
1383 config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";
1385 if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {
1386 if (arg->getOption().matches(OPT_eb))
1387 config->optEB = true;
1388 else
1389 config->optEL = true;
1392 for (opt::Arg *arg : args.filtered(OPT_remap_inputs)) {
1393 StringRef value(arg->getValue());
1394 remapInputs(value, arg->getSpelling());
1396 for (opt::Arg *arg : args.filtered(OPT_remap_inputs_file)) {
1397 StringRef filename(arg->getValue());
1398 std::optional<MemoryBufferRef> buffer = readFile(filename);
1399 if (!buffer)
1400 continue;
1401 // Parse 'from-glob=to-file' lines, ignoring #-led comments.
1402 for (auto [lineno, line] : llvm::enumerate(args::getLines(*buffer)))
1403 if (remapInputs(line, filename + ":" + Twine(lineno + 1)))
1404 break;
1407 for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {
1408 constexpr StringRef errPrefix = "--shuffle-sections=: ";
1409 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
1410 if (kv.first.empty() || kv.second.empty()) {
1411 error(errPrefix + "expected <section_glob>=<seed>, but got '" +
1412 arg->getValue() + "'");
1413 continue;
1415 // Signed so that <section_glob>=-1 is allowed.
1416 int64_t v;
1417 if (!to_integer(kv.second, v))
1418 error(errPrefix + "expected an integer, but got '" + kv.second + "'");
1419 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1420 config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v));
1421 else
1422 error(errPrefix + toString(pat.takeError()));
1425 auto reports = {std::make_pair("bti-report", &config->zBtiReport),
1426 std::make_pair("cet-report", &config->zCetReport)};
1427 for (opt::Arg *arg : args.filtered(OPT_z)) {
1428 std::pair<StringRef, StringRef> option =
1429 StringRef(arg->getValue()).split('=');
1430 for (auto reportArg : reports) {
1431 if (option.first != reportArg.first)
1432 continue;
1433 if (!isValidReportString(option.second)) {
1434 error(Twine("-z ") + reportArg.first + "= parameter " + option.second +
1435 " is not recognized");
1436 continue;
1438 *reportArg.second = option.second;
1442 for (opt::Arg *arg : args.filtered(OPT_z)) {
1443 std::pair<StringRef, StringRef> option =
1444 StringRef(arg->getValue()).split('=');
1445 if (option.first != "dead-reloc-in-nonalloc")
1446 continue;
1447 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
1448 std::pair<StringRef, StringRef> kv = option.second.split('=');
1449 if (kv.first.empty() || kv.second.empty()) {
1450 error(errPrefix + "expected <section_glob>=<value>");
1451 continue;
1453 uint64_t v;
1454 if (!to_integer(kv.second, v))
1455 error(errPrefix + "expected a non-negative integer, but got '" +
1456 kv.second + "'");
1457 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1458 config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
1459 else
1460 error(errPrefix + toString(pat.takeError()));
1463 cl::ResetAllOptionOccurrences();
1465 // Parse LTO options.
1466 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
1467 parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
1468 arg->getSpelling());
1470 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
1471 parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
1473 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1474 // relative path. Just ignore. If not ended with "lto-wrapper" (or
1475 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
1476 // unsupported LLVMgold.so option and error.
1477 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) {
1478 StringRef v(arg->getValue());
1479 if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe"))
1480 error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
1481 "'");
1484 config->passPlugins = args::getStrings(args, OPT_load_pass_plugins);
1486 // Parse -mllvm options.
1487 for (const auto *arg : args.filtered(OPT_mllvm)) {
1488 parseClangOption(arg->getValue(), arg->getSpelling());
1489 config->mllvmOpts.emplace_back(arg->getValue());
1492 // --threads= takes a positive integer and provides the default value for
1493 // --thinlto-jobs=. If unspecified, cap the number of threads since
1494 // overhead outweighs optimization for used parallel algorithms for the
1495 // non-LTO parts.
1496 if (auto *arg = args.getLastArg(OPT_threads)) {
1497 StringRef v(arg->getValue());
1498 unsigned threads = 0;
1499 if (!llvm::to_integer(v, threads, 0) || threads == 0)
1500 error(arg->getSpelling() + ": expected a positive integer, but got '" +
1501 arg->getValue() + "'");
1502 parallel::strategy = hardware_concurrency(threads);
1503 config->thinLTOJobs = v;
1504 } else if (parallel::strategy.compute_thread_count() > 16) {
1505 log("set maximum concurrency to 16, specify --threads= to change");
1506 parallel::strategy = hardware_concurrency(16);
1508 if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
1509 config->thinLTOJobs = arg->getValue();
1510 config->threadCount = parallel::strategy.compute_thread_count();
1512 if (config->ltoPartitions == 0)
1513 error("--lto-partitions: number of threads must be > 0");
1514 if (!get_threadpool_strategy(config->thinLTOJobs))
1515 error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1517 if (config->splitStackAdjustSize < 0)
1518 error("--split-stack-adjust-size: size must be >= 0");
1520 // The text segment is traditionally the first segment, whose address equals
1521 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1522 // is an old-fashioned option that does not play well with lld's layout.
1523 // Suggest --image-base as a likely alternative.
1524 if (args.hasArg(OPT_Ttext_segment))
1525 error("-Ttext-segment is not supported. Use --image-base if you "
1526 "intend to set the base address");
1528 // Parse ELF{32,64}{LE,BE} and CPU type.
1529 if (auto *arg = args.getLastArg(OPT_m)) {
1530 StringRef s = arg->getValue();
1531 std::tie(config->ekind, config->emachine, config->osabi) =
1532 parseEmulation(s);
1533 config->mipsN32Abi =
1534 (s.starts_with("elf32btsmipn32") || s.starts_with("elf32ltsmipn32"));
1535 config->emulation = s;
1538 // Parse --hash-style={sysv,gnu,both}.
1539 if (auto *arg = args.getLastArg(OPT_hash_style)) {
1540 StringRef s = arg->getValue();
1541 if (s == "sysv")
1542 config->sysvHash = true;
1543 else if (s == "gnu")
1544 config->gnuHash = true;
1545 else if (s == "both")
1546 config->sysvHash = config->gnuHash = true;
1547 else
1548 error("unknown --hash-style: " + s);
1551 if (args.hasArg(OPT_print_map))
1552 config->mapFile = "-";
1554 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1555 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1556 // it.
1557 if (config->nmagic || config->omagic)
1558 config->zRelro = false;
1560 std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1562 if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) {
1563 config->relrGlibc = true;
1564 config->relrPackDynRelocs = true;
1565 } else {
1566 std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1567 getPackDynRelocs(args);
1570 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1571 if (args.hasArg(OPT_call_graph_ordering_file))
1572 error("--symbol-ordering-file and --call-graph-order-file "
1573 "may not be used together");
1574 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) {
1575 config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1576 // Also need to disable CallGraphProfileSort to prevent
1577 // LLD order symbols with CGProfile
1578 config->callGraphProfileSort = false;
1582 assert(config->versionDefinitions.empty());
1583 config->versionDefinitions.push_back(
1584 {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});
1585 config->versionDefinitions.push_back(
1586 {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});
1588 // If --retain-symbol-file is used, we'll keep only the symbols listed in
1589 // the file and discard all others.
1590 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1591 config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
1592 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1593 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1594 for (StringRef s : args::getLines(*buffer))
1595 config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
1596 {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1599 for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
1600 StringRef pattern(arg->getValue());
1601 if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
1602 config->warnBackrefsExclude.push_back(std::move(*pat));
1603 else
1604 error(arg->getSpelling() + ": " + toString(pat.takeError()));
1607 // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1608 // which should be exported. For -shared, references to matched non-local
1609 // STV_DEFAULT symbols are not bound to definitions within the shared object,
1610 // even if other options express a symbolic intention: -Bsymbolic,
1611 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1612 for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1613 config->dynamicList.push_back(
1614 {arg->getValue(), /*isExternCpp=*/false,
1615 /*hasWildcard=*/hasWildcard(arg->getValue())});
1617 // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1618 // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1619 // like semantics.
1620 config->symbolic =
1621 config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1622 for (auto *arg :
1623 args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))
1624 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1625 readDynamicList(*buffer);
1627 for (auto *arg : args.filtered(OPT_version_script))
1628 if (std::optional<std::string> path = searchScript(arg->getValue())) {
1629 if (std::optional<MemoryBufferRef> buffer = readFile(*path))
1630 readVersionScript(*buffer);
1631 } else {
1632 error(Twine("cannot find version script ") + arg->getValue());
1636 // Some Config members do not directly correspond to any particular
1637 // command line options, but computed based on other Config values.
1638 // This function initialize such members. See Config.h for the details
1639 // of these values.
1640 static void setConfigs(opt::InputArgList &args) {
1641 ELFKind k = config->ekind;
1642 uint16_t m = config->emachine;
1644 config->copyRelocs = (config->relocatable || config->emitRelocs);
1645 config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1646 config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1647 config->endianness = config->isLE ? endianness::little : endianness::big;
1648 config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1649 config->isPic = config->pie || config->shared;
1650 config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1651 config->wordsize = config->is64 ? 8 : 4;
1653 // ELF defines two different ways to store relocation addends as shown below:
1655 // Rel: Addends are stored to the location where relocations are applied. It
1656 // cannot pack the full range of addend values for all relocation types, but
1657 // this only affects relocation types that we don't support emitting as
1658 // dynamic relocations (see getDynRel).
1659 // Rela: Addends are stored as part of relocation entry.
1661 // In other words, Rela makes it easy to read addends at the price of extra
1662 // 4 or 8 byte for each relocation entry.
1664 // We pick the format for dynamic relocations according to the psABI for each
1665 // processor, but a contrary choice can be made if the dynamic loader
1666 // supports.
1667 config->isRela = getIsRela(args);
1669 // If the output uses REL relocations we must store the dynamic relocation
1670 // addends to the output sections. We also store addends for RELA relocations
1671 // if --apply-dynamic-relocs is used.
1672 // We default to not writing the addends when using RELA relocations since
1673 // any standard conforming tool can find it in r_addend.
1674 config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1675 OPT_no_apply_dynamic_relocs, false) ||
1676 !config->isRela;
1677 // Validation of dynamic relocation addends is on by default for assertions
1678 // builds (for supported targets) and disabled otherwise. Ideally we would
1679 // enable the debug checks for all targets, but currently not all targets
1680 // have support for reading Elf_Rel addends, so we only enable for a subset.
1681 #ifndef NDEBUG
1682 bool checkDynamicRelocsDefault = m == EM_AARCH64 || m == EM_ARM ||
1683 m == EM_386 || m == EM_MIPS ||
1684 m == EM_X86_64 || m == EM_RISCV;
1685 #else
1686 bool checkDynamicRelocsDefault = false;
1687 #endif
1688 config->checkDynamicRelocs =
1689 args.hasFlag(OPT_check_dynamic_relocations,
1690 OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);
1691 config->tocOptimize =
1692 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1693 config->pcRelOptimize =
1694 args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
1697 static bool isFormatBinary(StringRef s) {
1698 if (s == "binary")
1699 return true;
1700 if (s == "elf" || s == "default")
1701 return false;
1702 error("unknown --format value: " + s +
1703 " (supported formats: elf, default, binary)");
1704 return false;
1707 void LinkerDriver::createFiles(opt::InputArgList &args) {
1708 llvm::TimeTraceScope timeScope("Load input files");
1709 // For --{push,pop}-state.
1710 std::vector<std::tuple<bool, bool, bool>> stack;
1712 // Iterate over argv to process input files and positional arguments.
1713 InputFile::isInGroup = false;
1714 bool hasInput = false;
1715 for (auto *arg : args) {
1716 switch (arg->getOption().getID()) {
1717 case OPT_library:
1718 addLibrary(arg->getValue());
1719 hasInput = true;
1720 break;
1721 case OPT_INPUT:
1722 addFile(arg->getValue(), /*withLOption=*/false);
1723 hasInput = true;
1724 break;
1725 case OPT_defsym: {
1726 StringRef from;
1727 StringRef to;
1728 std::tie(from, to) = StringRef(arg->getValue()).split('=');
1729 if (from.empty() || to.empty())
1730 error("--defsym: syntax error: " + StringRef(arg->getValue()));
1731 else
1732 readDefsym(from, MemoryBufferRef(to, "--defsym"));
1733 break;
1735 case OPT_script:
1736 if (std::optional<std::string> path = searchScript(arg->getValue())) {
1737 if (std::optional<MemoryBufferRef> mb = readFile(*path))
1738 readLinkerScript(*mb);
1739 break;
1741 error(Twine("cannot find linker script ") + arg->getValue());
1742 break;
1743 case OPT_as_needed:
1744 config->asNeeded = true;
1745 break;
1746 case OPT_format:
1747 config->formatBinary = isFormatBinary(arg->getValue());
1748 break;
1749 case OPT_no_as_needed:
1750 config->asNeeded = false;
1751 break;
1752 case OPT_Bstatic:
1753 case OPT_omagic:
1754 case OPT_nmagic:
1755 config->isStatic = true;
1756 break;
1757 case OPT_Bdynamic:
1758 config->isStatic = false;
1759 break;
1760 case OPT_whole_archive:
1761 inWholeArchive = true;
1762 break;
1763 case OPT_no_whole_archive:
1764 inWholeArchive = false;
1765 break;
1766 case OPT_just_symbols:
1767 if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1768 files.push_back(createObjFile(*mb));
1769 files.back()->justSymbols = true;
1771 break;
1772 case OPT_in_implib:
1773 if (armCmseImpLib)
1774 error("multiple CMSE import libraries not supported");
1775 else if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue()))
1776 armCmseImpLib = createObjFile(*mb);
1777 break;
1778 case OPT_start_group:
1779 if (InputFile::isInGroup)
1780 error("nested --start-group");
1781 InputFile::isInGroup = true;
1782 break;
1783 case OPT_end_group:
1784 if (!InputFile::isInGroup)
1785 error("stray --end-group");
1786 InputFile::isInGroup = false;
1787 ++InputFile::nextGroupId;
1788 break;
1789 case OPT_start_lib:
1790 if (inLib)
1791 error("nested --start-lib");
1792 if (InputFile::isInGroup)
1793 error("may not nest --start-lib in --start-group");
1794 inLib = true;
1795 InputFile::isInGroup = true;
1796 break;
1797 case OPT_end_lib:
1798 if (!inLib)
1799 error("stray --end-lib");
1800 inLib = false;
1801 InputFile::isInGroup = false;
1802 ++InputFile::nextGroupId;
1803 break;
1804 case OPT_push_state:
1805 stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1806 break;
1807 case OPT_pop_state:
1808 if (stack.empty()) {
1809 error("unbalanced --push-state/--pop-state");
1810 break;
1812 std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1813 stack.pop_back();
1814 break;
1818 if (files.empty() && !hasInput && errorCount() == 0)
1819 error("no input files");
1822 // If -m <machine_type> was not given, infer it from object files.
1823 void LinkerDriver::inferMachineType() {
1824 if (config->ekind != ELFNoneKind)
1825 return;
1827 for (InputFile *f : files) {
1828 if (f->ekind == ELFNoneKind)
1829 continue;
1830 config->ekind = f->ekind;
1831 config->emachine = f->emachine;
1832 config->osabi = f->osabi;
1833 config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1834 return;
1836 error("target emulation unknown: -m or at least one .o file required");
1839 // Parse -z max-page-size=<value>. The default value is defined by
1840 // each target.
1841 static uint64_t getMaxPageSize(opt::InputArgList &args) {
1842 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1843 target->defaultMaxPageSize);
1844 if (!isPowerOf2_64(val)) {
1845 error("max-page-size: value isn't a power of 2");
1846 return target->defaultMaxPageSize;
1848 if (config->nmagic || config->omagic) {
1849 if (val != target->defaultMaxPageSize)
1850 warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1851 return 1;
1853 return val;
1856 // Parse -z common-page-size=<value>. The default value is defined by
1857 // each target.
1858 static uint64_t getCommonPageSize(opt::InputArgList &args) {
1859 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1860 target->defaultCommonPageSize);
1861 if (!isPowerOf2_64(val)) {
1862 error("common-page-size: value isn't a power of 2");
1863 return target->defaultCommonPageSize;
1865 if (config->nmagic || config->omagic) {
1866 if (val != target->defaultCommonPageSize)
1867 warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1868 return 1;
1870 // commonPageSize can't be larger than maxPageSize.
1871 if (val > config->maxPageSize)
1872 val = config->maxPageSize;
1873 return val;
1876 // Parses --image-base option.
1877 static std::optional<uint64_t> getImageBase(opt::InputArgList &args) {
1878 // Because we are using "Config->maxPageSize" here, this function has to be
1879 // called after the variable is initialized.
1880 auto *arg = args.getLastArg(OPT_image_base);
1881 if (!arg)
1882 return std::nullopt;
1884 StringRef s = arg->getValue();
1885 uint64_t v;
1886 if (!to_integer(s, v)) {
1887 error("--image-base: number expected, but got " + s);
1888 return 0;
1890 if ((v % config->maxPageSize) != 0)
1891 warn("--image-base: address isn't multiple of page size: " + s);
1892 return v;
1895 // Parses `--exclude-libs=lib,lib,...`.
1896 // The library names may be delimited by commas or colons.
1897 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1898 DenseSet<StringRef> ret;
1899 for (auto *arg : args.filtered(OPT_exclude_libs)) {
1900 StringRef s = arg->getValue();
1901 for (;;) {
1902 size_t pos = s.find_first_of(",:");
1903 if (pos == StringRef::npos)
1904 break;
1905 ret.insert(s.substr(0, pos));
1906 s = s.substr(pos + 1);
1908 ret.insert(s);
1910 return ret;
1913 // Handles the --exclude-libs option. If a static library file is specified
1914 // by the --exclude-libs option, all public symbols from the archive become
1915 // private unless otherwise specified by version scripts or something.
1916 // A special library name "ALL" means all archive files.
1918 // This is not a popular option, but some programs such as bionic libc use it.
1919 static void excludeLibs(opt::InputArgList &args) {
1920 DenseSet<StringRef> libs = getExcludeLibs(args);
1921 bool all = libs.count("ALL");
1923 auto visit = [&](InputFile *file) {
1924 if (file->archiveName.empty() ||
1925 !(all || libs.count(path::filename(file->archiveName))))
1926 return;
1927 ArrayRef<Symbol *> symbols = file->getSymbols();
1928 if (isa<ELFFileBase>(file))
1929 symbols = cast<ELFFileBase>(file)->getGlobalSymbols();
1930 for (Symbol *sym : symbols)
1931 if (!sym->isUndefined() && sym->file == file)
1932 sym->versionId = VER_NDX_LOCAL;
1935 for (ELFFileBase *file : ctx.objectFiles)
1936 visit(file);
1938 for (BitcodeFile *file : ctx.bitcodeFiles)
1939 visit(file);
1942 // Force Sym to be entered in the output.
1943 static void handleUndefined(Symbol *sym, const char *option) {
1944 // Since a symbol may not be used inside the program, LTO may
1945 // eliminate it. Mark the symbol as "used" to prevent it.
1946 sym->isUsedInRegularObj = true;
1948 if (!sym->isLazy())
1949 return;
1950 sym->extract();
1951 if (!config->whyExtract.empty())
1952 ctx.whyExtractRecords.emplace_back(option, sym->file, *sym);
1955 // As an extension to GNU linkers, lld supports a variant of `-u`
1956 // which accepts wildcard patterns. All symbols that match a given
1957 // pattern are handled as if they were given by `-u`.
1958 static void handleUndefinedGlob(StringRef arg) {
1959 Expected<GlobPattern> pat = GlobPattern::create(arg);
1960 if (!pat) {
1961 error("--undefined-glob: " + toString(pat.takeError()));
1962 return;
1965 // Calling sym->extract() in the loop is not safe because it may add new
1966 // symbols to the symbol table, invalidating the current iterator.
1967 SmallVector<Symbol *, 0> syms;
1968 for (Symbol *sym : symtab.getSymbols())
1969 if (!sym->isPlaceholder() && pat->match(sym->getName()))
1970 syms.push_back(sym);
1972 for (Symbol *sym : syms)
1973 handleUndefined(sym, "--undefined-glob");
1976 static void handleLibcall(StringRef name) {
1977 Symbol *sym = symtab.find(name);
1978 if (!sym || !sym->isLazy())
1979 return;
1981 MemoryBufferRef mb;
1982 mb = cast<LazyObject>(sym)->file->mb;
1984 if (isBitcode(mb))
1985 sym->extract();
1988 static void writeArchiveStats() {
1989 if (config->printArchiveStats.empty())
1990 return;
1992 std::error_code ec;
1993 raw_fd_ostream os = ctx.openAuxiliaryFile(config->printArchiveStats, ec);
1994 if (ec) {
1995 error("--print-archive-stats=: cannot open " + config->printArchiveStats +
1996 ": " + ec.message());
1997 return;
2000 os << "members\textracted\tarchive\n";
2002 SmallVector<StringRef, 0> archives;
2003 DenseMap<CachedHashStringRef, unsigned> all, extracted;
2004 for (ELFFileBase *file : ctx.objectFiles)
2005 if (file->archiveName.size())
2006 ++extracted[CachedHashStringRef(file->archiveName)];
2007 for (BitcodeFile *file : ctx.bitcodeFiles)
2008 if (file->archiveName.size())
2009 ++extracted[CachedHashStringRef(file->archiveName)];
2010 for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) {
2011 unsigned &v = extracted[CachedHashString(f.first)];
2012 os << f.second << '\t' << v << '\t' << f.first << '\n';
2013 // If the archive occurs multiple times, other instances have a count of 0.
2014 v = 0;
2018 static void writeWhyExtract() {
2019 if (config->whyExtract.empty())
2020 return;
2022 std::error_code ec;
2023 raw_fd_ostream os = ctx.openAuxiliaryFile(config->whyExtract, ec);
2024 if (ec) {
2025 error("cannot open --why-extract= file " + config->whyExtract + ": " +
2026 ec.message());
2027 return;
2030 os << "reference\textracted\tsymbol\n";
2031 for (auto &entry : ctx.whyExtractRecords) {
2032 os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t'
2033 << toString(std::get<2>(entry)) << '\n';
2037 static void reportBackrefs() {
2038 for (auto &ref : ctx.backwardReferences) {
2039 const Symbol &sym = *ref.first;
2040 std::string to = toString(ref.second.second);
2041 // Some libraries have known problems and can cause noise. Filter them out
2042 // with --warn-backrefs-exclude=. The value may look like (for --start-lib)
2043 // *.o or (archive member) *.a(*.o).
2044 bool exclude = false;
2045 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
2046 if (pat.match(to)) {
2047 exclude = true;
2048 break;
2050 if (!exclude)
2051 warn("backward reference detected: " + sym.getName() + " in " +
2052 toString(ref.second.first) + " refers to " + to);
2056 // Handle --dependency-file=<path>. If that option is given, lld creates a
2057 // file at a given path with the following contents:
2059 // <output-file>: <input-file> ...
2061 // <input-file>:
2063 // where <output-file> is a pathname of an output file and <input-file>
2064 // ... is a list of pathnames of all input files. `make` command can read a
2065 // file in the above format and interpret it as a dependency info. We write
2066 // phony targets for every <input-file> to avoid an error when that file is
2067 // removed.
2069 // This option is useful if you want to make your final executable to depend
2070 // on all input files including system libraries. Here is why.
2072 // When you write a Makefile, you usually write it so that the final
2073 // executable depends on all user-generated object files. Normally, you
2074 // don't make your executable to depend on system libraries (such as libc)
2075 // because you don't know the exact paths of libraries, even though system
2076 // libraries that are linked to your executable statically are technically a
2077 // part of your program. By using --dependency-file option, you can make
2078 // lld to dump dependency info so that you can maintain exact dependencies
2079 // easily.
2080 static void writeDependencyFile() {
2081 std::error_code ec;
2082 raw_fd_ostream os = ctx.openAuxiliaryFile(config->dependencyFile, ec);
2083 if (ec) {
2084 error("cannot open " + config->dependencyFile + ": " + ec.message());
2085 return;
2088 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
2089 // * A space is escaped by a backslash which itself must be escaped.
2090 // * A hash sign is escaped by a single backslash.
2091 // * $ is escapes as $$.
2092 auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
2093 llvm::SmallString<256> nativePath;
2094 llvm::sys::path::native(filename.str(), nativePath);
2095 llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
2096 for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
2097 if (nativePath[i] == '#') {
2098 os << '\\';
2099 } else if (nativePath[i] == ' ') {
2100 os << '\\';
2101 unsigned j = i;
2102 while (j > 0 && nativePath[--j] == '\\')
2103 os << '\\';
2104 } else if (nativePath[i] == '$') {
2105 os << '$';
2107 os << nativePath[i];
2111 os << config->outputFile << ":";
2112 for (StringRef path : config->dependencyFiles) {
2113 os << " \\\n ";
2114 printFilename(os, path);
2116 os << "\n";
2118 for (StringRef path : config->dependencyFiles) {
2119 os << "\n";
2120 printFilename(os, path);
2121 os << ":\n";
2125 // Replaces common symbols with defined symbols reside in .bss sections.
2126 // This function is called after all symbol names are resolved. As a
2127 // result, the passes after the symbol resolution won't see any
2128 // symbols of type CommonSymbol.
2129 static void replaceCommonSymbols() {
2130 llvm::TimeTraceScope timeScope("Replace common symbols");
2131 for (ELFFileBase *file : ctx.objectFiles) {
2132 if (!file->hasCommonSyms)
2133 continue;
2134 for (Symbol *sym : file->getGlobalSymbols()) {
2135 auto *s = dyn_cast<CommonSymbol>(sym);
2136 if (!s)
2137 continue;
2139 auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
2140 bss->file = s->file;
2141 ctx.inputSections.push_back(bss);
2142 Defined(s->file, StringRef(), s->binding, s->stOther, s->type,
2143 /*value=*/0, s->size, bss)
2144 .overwrite(*s);
2149 // If all references to a DSO happen to be weak, the DSO is not added to
2150 // DT_NEEDED. If that happens, replace ShardSymbol with Undefined to avoid
2151 // dangling references to an unneeded DSO. Use a weak binding to avoid
2152 // --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols.
2153 static void demoteSharedAndLazySymbols() {
2154 llvm::TimeTraceScope timeScope("Demote shared and lazy symbols");
2155 for (Symbol *sym : symtab.getSymbols()) {
2156 auto *s = dyn_cast<SharedSymbol>(sym);
2157 if (!(s && !cast<SharedFile>(s->file)->isNeeded) && !sym->isLazy())
2158 continue;
2160 uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK);
2161 Undefined(nullptr, sym->getName(), binding, sym->stOther, sym->type)
2162 .overwrite(*sym);
2163 sym->versionId = VER_NDX_GLOBAL;
2167 // The section referred to by `s` is considered address-significant. Set the
2168 // keepUnique flag on the section if appropriate.
2169 static void markAddrsig(Symbol *s) {
2170 if (auto *d = dyn_cast_or_null<Defined>(s))
2171 if (d->section)
2172 // We don't need to keep text sections unique under --icf=all even if they
2173 // are address-significant.
2174 if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
2175 d->section->keepUnique = true;
2178 // Record sections that define symbols mentioned in --keep-unique <symbol>
2179 // and symbols referred to by address-significance tables. These sections are
2180 // ineligible for ICF.
2181 template <class ELFT>
2182 static void findKeepUniqueSections(opt::InputArgList &args) {
2183 for (auto *arg : args.filtered(OPT_keep_unique)) {
2184 StringRef name = arg->getValue();
2185 auto *d = dyn_cast_or_null<Defined>(symtab.find(name));
2186 if (!d || !d->section) {
2187 warn("could not find symbol " + name + " to keep unique");
2188 continue;
2190 d->section->keepUnique = true;
2193 // --icf=all --ignore-data-address-equality means that we can ignore
2194 // the dynsym and address-significance tables entirely.
2195 if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
2196 return;
2198 // Symbols in the dynsym could be address-significant in other executables
2199 // or DSOs, so we conservatively mark them as address-significant.
2200 for (Symbol *sym : symtab.getSymbols())
2201 if (sym->includeInDynsym())
2202 markAddrsig(sym);
2204 // Visit the address-significance table in each object file and mark each
2205 // referenced symbol as address-significant.
2206 for (InputFile *f : ctx.objectFiles) {
2207 auto *obj = cast<ObjFile<ELFT>>(f);
2208 ArrayRef<Symbol *> syms = obj->getSymbols();
2209 if (obj->addrsigSec) {
2210 ArrayRef<uint8_t> contents =
2211 check(obj->getObj().getSectionContents(*obj->addrsigSec));
2212 const uint8_t *cur = contents.begin();
2213 while (cur != contents.end()) {
2214 unsigned size;
2215 const char *err;
2216 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
2217 if (err)
2218 fatal(toString(f) + ": could not decode addrsig section: " + err);
2219 markAddrsig(syms[symIndex]);
2220 cur += size;
2222 } else {
2223 // If an object file does not have an address-significance table,
2224 // conservatively mark all of its symbols as address-significant.
2225 for (Symbol *s : syms)
2226 markAddrsig(s);
2231 // This function reads a symbol partition specification section. These sections
2232 // are used to control which partition a symbol is allocated to. See
2233 // https://lld.llvm.org/Partitions.html for more details on partitions.
2234 template <typename ELFT>
2235 static void readSymbolPartitionSection(InputSectionBase *s) {
2236 // Read the relocation that refers to the partition's entry point symbol.
2237 Symbol *sym;
2238 const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
2239 if (rels.areRelocsRel())
2240 sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]);
2241 else
2242 sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]);
2243 if (!isa<Defined>(sym) || !sym->includeInDynsym())
2244 return;
2246 StringRef partName = reinterpret_cast<const char *>(s->content().data());
2247 for (Partition &part : partitions) {
2248 if (part.name == partName) {
2249 sym->partition = part.getNumber();
2250 return;
2254 // Forbid partitions from being used on incompatible targets, and forbid them
2255 // from being used together with various linker features that assume a single
2256 // set of output sections.
2257 if (script->hasSectionsCommand)
2258 error(toString(s->file) +
2259 ": partitions cannot be used with the SECTIONS command");
2260 if (script->hasPhdrsCommands())
2261 error(toString(s->file) +
2262 ": partitions cannot be used with the PHDRS command");
2263 if (!config->sectionStartMap.empty())
2264 error(toString(s->file) + ": partitions cannot be used with "
2265 "--section-start, -Ttext, -Tdata or -Tbss");
2266 if (config->emachine == EM_MIPS)
2267 error(toString(s->file) + ": partitions cannot be used on this target");
2269 // Impose a limit of no more than 254 partitions. This limit comes from the
2270 // sizes of the Partition fields in InputSectionBase and Symbol, as well as
2271 // the amount of space devoted to the partition number in RankFlags.
2272 if (partitions.size() == 254)
2273 fatal("may not have more than 254 partitions");
2275 partitions.emplace_back();
2276 Partition &newPart = partitions.back();
2277 newPart.name = partName;
2278 sym->partition = newPart.getNumber();
2281 static Symbol *addUnusedUndefined(StringRef name,
2282 uint8_t binding = STB_GLOBAL) {
2283 return symtab.addSymbol(Undefined{nullptr, name, binding, STV_DEFAULT, 0});
2286 static void markBuffersAsDontNeed(bool skipLinkedOutput) {
2287 // With --thinlto-index-only, all buffers are nearly unused from now on
2288 // (except symbol/section names used by infrequent passes). Mark input file
2289 // buffers as MADV_DONTNEED so that these pages can be reused by the expensive
2290 // thin link, saving memory.
2291 if (skipLinkedOutput) {
2292 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))
2293 mb.dontNeedIfMmap();
2294 return;
2297 // Otherwise, just mark MemoryBuffers backing BitcodeFiles.
2298 DenseSet<const char *> bufs;
2299 for (BitcodeFile *file : ctx.bitcodeFiles)
2300 bufs.insert(file->mb.getBufferStart());
2301 for (BitcodeFile *file : ctx.lazyBitcodeFiles)
2302 bufs.insert(file->mb.getBufferStart());
2303 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))
2304 if (bufs.count(mb.getBufferStart()))
2305 mb.dontNeedIfMmap();
2308 // This function is where all the optimizations of link-time
2309 // optimization takes place. When LTO is in use, some input files are
2310 // not in native object file format but in the LLVM bitcode format.
2311 // This function compiles bitcode files into a few big native files
2312 // using LLVM functions and replaces bitcode symbols with the results.
2313 // Because all bitcode files that the program consists of are passed to
2314 // the compiler at once, it can do a whole-program optimization.
2315 template <class ELFT>
2316 void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) {
2317 llvm::TimeTraceScope timeScope("LTO");
2318 // Compile bitcode files and replace bitcode symbols.
2319 lto.reset(new BitcodeCompiler);
2320 for (BitcodeFile *file : ctx.bitcodeFiles)
2321 lto->add(*file);
2323 if (!ctx.bitcodeFiles.empty())
2324 markBuffersAsDontNeed(skipLinkedOutput);
2326 for (InputFile *file : lto->compile()) {
2327 auto *obj = cast<ObjFile<ELFT>>(file);
2328 obj->parse(/*ignoreComdats=*/true);
2330 // Parse '@' in symbol names for non-relocatable output.
2331 if (!config->relocatable)
2332 for (Symbol *sym : obj->getGlobalSymbols())
2333 if (sym->hasVersionSuffix)
2334 sym->parseSymbolVersion();
2335 ctx.objectFiles.push_back(obj);
2339 // The --wrap option is a feature to rename symbols so that you can write
2340 // wrappers for existing functions. If you pass `--wrap=foo`, all
2341 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
2342 // expected to write `__wrap_foo` function as a wrapper). The original
2343 // symbol becomes accessible as `__real_foo`, so you can call that from your
2344 // wrapper.
2346 // This data structure is instantiated for each --wrap option.
2347 struct WrappedSymbol {
2348 Symbol *sym;
2349 Symbol *real;
2350 Symbol *wrap;
2353 // Handles --wrap option.
2355 // This function instantiates wrapper symbols. At this point, they seem
2356 // like they are not being used at all, so we explicitly set some flags so
2357 // that LTO won't eliminate them.
2358 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
2359 std::vector<WrappedSymbol> v;
2360 DenseSet<StringRef> seen;
2362 for (auto *arg : args.filtered(OPT_wrap)) {
2363 StringRef name = arg->getValue();
2364 if (!seen.insert(name).second)
2365 continue;
2367 Symbol *sym = symtab.find(name);
2368 if (!sym)
2369 continue;
2371 Symbol *wrap =
2372 addUnusedUndefined(saver().save("__wrap_" + name), sym->binding);
2374 // If __real_ is referenced, pull in the symbol if it is lazy. Do this after
2375 // processing __wrap_ as that may have referenced __real_.
2376 StringRef realName = saver().save("__real_" + name);
2377 if (symtab.find(realName))
2378 addUnusedUndefined(name, sym->binding);
2380 Symbol *real = addUnusedUndefined(realName);
2381 v.push_back({sym, real, wrap});
2383 // We want to tell LTO not to inline symbols to be overwritten
2384 // because LTO doesn't know the final symbol contents after renaming.
2385 real->scriptDefined = true;
2386 sym->scriptDefined = true;
2388 // If a symbol is referenced in any object file, bitcode file or shared
2389 // object, mark its redirection target (foo for __real_foo and __wrap_foo
2390 // for foo) as referenced after redirection, which will be used to tell LTO
2391 // to not eliminate the redirection target. If the object file defining the
2392 // symbol also references it, we cannot easily distinguish the case from
2393 // cases where the symbol is not referenced. Retain the redirection target
2394 // in this case because we choose to wrap symbol references regardless of
2395 // whether the symbol is defined
2396 // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
2397 if (real->referenced || real->isDefined())
2398 sym->referencedAfterWrap = true;
2399 if (sym->referenced || sym->isDefined())
2400 wrap->referencedAfterWrap = true;
2402 return v;
2405 static void combineVersionedSymbol(Symbol &sym,
2406 DenseMap<Symbol *, Symbol *> &map) {
2407 const char *suffix1 = sym.getVersionSuffix();
2408 if (suffix1[0] != '@' || suffix1[1] == '@')
2409 return;
2411 // Check the existing symbol foo. We have two special cases to handle:
2413 // * There is a definition of foo@v1 and foo@@v1.
2414 // * There is a definition of foo@v1 and foo.
2415 Defined *sym2 = dyn_cast_or_null<Defined>(symtab.find(sym.getName()));
2416 if (!sym2)
2417 return;
2418 const char *suffix2 = sym2->getVersionSuffix();
2419 if (suffix2[0] == '@' && suffix2[1] == '@' &&
2420 strcmp(suffix1 + 1, suffix2 + 2) == 0) {
2421 // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
2422 map.try_emplace(&sym, sym2);
2423 // If both foo@v1 and foo@@v1 are defined and non-weak, report a
2424 // duplicate definition error.
2425 if (sym.isDefined()) {
2426 sym2->checkDuplicate(cast<Defined>(sym));
2427 sym2->resolve(cast<Defined>(sym));
2428 } else if (sym.isUndefined()) {
2429 sym2->resolve(cast<Undefined>(sym));
2430 } else {
2431 sym2->resolve(cast<SharedSymbol>(sym));
2433 // Eliminate foo@v1 from the symbol table.
2434 sym.symbolKind = Symbol::PlaceholderKind;
2435 sym.isUsedInRegularObj = false;
2436 } else if (auto *sym1 = dyn_cast<Defined>(&sym)) {
2437 if (sym2->versionId > VER_NDX_GLOBAL
2438 ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1
2439 : sym1->section == sym2->section && sym1->value == sym2->value) {
2440 // Due to an assembler design flaw, if foo is defined, .symver foo,
2441 // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2442 // different version, GNU ld makes foo@v1 canonical and eliminates
2443 // foo. Emulate its behavior, otherwise we would have foo or foo@@v1
2444 // beside foo@v1. foo@v1 and foo combining does not apply if they are
2445 // not defined in the same place.
2446 map.try_emplace(sym2, &sym);
2447 sym2->symbolKind = Symbol::PlaceholderKind;
2448 sym2->isUsedInRegularObj = false;
2453 // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
2455 // When this function is executed, only InputFiles and symbol table
2456 // contain pointers to symbol objects. We visit them to replace pointers,
2457 // so that wrapped symbols are swapped as instructed by the command line.
2458 static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) {
2459 llvm::TimeTraceScope timeScope("Redirect symbols");
2460 DenseMap<Symbol *, Symbol *> map;
2461 for (const WrappedSymbol &w : wrapped) {
2462 map[w.sym] = w.wrap;
2463 map[w.real] = w.sym;
2466 // If there are version definitions (versionDefinitions.size() > 2), enumerate
2467 // symbols with a non-default version (foo@v1) and check whether it should be
2468 // combined with foo or foo@@v1.
2469 if (config->versionDefinitions.size() > 2)
2470 for (Symbol *sym : symtab.getSymbols())
2471 if (sym->hasVersionSuffix)
2472 combineVersionedSymbol(*sym, map);
2474 if (map.empty())
2475 return;
2477 // Update pointers in input files.
2478 parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) {
2479 for (Symbol *&sym : file->getMutableGlobalSymbols())
2480 if (Symbol *s = map.lookup(sym))
2481 sym = s;
2484 // Update pointers in the symbol table.
2485 for (const WrappedSymbol &w : wrapped)
2486 symtab.wrap(w.sym, w.real, w.wrap);
2489 static void checkAndReportMissingFeature(StringRef config, uint32_t features,
2490 uint32_t mask, const Twine &report) {
2491 if (!(features & mask)) {
2492 if (config == "error")
2493 error(report);
2494 else if (config == "warning")
2495 warn(report);
2499 // To enable CET (x86's hardware-assisted control flow enforcement), each
2500 // source file must be compiled with -fcf-protection. Object files compiled
2501 // with the flag contain feature flags indicating that they are compatible
2502 // with CET. We enable the feature only when all object files are compatible
2503 // with CET.
2505 // This is also the case with AARCH64's BTI and PAC which use the similar
2506 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
2507 static uint32_t getAndFeatures() {
2508 if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
2509 config->emachine != EM_AARCH64)
2510 return 0;
2512 uint32_t ret = -1;
2513 for (ELFFileBase *f : ctx.objectFiles) {
2514 uint32_t features = f->andFeatures;
2516 checkAndReportMissingFeature(
2517 config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI,
2518 toString(f) + ": -z bti-report: file does not have "
2519 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2521 checkAndReportMissingFeature(
2522 config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT,
2523 toString(f) + ": -z cet-report: file does not have "
2524 "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2526 checkAndReportMissingFeature(
2527 config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK,
2528 toString(f) + ": -z cet-report: file does not have "
2529 "GNU_PROPERTY_X86_FEATURE_1_SHSTK property");
2531 if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
2532 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
2533 if (config->zBtiReport == "none")
2534 warn(toString(f) + ": -z force-bti: file does not have "
2535 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2536 } else if (config->zForceIbt &&
2537 !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
2538 if (config->zCetReport == "none")
2539 warn(toString(f) + ": -z force-ibt: file does not have "
2540 "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2541 features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
2543 if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
2544 warn(toString(f) + ": -z pac-plt: file does not have "
2545 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
2546 features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
2548 ret &= features;
2551 // Force enable Shadow Stack.
2552 if (config->zShstk)
2553 ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
2555 return ret;
2558 static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) {
2559 switch (file->ekind) {
2560 case ELF32LEKind:
2561 cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2562 break;
2563 case ELF32BEKind:
2564 cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2565 break;
2566 case ELF64LEKind:
2567 cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2568 break;
2569 case ELF64BEKind:
2570 cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2571 break;
2572 default:
2573 llvm_unreachable("");
2577 static void postParseObjectFile(ELFFileBase *file) {
2578 switch (file->ekind) {
2579 case ELF32LEKind:
2580 cast<ObjFile<ELF32LE>>(file)->postParse();
2581 break;
2582 case ELF32BEKind:
2583 cast<ObjFile<ELF32BE>>(file)->postParse();
2584 break;
2585 case ELF64LEKind:
2586 cast<ObjFile<ELF64LE>>(file)->postParse();
2587 break;
2588 case ELF64BEKind:
2589 cast<ObjFile<ELF64BE>>(file)->postParse();
2590 break;
2591 default:
2592 llvm_unreachable("");
2596 // Do actual linking. Note that when this function is called,
2597 // all linker scripts have already been parsed.
2598 void LinkerDriver::link(opt::InputArgList &args) {
2599 llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
2600 // If a --hash-style option was not given, set to a default value,
2601 // which varies depending on the target.
2602 if (!args.hasArg(OPT_hash_style)) {
2603 if (config->emachine == EM_MIPS)
2604 config->sysvHash = true;
2605 else
2606 config->sysvHash = config->gnuHash = true;
2609 // Default output filename is "a.out" by the Unix tradition.
2610 if (config->outputFile.empty())
2611 config->outputFile = "a.out";
2613 // Fail early if the output file or map file is not writable. If a user has a
2614 // long link, e.g. due to a large LTO link, they do not wish to run it and
2615 // find that it failed because there was a mistake in their command-line.
2617 llvm::TimeTraceScope timeScope("Create output files");
2618 if (auto e = tryCreateFile(config->outputFile))
2619 error("cannot open output file " + config->outputFile + ": " +
2620 e.message());
2621 if (auto e = tryCreateFile(config->mapFile))
2622 error("cannot open map file " + config->mapFile + ": " + e.message());
2623 if (auto e = tryCreateFile(config->whyExtract))
2624 error("cannot open --why-extract= file " + config->whyExtract + ": " +
2625 e.message());
2627 if (errorCount())
2628 return;
2630 // Use default entry point name if no name was given via the command
2631 // line nor linker scripts. For some reason, MIPS entry point name is
2632 // different from others.
2633 config->warnMissingEntry =
2634 (!config->entry.empty() || (!config->shared && !config->relocatable));
2635 if (config->entry.empty() && !config->relocatable)
2636 config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
2638 // Handle --trace-symbol.
2639 for (auto *arg : args.filtered(OPT_trace_symbol))
2640 symtab.insert(arg->getValue())->traced = true;
2642 // Handle -u/--undefined before input files. If both a.a and b.so define foo,
2643 // -u foo a.a b.so will extract a.a.
2644 for (StringRef name : config->undefined)
2645 addUnusedUndefined(name)->referenced = true;
2647 // Add all files to the symbol table. This will add almost all
2648 // symbols that we need to the symbol table. This process might
2649 // add files to the link, via autolinking, these files are always
2650 // appended to the Files vector.
2652 llvm::TimeTraceScope timeScope("Parse input files");
2653 for (size_t i = 0; i < files.size(); ++i) {
2654 llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
2655 parseFile(files[i]);
2657 if (armCmseImpLib)
2658 parseArmCMSEImportLib(*armCmseImpLib);
2661 // Now that we have every file, we can decide if we will need a
2662 // dynamic symbol table.
2663 // We need one if we were asked to export dynamic symbols or if we are
2664 // producing a shared library.
2665 // We also need one if any shared libraries are used and for pie executables
2666 // (probably because the dynamic linker needs it).
2667 config->hasDynSymTab =
2668 !ctx.sharedFiles.empty() || config->isPic || config->exportDynamic;
2670 // Some symbols (such as __ehdr_start) are defined lazily only when there
2671 // are undefined symbols for them, so we add these to trigger that logic.
2672 for (StringRef name : script->referencedSymbols) {
2673 Symbol *sym = addUnusedUndefined(name);
2674 sym->isUsedInRegularObj = true;
2675 sym->referenced = true;
2678 // Prevent LTO from removing any definition referenced by -u.
2679 for (StringRef name : config->undefined)
2680 if (Defined *sym = dyn_cast_or_null<Defined>(symtab.find(name)))
2681 sym->isUsedInRegularObj = true;
2683 // If an entry symbol is in a static archive, pull out that file now.
2684 if (Symbol *sym = symtab.find(config->entry))
2685 handleUndefined(sym, "--entry");
2687 // Handle the `--undefined-glob <pattern>` options.
2688 for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
2689 handleUndefinedGlob(pat);
2691 // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2692 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->init)))
2693 sym->isUsedInRegularObj = true;
2694 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->fini)))
2695 sym->isUsedInRegularObj = true;
2697 // If any of our inputs are bitcode files, the LTO code generator may create
2698 // references to certain library functions that might not be explicit in the
2699 // bitcode file's symbol table. If any of those library functions are defined
2700 // in a bitcode file in an archive member, we need to arrange to use LTO to
2701 // compile those archive members by adding them to the link beforehand.
2703 // However, adding all libcall symbols to the link can have undesired
2704 // consequences. For example, the libgcc implementation of
2705 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
2706 // that aborts the program if the Linux kernel does not support 64-bit
2707 // atomics, which would prevent the program from running even if it does not
2708 // use 64-bit atomics.
2710 // Therefore, we only add libcall symbols to the link before LTO if we have
2711 // to, i.e. if the symbol's definition is in bitcode. Any other required
2712 // libcall symbols will be added to the link after LTO when we add the LTO
2713 // object file to the link.
2714 if (!ctx.bitcodeFiles.empty())
2715 for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2716 handleLibcall(s);
2718 // Archive members defining __wrap symbols may be extracted.
2719 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
2721 // No more lazy bitcode can be extracted at this point. Do post parse work
2722 // like checking duplicate symbols.
2723 parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {
2724 initSectionsAndLocalSyms(file, /*ignoreComdats=*/false);
2726 parallelForEach(ctx.objectFiles, postParseObjectFile);
2727 parallelForEach(ctx.bitcodeFiles,
2728 [](BitcodeFile *file) { file->postParse(); });
2729 for (auto &it : ctx.nonPrevailingSyms) {
2730 Symbol &sym = *it.first;
2731 Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type,
2732 it.second)
2733 .overwrite(sym);
2734 cast<Undefined>(sym).nonPrevailing = true;
2736 ctx.nonPrevailingSyms.clear();
2737 for (const DuplicateSymbol &d : ctx.duplicates)
2738 reportDuplicate(*d.sym, d.file, d.section, d.value);
2739 ctx.duplicates.clear();
2741 // Return if there were name resolution errors.
2742 if (errorCount())
2743 return;
2745 // We want to declare linker script's symbols early,
2746 // so that we can version them.
2747 // They also might be exported if referenced by DSOs.
2748 script->declareSymbols();
2750 // Handle --exclude-libs. This is before scanVersionScript() due to a
2751 // workaround for Android ndk: for a defined versioned symbol in an archive
2752 // without a version node in the version script, Android does not expect a
2753 // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2754 // GNU ld errors in this case.
2755 if (args.hasArg(OPT_exclude_libs))
2756 excludeLibs(args);
2758 // Create elfHeader early. We need a dummy section in
2759 // addReservedSymbols to mark the created symbols as not absolute.
2760 Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
2762 // We need to create some reserved symbols such as _end. Create them.
2763 if (!config->relocatable)
2764 addReservedSymbols();
2766 // Apply version scripts.
2768 // For a relocatable output, version scripts don't make sense, and
2769 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
2770 // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2771 if (!config->relocatable) {
2772 llvm::TimeTraceScope timeScope("Process symbol versions");
2773 symtab.scanVersionScript();
2776 // Skip the normal linked output if some LTO options are specified.
2778 // For --thinlto-index-only, index file creation is performed in
2779 // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and
2780 // --plugin-opt=emit-asm create output files in bitcode or assembly code,
2781 // respectively. When only certain thinLTO modules are specified for
2782 // compilation, the intermediate object file are the expected output.
2783 const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM ||
2784 config->ltoEmitAsm ||
2785 !config->thinLTOModulesToCompile.empty();
2787 // Do link-time optimization if given files are LLVM bitcode files.
2788 // This compiles bitcode files into real object files.
2790 // With this the symbol table should be complete. After this, no new names
2791 // except a few linker-synthesized ones will be added to the symbol table.
2792 const size_t numObjsBeforeLTO = ctx.objectFiles.size();
2793 invokeELFT(compileBitcodeFiles, skipLinkedOutput);
2795 // Symbol resolution finished. Report backward reference problems,
2796 // --print-archive-stats=, and --why-extract=.
2797 reportBackrefs();
2798 writeArchiveStats();
2799 writeWhyExtract();
2800 if (errorCount())
2801 return;
2803 // Bail out if normal linked output is skipped due to LTO.
2804 if (skipLinkedOutput)
2805 return;
2807 // compileBitcodeFiles may have produced lto.tmp object files. After this, no
2808 // more file will be added.
2809 auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO);
2810 parallelForEach(newObjectFiles, [](ELFFileBase *file) {
2811 initSectionsAndLocalSyms(file, /*ignoreComdats=*/true);
2813 parallelForEach(newObjectFiles, postParseObjectFile);
2814 for (const DuplicateSymbol &d : ctx.duplicates)
2815 reportDuplicate(*d.sym, d.file, d.section, d.value);
2817 // Handle --exclude-libs again because lto.tmp may reference additional
2818 // libcalls symbols defined in an excluded archive. This may override
2819 // versionId set by scanVersionScript().
2820 if (args.hasArg(OPT_exclude_libs))
2821 excludeLibs(args);
2823 // Record [__acle_se_<sym>, <sym>] pairs for later processing.
2824 processArmCmseSymbols();
2826 // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
2827 redirectSymbols(wrapped);
2829 // Replace common symbols with regular symbols.
2830 replaceCommonSymbols();
2833 llvm::TimeTraceScope timeScope("Aggregate sections");
2834 // Now that we have a complete list of input files.
2835 // Beyond this point, no new files are added.
2836 // Aggregate all input sections into one place.
2837 for (InputFile *f : ctx.objectFiles) {
2838 for (InputSectionBase *s : f->getSections()) {
2839 if (!s || s == &InputSection::discarded)
2840 continue;
2841 if (LLVM_UNLIKELY(isa<EhInputSection>(s)))
2842 ctx.ehInputSections.push_back(cast<EhInputSection>(s));
2843 else
2844 ctx.inputSections.push_back(s);
2847 for (BinaryFile *f : ctx.binaryFiles)
2848 for (InputSectionBase *s : f->getSections())
2849 ctx.inputSections.push_back(cast<InputSection>(s));
2853 llvm::TimeTraceScope timeScope("Strip sections");
2854 if (ctx.hasSympart.load(std::memory_order_relaxed)) {
2855 llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
2856 if (s->type != SHT_LLVM_SYMPART)
2857 return false;
2858 invokeELFT(readSymbolPartitionSection, s);
2859 return true;
2862 // We do not want to emit debug sections if --strip-all
2863 // or --strip-debug are given.
2864 if (config->strip != StripPolicy::None) {
2865 llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
2866 if (isDebugSection(*s))
2867 return true;
2868 if (auto *isec = dyn_cast<InputSection>(s))
2869 if (InputSectionBase *rel = isec->getRelocatedSection())
2870 if (isDebugSection(*rel))
2871 return true;
2873 return false;
2878 // Since we now have a complete set of input files, we can create
2879 // a .d file to record build dependencies.
2880 if (!config->dependencyFile.empty())
2881 writeDependencyFile();
2883 // Now that the number of partitions is fixed, save a pointer to the main
2884 // partition.
2885 mainPart = &partitions[0];
2887 // Read .note.gnu.property sections from input object files which
2888 // contain a hint to tweak linker's and loader's behaviors.
2889 config->andFeatures = getAndFeatures();
2891 // The Target instance handles target-specific stuff, such as applying
2892 // relocations or writing a PLT section. It also contains target-dependent
2893 // values such as a default image base address.
2894 target = getTarget();
2896 config->eflags = target->calcEFlags();
2897 // maxPageSize (sometimes called abi page size) is the maximum page size that
2898 // the output can be run on. For example if the OS can use 4k or 64k page
2899 // sizes then maxPageSize must be 64k for the output to be useable on both.
2900 // All important alignment decisions must use this value.
2901 config->maxPageSize = getMaxPageSize(args);
2902 // commonPageSize is the most common page size that the output will be run on.
2903 // For example if an OS can use 4k or 64k page sizes and 4k is more common
2904 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
2905 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
2906 // is limited to writing trap instructions on the last executable segment.
2907 config->commonPageSize = getCommonPageSize(args);
2909 config->imageBase = getImageBase(args);
2911 // This adds a .comment section containing a version string.
2912 if (!config->relocatable)
2913 ctx.inputSections.push_back(createCommentSection());
2915 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
2916 invokeELFT(splitSections,);
2918 // Garbage collection and removal of shared symbols from unused shared objects.
2919 invokeELFT(markLive,);
2920 demoteSharedAndLazySymbols();
2922 // Make copies of any input sections that need to be copied into each
2923 // partition.
2924 copySectionsIntoPartitions();
2926 // Create synthesized sections such as .got and .plt. This is called before
2927 // processSectionCommands() so that they can be placed by SECTIONS commands.
2928 invokeELFT(createSyntheticSections,);
2930 // Some input sections that are used for exception handling need to be moved
2931 // into synthetic sections. Do that now so that they aren't assigned to
2932 // output sections in the usual way.
2933 if (!config->relocatable)
2934 combineEhSections();
2936 // Merge .riscv.attributes sections.
2937 if (config->emachine == EM_RISCV)
2938 mergeRISCVAttributesSections();
2941 llvm::TimeTraceScope timeScope("Assign sections");
2943 // Create output sections described by SECTIONS commands.
2944 script->processSectionCommands();
2946 // Linker scripts control how input sections are assigned to output
2947 // sections. Input sections that were not handled by scripts are called
2948 // "orphans", and they are assigned to output sections by the default rule.
2949 // Process that.
2950 script->addOrphanSections();
2954 llvm::TimeTraceScope timeScope("Merge/finalize input sections");
2956 // Migrate InputSectionDescription::sectionBases to sections. This includes
2957 // merging MergeInputSections into a single MergeSyntheticSection. From this
2958 // point onwards InputSectionDescription::sections should be used instead of
2959 // sectionBases.
2960 for (SectionCommand *cmd : script->sectionCommands)
2961 if (auto *osd = dyn_cast<OutputDesc>(cmd))
2962 osd->osec.finalizeInputSections();
2965 // Two input sections with different output sections should not be folded.
2966 // ICF runs after processSectionCommands() so that we know the output sections.
2967 if (config->icf != ICFLevel::None) {
2968 invokeELFT(findKeepUniqueSections, args);
2969 invokeELFT(doIcf,);
2972 // Read the callgraph now that we know what was gced or icfed
2973 if (config->callGraphProfileSort) {
2974 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
2975 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
2976 readCallGraph(*buffer);
2977 invokeELFT(readCallGraphsFromObjectFiles,);
2980 // Write the result to the file.
2981 invokeELFT(writeResult,);