[mlir][py] Enable loading only specified dialects during creation. (#121421)
[llvm-project.git] / lld / ELF / Driver.cpp
blobf573a8d3e19f3bd945a95e085b63783e15eee5df
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/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSwitch.h"
53 #include "llvm/Config/llvm-config.h"
54 #include "llvm/LTO/LTO.h"
55 #include "llvm/Object/Archive.h"
56 #include "llvm/Object/IRObjectFile.h"
57 #include "llvm/Remarks/HotnessThresholdParser.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/SaveAndRestore.h"
60 #include "llvm/Support/Compression.h"
61 #include "llvm/Support/FileSystem.h"
62 #include "llvm/Support/GlobPattern.h"
63 #include "llvm/Support/LEB128.h"
64 #include "llvm/Support/Parallel.h"
65 #include "llvm/Support/Path.h"
66 #include "llvm/Support/TarWriter.h"
67 #include "llvm/Support/TargetSelect.h"
68 #include "llvm/Support/TimeProfiler.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include <cstdlib>
71 #include <tuple>
72 #include <utility>
74 using namespace llvm;
75 using namespace llvm::ELF;
76 using namespace llvm::object;
77 using namespace llvm::sys;
78 using namespace llvm::support;
79 using namespace lld;
80 using namespace lld::elf;
82 static void setConfigs(Ctx &ctx, opt::InputArgList &args);
83 static void readConfigs(Ctx &ctx, opt::InputArgList &args);
85 ELFSyncStream elf::Log(Ctx &ctx) { return {ctx, DiagLevel::Log}; }
86 ELFSyncStream elf::Msg(Ctx &ctx) { return {ctx, DiagLevel::Msg}; }
87 ELFSyncStream elf::Warn(Ctx &ctx) { return {ctx, DiagLevel::Warn}; }
88 ELFSyncStream elf::Err(Ctx &ctx) {
89 return {ctx, ctx.arg.noinhibitExec ? DiagLevel::Warn : DiagLevel::Err};
91 ELFSyncStream elf::ErrAlways(Ctx &ctx) { return {ctx, DiagLevel::Err}; }
92 ELFSyncStream elf::Fatal(Ctx &ctx) { return {ctx, DiagLevel::Fatal}; }
93 uint64_t elf::errCount(Ctx &ctx) { return ctx.e.errorCount; }
95 ELFSyncStream elf::InternalErr(Ctx &ctx, const uint8_t *buf) {
96 ELFSyncStream s(ctx, DiagLevel::Err);
97 s << "internal linker error: ";
98 return s;
101 Ctx::Ctx() : driver(*this) {}
103 llvm::raw_fd_ostream Ctx::openAuxiliaryFile(llvm::StringRef filename,
104 std::error_code &ec) {
105 using namespace llvm::sys::fs;
106 OpenFlags flags =
107 auxiliaryFiles.insert(filename).second ? OF_None : OF_Append;
108 return {filename, ec, flags};
111 namespace lld {
112 namespace elf {
113 bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
114 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
115 // This driver-specific context will be freed later by unsafeLldMain().
116 auto *context = new Ctx;
117 Ctx &ctx = *context;
119 context->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
120 context->e.logName = args::getFilenameWithoutExe(args[0]);
121 context->e.errorLimitExceededMsg =
122 "too many errors emitted, stopping now (use "
123 "--error-limit=0 to see all errors)";
125 LinkerScript script(ctx);
126 ctx.script = &script;
127 ctx.symAux.emplace_back();
128 ctx.symtab = std::make_unique<SymbolTable>(ctx);
130 ctx.partitions.clear();
131 ctx.partitions.emplace_back(ctx);
133 ctx.arg.progName = args[0];
135 ctx.driver.linkerMain(args);
137 return errCount(ctx) == 0;
139 } // namespace elf
140 } // namespace lld
142 // Parses a linker -m option.
143 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(Ctx &ctx,
144 StringRef emul) {
145 uint8_t osabi = 0;
146 StringRef s = emul;
147 if (s.ends_with("_fbsd")) {
148 s = s.drop_back(5);
149 osabi = ELFOSABI_FREEBSD;
152 std::pair<ELFKind, uint16_t> ret =
153 StringSwitch<std::pair<ELFKind, uint16_t>>(s)
154 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
155 .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})
156 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
157 .Cases("armelfb", "armelfb_linux_eabi", {ELF32BEKind, EM_ARM})
158 .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
159 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
160 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
161 .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
162 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
163 .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})
164 .Case("elf32loongarch", {ELF32LEKind, EM_LOONGARCH})
165 .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
166 .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
167 .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
168 .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
169 .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
170 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
171 .Case("elf_i386", {ELF32LEKind, EM_386})
172 .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
173 .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
174 .Case("msp430elf", {ELF32LEKind, EM_MSP430})
175 .Case("elf64_amdgpu", {ELF64LEKind, EM_AMDGPU})
176 .Case("elf64loongarch", {ELF64LEKind, EM_LOONGARCH})
177 .Case("elf64_s390", {ELF64BEKind, EM_S390})
178 .Case("hexagonelf", {ELF32LEKind, EM_HEXAGON})
179 .Default({ELFNoneKind, EM_NONE});
181 if (ret.first == ELFNoneKind)
182 ErrAlways(ctx) << "unknown emulation: " << emul;
183 if (ret.second == EM_MSP430)
184 osabi = ELFOSABI_STANDALONE;
185 else if (ret.second == EM_AMDGPU)
186 osabi = ELFOSABI_AMDGPU_HSA;
187 return std::make_tuple(ret.first, ret.second, osabi);
190 // Returns slices of MB by parsing MB as an archive file.
191 // Each slice consists of a member file in the archive.
192 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
193 Ctx &ctx, MemoryBufferRef mb) {
194 std::unique_ptr<Archive> file =
195 CHECK(Archive::create(mb),
196 mb.getBufferIdentifier() + ": failed to parse archive");
198 std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
199 Error err = Error::success();
200 bool addToTar = file->isThin() && ctx.tar;
201 for (const Archive::Child &c : file->children(err)) {
202 MemoryBufferRef mbref =
203 CHECK(c.getMemoryBufferRef(),
204 mb.getBufferIdentifier() +
205 ": could not get the buffer for a child of the archive");
206 if (addToTar)
207 ctx.tar->append(relativeToRoot(check(c.getFullName())),
208 mbref.getBuffer());
209 v.push_back(std::make_pair(mbref, c.getChildOffset()));
211 if (err)
212 Fatal(ctx) << mb.getBufferIdentifier()
213 << ": Archive::children failed: " << std::move(err);
215 // Take ownership of memory buffers created for members of thin archives.
216 std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers();
217 std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx.memoryBuffers));
219 return v;
222 static bool isBitcode(MemoryBufferRef mb) {
223 return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode;
226 bool LinkerDriver::tryAddFatLTOFile(MemoryBufferRef mb, StringRef archiveName,
227 uint64_t offsetInArchive, bool lazy) {
228 if (!ctx.arg.fatLTOObjects)
229 return false;
230 Expected<MemoryBufferRef> fatLTOData =
231 IRObjectFile::findBitcodeInMemBuffer(mb);
232 if (errorToBool(fatLTOData.takeError()))
233 return false;
234 files.push_back(std::make_unique<BitcodeFile>(ctx, *fatLTOData, archiveName,
235 offsetInArchive, lazy));
236 return true;
239 // Opens a file and create a file object. Path has to be resolved already.
240 void LinkerDriver::addFile(StringRef path, bool withLOption) {
241 using namespace sys::fs;
243 std::optional<MemoryBufferRef> buffer = readFile(ctx, path);
244 if (!buffer)
245 return;
246 MemoryBufferRef mbref = *buffer;
248 if (ctx.arg.formatBinary) {
249 files.push_back(std::make_unique<BinaryFile>(ctx, mbref));
250 return;
253 switch (identify_magic(mbref.getBuffer())) {
254 case file_magic::unknown:
255 readLinkerScript(ctx, mbref);
256 return;
257 case file_magic::archive: {
258 auto members = getArchiveMembers(ctx, mbref);
259 if (inWholeArchive) {
260 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {
261 if (isBitcode(p.first))
262 files.push_back(std::make_unique<BitcodeFile>(ctx, p.first, path,
263 p.second, false));
264 else if (!tryAddFatLTOFile(p.first, path, p.second, false))
265 files.push_back(createObjFile(ctx, 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 SaveAndRestore saved(isInGroup, true);
285 for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {
286 auto magic = identify_magic(p.first.getBuffer());
287 if (magic == file_magic::elf_relocatable) {
288 if (!tryAddFatLTOFile(p.first, path, p.second, true))
289 files.push_back(createObjFile(ctx, p.first, path, true));
290 } else if (magic == file_magic::bitcode)
291 files.push_back(
292 std::make_unique<BitcodeFile>(ctx, p.first, path, p.second, true));
293 else
294 Warn(ctx) << path << ": archive member '"
295 << p.first.getBufferIdentifier()
296 << "' is neither ET_REL nor LLVM bitcode";
298 if (!saved.get())
299 ++nextGroupId;
300 return;
302 case file_magic::elf_shared_object: {
303 if (ctx.arg.isStatic) {
304 ErrAlways(ctx) << "attempted static link of dynamic object " << path;
305 return;
308 // Shared objects are identified by soname. soname is (if specified)
309 // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
310 // the directory part is ignored. Note that path may be a temporary and
311 // cannot be stored into SharedFile::soName.
312 path = mbref.getBufferIdentifier();
313 auto f = std::make_unique<SharedFile>(
314 ctx, mbref, withLOption ? path::filename(path) : path);
315 f->init();
316 files.push_back(std::move(f));
317 return;
319 case file_magic::bitcode:
320 files.push_back(std::make_unique<BitcodeFile>(ctx, mbref, "", 0, inLib));
321 break;
322 case file_magic::elf_relocatable:
323 if (!tryAddFatLTOFile(mbref, "", 0, inLib))
324 files.push_back(createObjFile(ctx, mbref, "", inLib));
325 break;
326 default:
327 ErrAlways(ctx) << path << ": unknown file type";
331 // Add a given library by searching it from input search paths.
332 void LinkerDriver::addLibrary(StringRef name) {
333 if (std::optional<std::string> path = searchLibrary(ctx, name))
334 addFile(ctx.saver.save(*path), /*withLOption=*/true);
335 else
336 ctx.e.error("unable to find library -l" + name, ErrorTag::LibNotFound,
337 {name});
340 // This function is called on startup. We need this for LTO since
341 // LTO calls LLVM functions to compile bitcode files to native code.
342 // Technically this can be delayed until we read bitcode files, but
343 // we don't bother to do lazily because the initialization is fast.
344 static void initLLVM() {
345 InitializeAllTargets();
346 InitializeAllTargetMCs();
347 InitializeAllAsmPrinters();
348 InitializeAllAsmParsers();
351 // Some command line options or some combinations of them are not allowed.
352 // This function checks for such errors.
353 static void checkOptions(Ctx &ctx) {
354 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
355 // table which is a relatively new feature.
356 if (ctx.arg.emachine == EM_MIPS && ctx.arg.gnuHash)
357 ErrAlways(ctx)
358 << "the .gnu.hash section is not compatible with the MIPS target";
360 if (ctx.arg.emachine == EM_ARM) {
361 if (!ctx.arg.cmseImplib) {
362 if (!ctx.arg.cmseInputLib.empty())
363 ErrAlways(ctx) << "--in-implib may not be used without --cmse-implib";
364 if (!ctx.arg.cmseOutputLib.empty())
365 ErrAlways(ctx) << "--out-implib may not be used without --cmse-implib";
367 } else {
368 if (ctx.arg.cmseImplib)
369 ErrAlways(ctx) << "--cmse-implib is only supported on ARM targets";
370 if (!ctx.arg.cmseInputLib.empty())
371 ErrAlways(ctx) << "--in-implib is only supported on ARM targets";
372 if (!ctx.arg.cmseOutputLib.empty())
373 ErrAlways(ctx) << "--out-implib is only supported on ARM targets";
376 if (ctx.arg.fixCortexA53Errata843419 && ctx.arg.emachine != EM_AARCH64)
377 ErrAlways(ctx)
378 << "--fix-cortex-a53-843419 is only supported on AArch64 targets";
380 if (ctx.arg.fixCortexA8 && ctx.arg.emachine != EM_ARM)
381 ErrAlways(ctx) << "--fix-cortex-a8 is only supported on ARM targets";
383 if (ctx.arg.armBe8 && ctx.arg.emachine != EM_ARM)
384 ErrAlways(ctx) << "--be8 is only supported on ARM targets";
386 if (ctx.arg.fixCortexA8 && !ctx.arg.isLE)
387 ErrAlways(ctx) << "--fix-cortex-a8 is not supported on big endian targets";
389 if (ctx.arg.tocOptimize && ctx.arg.emachine != EM_PPC64)
390 ErrAlways(ctx) << "--toc-optimize is only supported on PowerPC64 targets";
392 if (ctx.arg.pcRelOptimize && ctx.arg.emachine != EM_PPC64)
393 ErrAlways(ctx) << "--pcrel-optimize is only supported on PowerPC64 targets";
395 if (ctx.arg.relaxGP && ctx.arg.emachine != EM_RISCV)
396 ErrAlways(ctx) << "--relax-gp is only supported on RISC-V targets";
398 if (ctx.arg.pie && ctx.arg.shared)
399 ErrAlways(ctx) << "-shared and -pie may not be used together";
401 if (!ctx.arg.shared && !ctx.arg.filterList.empty())
402 ErrAlways(ctx) << "-F may not be used without -shared";
404 if (!ctx.arg.shared && !ctx.arg.auxiliaryList.empty())
405 ErrAlways(ctx) << "-f may not be used without -shared";
407 if (ctx.arg.strip == StripPolicy::All && ctx.arg.emitRelocs)
408 ErrAlways(ctx) << "--strip-all and --emit-relocs may not be used together";
410 if (ctx.arg.zText && ctx.arg.zIfuncNoplt)
411 ErrAlways(ctx) << "-z text and -z ifunc-noplt may not be used together";
413 if (ctx.arg.relocatable) {
414 if (ctx.arg.shared)
415 ErrAlways(ctx) << "-r and -shared may not be used together";
416 if (ctx.arg.gdbIndex)
417 ErrAlways(ctx) << "-r and --gdb-index may not be used together";
418 if (ctx.arg.icf != ICFLevel::None)
419 ErrAlways(ctx) << "-r and --icf may not be used together";
420 if (ctx.arg.pie)
421 ErrAlways(ctx) << "-r and -pie may not be used together";
422 if (ctx.arg.exportDynamic)
423 ErrAlways(ctx) << "-r and --export-dynamic may not be used together";
424 if (ctx.arg.debugNames)
425 ErrAlways(ctx) << "-r and --debug-names may not be used together";
426 if (!ctx.arg.zSectionHeader)
427 ErrAlways(ctx) << "-r and -z nosectionheader may not be used together";
430 if (ctx.arg.executeOnly) {
431 if (ctx.arg.emachine != EM_AARCH64)
432 ErrAlways(ctx) << "--execute-only is only supported on AArch64 targets";
434 if (ctx.arg.singleRoRx && !ctx.script->hasSectionsCommand)
435 ErrAlways(ctx)
436 << "--execute-only and --no-rosegment cannot be used together";
439 if (ctx.arg.zRetpolineplt && ctx.arg.zForceIbt)
440 ErrAlways(ctx) << "-z force-ibt may not be used with -z retpolineplt";
442 if (ctx.arg.emachine != EM_AARCH64) {
443 if (ctx.arg.zPacPlt)
444 ErrAlways(ctx) << "-z pac-plt only supported on AArch64";
445 if (ctx.arg.zForceBti)
446 ErrAlways(ctx) << "-z force-bti only supported on AArch64";
447 if (ctx.arg.zBtiReport != "none")
448 ErrAlways(ctx) << "-z bti-report only supported on AArch64";
449 if (ctx.arg.zPauthReport != "none")
450 ErrAlways(ctx) << "-z pauth-report only supported on AArch64";
451 if (ctx.arg.zGcsReport != "none")
452 ErrAlways(ctx) << "-z gcs-report only supported on AArch64";
453 if (ctx.arg.zGcs != GcsPolicy::Implicit)
454 ErrAlways(ctx) << "-z gcs only supported on AArch64";
457 if (ctx.arg.emachine != EM_386 && ctx.arg.emachine != EM_X86_64 &&
458 ctx.arg.zCetReport != "none")
459 ErrAlways(ctx) << "-z cet-report only supported on X86 and X86_64";
462 static const char *getReproduceOption(opt::InputArgList &args) {
463 if (auto *arg = args.getLastArg(OPT_reproduce))
464 return arg->getValue();
465 return getenv("LLD_REPRODUCE");
468 static bool hasZOption(opt::InputArgList &args, StringRef key) {
469 bool ret = false;
470 for (auto *arg : args.filtered(OPT_z))
471 if (key == arg->getValue()) {
472 ret = true;
473 arg->claim();
475 return ret;
478 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
479 bool defaultValue) {
480 for (auto *arg : args.filtered(OPT_z)) {
481 StringRef v = arg->getValue();
482 if (k1 == v)
483 defaultValue = true;
484 else if (k2 == v)
485 defaultValue = false;
486 else
487 continue;
488 arg->claim();
490 return defaultValue;
493 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
494 auto ret = SeparateSegmentKind::None;
495 for (auto *arg : args.filtered(OPT_z)) {
496 StringRef v = arg->getValue();
497 if (v == "noseparate-code")
498 ret = SeparateSegmentKind::None;
499 else if (v == "separate-code")
500 ret = SeparateSegmentKind::Code;
501 else if (v == "separate-loadable-segments")
502 ret = SeparateSegmentKind::Loadable;
503 else
504 continue;
505 arg->claim();
507 return ret;
510 static GnuStackKind getZGnuStack(opt::InputArgList &args) {
511 auto ret = GnuStackKind::NoExec;
512 for (auto *arg : args.filtered(OPT_z)) {
513 StringRef v = arg->getValue();
514 if (v == "execstack")
515 ret = GnuStackKind::Exec;
516 else if (v == "noexecstack")
517 ret = GnuStackKind::NoExec;
518 else if (v == "nognustack")
519 ret = GnuStackKind::None;
520 else
521 continue;
522 arg->claim();
524 return ret;
527 static uint8_t getZStartStopVisibility(Ctx &ctx, opt::InputArgList &args) {
528 uint8_t ret = STV_PROTECTED;
529 for (auto *arg : args.filtered(OPT_z)) {
530 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
531 if (kv.first == "start-stop-visibility") {
532 arg->claim();
533 if (kv.second == "default")
534 ret = STV_DEFAULT;
535 else if (kv.second == "internal")
536 ret = STV_INTERNAL;
537 else if (kv.second == "hidden")
538 ret = STV_HIDDEN;
539 else if (kv.second == "protected")
540 ret = STV_PROTECTED;
541 else
542 ErrAlways(ctx) << "unknown -z start-stop-visibility= value: "
543 << StringRef(kv.second);
546 return ret;
549 static GcsPolicy getZGcs(Ctx &ctx, opt::InputArgList &args) {
550 GcsPolicy ret = GcsPolicy::Implicit;
551 for (auto *arg : args.filtered(OPT_z)) {
552 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
553 if (kv.first == "gcs") {
554 arg->claim();
555 if (kv.second == "implicit")
556 ret = GcsPolicy::Implicit;
557 else if (kv.second == "never")
558 ret = GcsPolicy::Never;
559 else if (kv.second == "always")
560 ret = GcsPolicy::Always;
561 else
562 ErrAlways(ctx) << "unknown -z gcs= value: " << kv.second;
565 return ret;
568 // Report a warning for an unknown -z option.
569 static void checkZOptions(Ctx &ctx, opt::InputArgList &args) {
570 // This function is called before getTarget(), when certain options are not
571 // initialized yet. Claim them here.
572 args::getZOptionValue(args, OPT_z, "max-page-size", 0);
573 args::getZOptionValue(args, OPT_z, "common-page-size", 0);
574 getZFlag(args, "rel", "rela", false);
575 for (auto *arg : args.filtered(OPT_z))
576 if (!arg->isClaimed())
577 Warn(ctx) << "unknown -z value: " << StringRef(arg->getValue());
580 constexpr const char *saveTempsValues[] = {
581 "resolution", "preopt", "promote", "internalize", "import",
582 "opt", "precodegen", "prelink", "combinedindex"};
584 LinkerDriver::LinkerDriver(Ctx &ctx) : ctx(ctx) {}
586 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
587 ELFOptTable parser;
588 opt::InputArgList args = parser.parse(ctx, argsArr.slice(1));
590 // Interpret these flags early because Err/Warn depend on them.
591 ctx.e.errorLimit = args::getInteger(args, OPT_error_limit, 20);
592 ctx.e.fatalWarnings =
593 args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false) &&
594 !args.hasArg(OPT_no_warnings);
595 ctx.e.suppressWarnings = args.hasArg(OPT_no_warnings);
597 // Handle -help
598 if (args.hasArg(OPT_help)) {
599 printHelp(ctx);
600 return;
603 // Handle -v or -version.
605 // A note about "compatible with GNU linkers" message: this is a hack for
606 // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
607 // a GNU compatible linker. See
608 // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
610 // This is somewhat ugly hack, but in reality, we had no choice other
611 // than doing this. Considering the very long release cycle of Libtool,
612 // it is not easy to improve it to recognize LLD as a GNU compatible
613 // linker in a timely manner. Even if we can make it, there are still a
614 // lot of "configure" scripts out there that are generated by old version
615 // of Libtool. We cannot convince every software developer to migrate to
616 // the latest version and re-generate scripts. So we have this hack.
617 if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
618 Msg(ctx) << getLLDVersion() << " (compatible with GNU linkers)";
620 if (const char *path = getReproduceOption(args)) {
621 // Note that --reproduce is a debug option so you can ignore it
622 // if you are trying to understand the whole picture of the code.
623 Expected<std::unique_ptr<TarWriter>> errOrWriter =
624 TarWriter::create(path, path::stem(path));
625 if (errOrWriter) {
626 ctx.tar = std::move(*errOrWriter);
627 ctx.tar->append("response.txt", createResponseFile(args));
628 ctx.tar->append("version.txt", getLLDVersion() + "\n");
629 StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
630 if (!ltoSampleProfile.empty())
631 readFile(ctx, ltoSampleProfile);
632 } else {
633 ErrAlways(ctx) << "--reproduce: " << errOrWriter.takeError();
637 readConfigs(ctx, args);
638 checkZOptions(ctx, args);
640 // The behavior of -v or --version is a bit strange, but this is
641 // needed for compatibility with GNU linkers.
642 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
643 return;
644 if (args.hasArg(OPT_version))
645 return;
647 // Initialize time trace profiler.
648 if (ctx.arg.timeTraceEnabled)
649 timeTraceProfilerInitialize(ctx.arg.timeTraceGranularity, ctx.arg.progName);
652 llvm::TimeTraceScope timeScope("ExecuteLinker");
654 initLLVM();
655 createFiles(args);
656 if (errCount(ctx))
657 return;
659 inferMachineType();
660 setConfigs(ctx, args);
661 checkOptions(ctx);
662 if (errCount(ctx))
663 return;
665 invokeELFT(link, args);
668 if (ctx.arg.timeTraceEnabled) {
669 checkError(ctx.e, timeTraceProfilerWrite(
670 args.getLastArgValue(OPT_time_trace_eq).str(),
671 ctx.arg.outputFile));
672 timeTraceProfilerCleanup();
676 static std::string getRpath(opt::InputArgList &args) {
677 SmallVector<StringRef, 0> v = args::getStrings(args, OPT_rpath);
678 return llvm::join(v.begin(), v.end(), ":");
681 // Determines what we should do if there are remaining unresolved
682 // symbols after the name resolution.
683 static void setUnresolvedSymbolPolicy(Ctx &ctx, opt::InputArgList &args) {
684 UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
685 OPT_warn_unresolved_symbols, true)
686 ? UnresolvedPolicy::ReportError
687 : UnresolvedPolicy::Warn;
688 // -shared implies --unresolved-symbols=ignore-all because missing
689 // symbols are likely to be resolved at runtime.
690 bool diagRegular = !ctx.arg.shared, diagShlib = !ctx.arg.shared;
692 for (const opt::Arg *arg : args) {
693 switch (arg->getOption().getID()) {
694 case OPT_unresolved_symbols: {
695 StringRef s = arg->getValue();
696 if (s == "ignore-all") {
697 diagRegular = false;
698 diagShlib = false;
699 } else if (s == "ignore-in-object-files") {
700 diagRegular = false;
701 diagShlib = true;
702 } else if (s == "ignore-in-shared-libs") {
703 diagRegular = true;
704 diagShlib = false;
705 } else if (s == "report-all") {
706 diagRegular = true;
707 diagShlib = true;
708 } else {
709 ErrAlways(ctx) << "unknown --unresolved-symbols value: " << s;
711 break;
713 case OPT_no_undefined:
714 diagRegular = true;
715 break;
716 case OPT_z:
717 if (StringRef(arg->getValue()) == "defs")
718 diagRegular = true;
719 else if (StringRef(arg->getValue()) == "undefs")
720 diagRegular = false;
721 else
722 break;
723 arg->claim();
724 break;
725 case OPT_allow_shlib_undefined:
726 diagShlib = false;
727 break;
728 case OPT_no_allow_shlib_undefined:
729 diagShlib = true;
730 break;
734 ctx.arg.unresolvedSymbols =
735 diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;
736 ctx.arg.unresolvedSymbolsInShlib =
737 diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;
740 static Target2Policy getTarget2(Ctx &ctx, opt::InputArgList &args) {
741 StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
742 if (s == "rel")
743 return Target2Policy::Rel;
744 if (s == "abs")
745 return Target2Policy::Abs;
746 if (s == "got-rel")
747 return Target2Policy::GotRel;
748 ErrAlways(ctx) << "unknown --target2 option: " << s;
749 return Target2Policy::GotRel;
752 static bool isOutputFormatBinary(Ctx &ctx, opt::InputArgList &args) {
753 StringRef s = args.getLastArgValue(OPT_oformat, "elf");
754 if (s == "binary")
755 return true;
756 if (!s.starts_with("elf"))
757 ErrAlways(ctx) << "unknown --oformat value: " << s;
758 return false;
761 static DiscardPolicy getDiscard(opt::InputArgList &args) {
762 auto *arg =
763 args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
764 if (!arg)
765 return DiscardPolicy::Default;
766 if (arg->getOption().getID() == OPT_discard_all)
767 return DiscardPolicy::All;
768 if (arg->getOption().getID() == OPT_discard_locals)
769 return DiscardPolicy::Locals;
770 return DiscardPolicy::None;
773 static StringRef getDynamicLinker(Ctx &ctx, opt::InputArgList &args) {
774 auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
775 if (!arg)
776 return "";
777 if (arg->getOption().getID() == OPT_no_dynamic_linker) {
778 // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
779 ctx.arg.noDynamicLinker = true;
780 return "";
782 return arg->getValue();
785 static int getMemtagMode(Ctx &ctx, opt::InputArgList &args) {
786 StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode);
787 if (memtagModeArg.empty()) {
788 if (ctx.arg.androidMemtagStack)
789 Warn(ctx) << "--android-memtag-mode is unspecified, leaving "
790 "--android-memtag-stack a no-op";
791 else if (ctx.arg.androidMemtagHeap)
792 Warn(ctx) << "--android-memtag-mode is unspecified, leaving "
793 "--android-memtag-heap a no-op";
794 return ELF::NT_MEMTAG_LEVEL_NONE;
797 if (memtagModeArg == "sync")
798 return ELF::NT_MEMTAG_LEVEL_SYNC;
799 if (memtagModeArg == "async")
800 return ELF::NT_MEMTAG_LEVEL_ASYNC;
801 if (memtagModeArg == "none")
802 return ELF::NT_MEMTAG_LEVEL_NONE;
804 ErrAlways(ctx) << "unknown --android-memtag-mode value: \"" << memtagModeArg
805 << "\", should be one of {async, sync, none}";
806 return ELF::NT_MEMTAG_LEVEL_NONE;
809 static ICFLevel getICF(opt::InputArgList &args) {
810 auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
811 if (!arg || arg->getOption().getID() == OPT_icf_none)
812 return ICFLevel::None;
813 if (arg->getOption().getID() == OPT_icf_safe)
814 return ICFLevel::Safe;
815 return ICFLevel::All;
818 static StripPolicy getStrip(Ctx &ctx, opt::InputArgList &args) {
819 if (args.hasArg(OPT_relocatable))
820 return StripPolicy::None;
821 if (!ctx.arg.zSectionHeader)
822 return StripPolicy::All;
824 auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
825 if (!arg)
826 return StripPolicy::None;
827 if (arg->getOption().getID() == OPT_strip_all)
828 return StripPolicy::All;
829 return StripPolicy::Debug;
832 static uint64_t parseSectionAddress(Ctx &ctx, StringRef s,
833 opt::InputArgList &args,
834 const opt::Arg &arg) {
835 uint64_t va = 0;
836 s.consume_front("0x");
837 if (!to_integer(s, va, 16))
838 ErrAlways(ctx) << "invalid argument: " << arg.getAsString(args);
839 return va;
842 static StringMap<uint64_t> getSectionStartMap(Ctx &ctx,
843 opt::InputArgList &args) {
844 StringMap<uint64_t> ret;
845 for (auto *arg : args.filtered(OPT_section_start)) {
846 StringRef name;
847 StringRef addr;
848 std::tie(name, addr) = StringRef(arg->getValue()).split('=');
849 ret[name] = parseSectionAddress(ctx, addr, args, *arg);
852 if (auto *arg = args.getLastArg(OPT_Ttext))
853 ret[".text"] = parseSectionAddress(ctx, arg->getValue(), args, *arg);
854 if (auto *arg = args.getLastArg(OPT_Tdata))
855 ret[".data"] = parseSectionAddress(ctx, arg->getValue(), args, *arg);
856 if (auto *arg = args.getLastArg(OPT_Tbss))
857 ret[".bss"] = parseSectionAddress(ctx, arg->getValue(), args, *arg);
858 return ret;
861 static SortSectionPolicy getSortSection(Ctx &ctx, opt::InputArgList &args) {
862 StringRef s = args.getLastArgValue(OPT_sort_section);
863 if (s == "alignment")
864 return SortSectionPolicy::Alignment;
865 if (s == "name")
866 return SortSectionPolicy::Name;
867 if (!s.empty())
868 ErrAlways(ctx) << "unknown --sort-section rule: " << s;
869 return SortSectionPolicy::Default;
872 static OrphanHandlingPolicy getOrphanHandling(Ctx &ctx,
873 opt::InputArgList &args) {
874 StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
875 if (s == "warn")
876 return OrphanHandlingPolicy::Warn;
877 if (s == "error")
878 return OrphanHandlingPolicy::Error;
879 if (s != "place")
880 ErrAlways(ctx) << "unknown --orphan-handling mode: " << s;
881 return OrphanHandlingPolicy::Place;
884 // Parse --build-id or --build-id=<style>. We handle "tree" as a
885 // synonym for "sha1" because all our hash functions including
886 // --build-id=sha1 are actually tree hashes for performance reasons.
887 static std::pair<BuildIdKind, SmallVector<uint8_t, 0>>
888 getBuildId(Ctx &ctx, opt::InputArgList &args) {
889 auto *arg = args.getLastArg(OPT_build_id);
890 if (!arg)
891 return {BuildIdKind::None, {}};
893 StringRef s = arg->getValue();
894 if (s == "fast")
895 return {BuildIdKind::Fast, {}};
896 if (s == "md5")
897 return {BuildIdKind::Md5, {}};
898 if (s == "sha1" || s == "tree")
899 return {BuildIdKind::Sha1, {}};
900 if (s == "uuid")
901 return {BuildIdKind::Uuid, {}};
902 if (s.starts_with("0x"))
903 return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
905 if (s != "none")
906 ErrAlways(ctx) << "unknown --build-id style: " << s;
907 return {BuildIdKind::None, {}};
910 static std::pair<bool, bool> getPackDynRelocs(Ctx &ctx,
911 opt::InputArgList &args) {
912 StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
913 if (s == "android")
914 return {true, false};
915 if (s == "relr")
916 return {false, true};
917 if (s == "android+relr")
918 return {true, true};
920 if (s != "none")
921 ErrAlways(ctx) << "unknown --pack-dyn-relocs format: " << s;
922 return {false, false};
925 static void readCallGraph(Ctx &ctx, MemoryBufferRef mb) {
926 // Build a map from symbol name to section
927 DenseMap<StringRef, Symbol *> map;
928 for (ELFFileBase *file : ctx.objectFiles)
929 for (Symbol *sym : file->getSymbols())
930 map[sym->getName()] = sym;
932 auto findSection = [&](StringRef name) -> InputSectionBase * {
933 Symbol *sym = map.lookup(name);
934 if (!sym) {
935 if (ctx.arg.warnSymbolOrdering)
936 Warn(ctx) << mb.getBufferIdentifier() << ": no such symbol: " << name;
937 return nullptr;
939 maybeWarnUnorderableSymbol(ctx, sym);
941 if (Defined *dr = dyn_cast_or_null<Defined>(sym))
942 return dyn_cast_or_null<InputSectionBase>(dr->section);
943 return nullptr;
946 for (StringRef line : args::getLines(mb)) {
947 SmallVector<StringRef, 3> fields;
948 line.split(fields, ' ');
949 uint64_t count;
951 if (fields.size() != 3 || !to_integer(fields[2], count)) {
952 ErrAlways(ctx) << mb.getBufferIdentifier() << ": parse error";
953 return;
956 if (InputSectionBase *from = findSection(fields[0]))
957 if (InputSectionBase *to = findSection(fields[1]))
958 ctx.arg.callGraphProfile[std::make_pair(from, to)] += count;
962 // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
963 // true and populates cgProfile and symbolIndices.
964 template <class ELFT>
965 static bool
966 processCallGraphRelocations(Ctx &ctx, SmallVector<uint32_t, 32> &symbolIndices,
967 ArrayRef<typename ELFT::CGProfile> &cgProfile,
968 ObjFile<ELFT> *inputObj) {
969 if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
970 return false;
972 ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
973 inputObj->template getELFShdrs<ELFT>();
974 symbolIndices.clear();
975 const ELFFile<ELFT> &obj = inputObj->getObj();
976 cgProfile =
977 check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(
978 objSections[inputObj->cgProfileSectionIndex]));
980 for (size_t i = 0, e = objSections.size(); i < e; ++i) {
981 const Elf_Shdr_Impl<ELFT> &sec = objSections[i];
982 if (sec.sh_info == inputObj->cgProfileSectionIndex) {
983 if (sec.sh_type == SHT_CREL) {
984 auto crels =
985 CHECK(obj.crels(sec), "could not retrieve cg profile rela section");
986 for (const auto &rel : crels.first)
987 symbolIndices.push_back(rel.getSymbol(false));
988 for (const auto &rel : crels.second)
989 symbolIndices.push_back(rel.getSymbol(false));
990 break;
992 if (sec.sh_type == SHT_RELA) {
993 ArrayRef<typename ELFT::Rela> relas =
994 CHECK(obj.relas(sec), "could not retrieve cg profile rela section");
995 for (const typename ELFT::Rela &rel : relas)
996 symbolIndices.push_back(rel.getSymbol(ctx.arg.isMips64EL));
997 break;
999 if (sec.sh_type == SHT_REL) {
1000 ArrayRef<typename ELFT::Rel> rels =
1001 CHECK(obj.rels(sec), "could not retrieve cg profile rel section");
1002 for (const typename ELFT::Rel &rel : rels)
1003 symbolIndices.push_back(rel.getSymbol(ctx.arg.isMips64EL));
1004 break;
1008 if (symbolIndices.empty())
1009 Warn(ctx)
1010 << "SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't";
1011 return !symbolIndices.empty();
1014 template <class ELFT> static void readCallGraphsFromObjectFiles(Ctx &ctx) {
1015 SmallVector<uint32_t, 32> symbolIndices;
1016 ArrayRef<typename ELFT::CGProfile> cgProfile;
1017 for (auto file : ctx.objectFiles) {
1018 auto *obj = cast<ObjFile<ELFT>>(file);
1019 if (!processCallGraphRelocations(ctx, symbolIndices, cgProfile, obj))
1020 continue;
1022 if (symbolIndices.size() != cgProfile.size() * 2)
1023 Fatal(ctx) << "number of relocations doesn't match Weights";
1025 for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {
1026 const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];
1027 uint32_t fromIndex = symbolIndices[i * 2];
1028 uint32_t toIndex = symbolIndices[i * 2 + 1];
1029 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
1030 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
1031 if (!fromSym || !toSym)
1032 continue;
1034 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
1035 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
1036 if (from && to)
1037 ctx.arg.callGraphProfile[{from, to}] += cgpe.cgp_weight;
1042 template <class ELFT>
1043 static void ltoValidateAllVtablesHaveTypeInfos(Ctx &ctx,
1044 opt::InputArgList &args) {
1045 DenseSet<StringRef> typeInfoSymbols;
1046 SmallSetVector<StringRef, 0> vtableSymbols;
1047 auto processVtableAndTypeInfoSymbols = [&](StringRef name) {
1048 if (name.consume_front("_ZTI"))
1049 typeInfoSymbols.insert(name);
1050 else if (name.consume_front("_ZTV"))
1051 vtableSymbols.insert(name);
1054 // Examine all native symbol tables.
1055 for (ELFFileBase *f : ctx.objectFiles) {
1056 using Elf_Sym = typename ELFT::Sym;
1057 for (const Elf_Sym &s : f->template getGlobalELFSyms<ELFT>()) {
1058 if (s.st_shndx != SHN_UNDEF) {
1059 StringRef name = check(s.getName(f->getStringTable()));
1060 processVtableAndTypeInfoSymbols(name);
1065 for (SharedFile *f : ctx.sharedFiles) {
1066 using Elf_Sym = typename ELFT::Sym;
1067 for (const Elf_Sym &s : f->template getELFSyms<ELFT>()) {
1068 if (s.st_shndx != SHN_UNDEF) {
1069 StringRef name = check(s.getName(f->getStringTable()));
1070 processVtableAndTypeInfoSymbols(name);
1075 SmallSetVector<StringRef, 0> vtableSymbolsWithNoRTTI;
1076 for (StringRef s : vtableSymbols)
1077 if (!typeInfoSymbols.count(s))
1078 vtableSymbolsWithNoRTTI.insert(s);
1080 // Remove known safe symbols.
1081 for (auto *arg : args.filtered(OPT_lto_known_safe_vtables)) {
1082 StringRef knownSafeName = arg->getValue();
1083 if (!knownSafeName.consume_front("_ZTV"))
1084 ErrAlways(ctx)
1085 << "--lto-known-safe-vtables=: expected symbol to start with _ZTV, "
1086 "but got "
1087 << knownSafeName;
1088 Expected<GlobPattern> pat = GlobPattern::create(knownSafeName);
1089 if (!pat)
1090 ErrAlways(ctx) << "--lto-known-safe-vtables=: " << pat.takeError();
1091 vtableSymbolsWithNoRTTI.remove_if(
1092 [&](StringRef s) { return pat->match(s); });
1095 ctx.ltoAllVtablesHaveTypeInfos = vtableSymbolsWithNoRTTI.empty();
1096 // Check for unmatched RTTI symbols
1097 for (StringRef s : vtableSymbolsWithNoRTTI) {
1098 Msg(ctx) << "--lto-validate-all-vtables-have-type-infos: RTTI missing for "
1099 "vtable "
1100 "_ZTV"
1101 << s << ", --lto-whole-program-visibility disabled";
1105 static CGProfileSortKind getCGProfileSortKind(Ctx &ctx,
1106 opt::InputArgList &args) {
1107 StringRef s = args.getLastArgValue(OPT_call_graph_profile_sort, "cdsort");
1108 if (s == "hfsort")
1109 return CGProfileSortKind::Hfsort;
1110 if (s == "cdsort")
1111 return CGProfileSortKind::Cdsort;
1112 if (s != "none")
1113 ErrAlways(ctx) << "unknown --call-graph-profile-sort= value: " << s;
1114 return CGProfileSortKind::None;
1117 static DebugCompressionType getCompressionType(Ctx &ctx, StringRef s,
1118 StringRef option) {
1119 DebugCompressionType type = StringSwitch<DebugCompressionType>(s)
1120 .Case("zlib", DebugCompressionType::Zlib)
1121 .Case("zstd", DebugCompressionType::Zstd)
1122 .Default(DebugCompressionType::None);
1123 if (type == DebugCompressionType::None) {
1124 if (s != "none")
1125 ErrAlways(ctx) << "unknown " << option << " value: " << s;
1126 } else if (const char *reason = compression::getReasonIfUnsupported(
1127 compression::formatFor(type))) {
1128 ErrAlways(ctx) << option << ": " << reason;
1130 return type;
1133 static StringRef getAliasSpelling(opt::Arg *arg) {
1134 if (const opt::Arg *alias = arg->getAlias())
1135 return alias->getSpelling();
1136 return arg->getSpelling();
1139 static std::pair<StringRef, StringRef>
1140 getOldNewOptions(Ctx &ctx, opt::InputArgList &args, unsigned id) {
1141 auto *arg = args.getLastArg(id);
1142 if (!arg)
1143 return {"", ""};
1145 StringRef s = arg->getValue();
1146 std::pair<StringRef, StringRef> ret = s.split(';');
1147 if (ret.second.empty())
1148 ErrAlways(ctx) << getAliasSpelling(arg)
1149 << " expects 'old;new' format, but got " << s;
1150 return ret;
1153 // Parse options of the form "old;new[;extra]".
1154 static std::tuple<StringRef, StringRef, StringRef>
1155 getOldNewOptionsExtra(Ctx &ctx, opt::InputArgList &args, unsigned id) {
1156 auto [oldDir, second] = getOldNewOptions(ctx, args, id);
1157 auto [newDir, extraDir] = second.split(';');
1158 return {oldDir, newDir, extraDir};
1161 // Parse the symbol ordering file and warn for any duplicate entries.
1162 static SmallVector<StringRef, 0> getSymbolOrderingFile(Ctx &ctx,
1163 MemoryBufferRef mb) {
1164 SetVector<StringRef, SmallVector<StringRef, 0>> names;
1165 for (StringRef s : args::getLines(mb))
1166 if (!names.insert(s) && ctx.arg.warnSymbolOrdering)
1167 Warn(ctx) << mb.getBufferIdentifier()
1168 << ": duplicate ordered symbol: " << s;
1170 return names.takeVector();
1173 static bool getIsRela(Ctx &ctx, opt::InputArgList &args) {
1174 // The psABI specifies the default relocation entry format.
1175 bool rela = is_contained({EM_AARCH64, EM_AMDGPU, EM_HEXAGON, EM_LOONGARCH,
1176 EM_PPC, EM_PPC64, EM_RISCV, EM_S390, EM_X86_64},
1177 ctx.arg.emachine);
1178 // If -z rel or -z rela is specified, use the last option.
1179 for (auto *arg : args.filtered(OPT_z)) {
1180 StringRef s(arg->getValue());
1181 if (s == "rel")
1182 rela = false;
1183 else if (s == "rela")
1184 rela = true;
1185 else
1186 continue;
1187 arg->claim();
1189 return rela;
1192 static void parseClangOption(Ctx &ctx, StringRef opt, const Twine &msg) {
1193 std::string err;
1194 raw_string_ostream os(err);
1196 const char *argv[] = {ctx.arg.progName.data(), opt.data()};
1197 if (cl::ParseCommandLineOptions(2, argv, "", &os))
1198 return;
1199 ErrAlways(ctx) << msg << ": " << StringRef(err).trim();
1202 // Checks the parameter of the bti-report and cet-report options.
1203 static bool isValidReportString(StringRef arg) {
1204 return arg == "none" || arg == "warning" || arg == "error";
1207 // Process a remap pattern 'from-glob=to-file'.
1208 static bool remapInputs(Ctx &ctx, StringRef line, const Twine &location) {
1209 SmallVector<StringRef, 0> fields;
1210 line.split(fields, '=');
1211 if (fields.size() != 2 || fields[1].empty()) {
1212 ErrAlways(ctx) << location << ": parse error, not 'from-glob=to-file'";
1213 return true;
1215 if (!hasWildcard(fields[0]))
1216 ctx.arg.remapInputs[fields[0]] = fields[1];
1217 else if (Expected<GlobPattern> pat = GlobPattern::create(fields[0]))
1218 ctx.arg.remapInputsWildcards.emplace_back(std::move(*pat), fields[1]);
1219 else {
1220 ErrAlways(ctx) << location << ": " << pat.takeError() << ": " << fields[0];
1221 return true;
1223 return false;
1226 // Initializes Config members by the command line options.
1227 static void readConfigs(Ctx &ctx, opt::InputArgList &args) {
1228 ctx.e.verbose = args.hasArg(OPT_verbose);
1229 ctx.e.vsDiagnostics =
1230 args.hasArg(OPT_visual_studio_diagnostics_format, false);
1232 ctx.arg.allowMultipleDefinition =
1233 hasZOption(args, "muldefs") ||
1234 args.hasFlag(OPT_allow_multiple_definition,
1235 OPT_no_allow_multiple_definition, false);
1236 ctx.arg.androidMemtagHeap =
1237 args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false);
1238 ctx.arg.androidMemtagStack = args.hasFlag(OPT_android_memtag_stack,
1239 OPT_no_android_memtag_stack, false);
1240 ctx.arg.fatLTOObjects =
1241 args.hasFlag(OPT_fat_lto_objects, OPT_no_fat_lto_objects, false);
1242 ctx.arg.androidMemtagMode = getMemtagMode(ctx, args);
1243 ctx.arg.auxiliaryList = args::getStrings(args, OPT_auxiliary);
1244 ctx.arg.armBe8 = args.hasArg(OPT_be8);
1245 if (opt::Arg *arg = args.getLastArg(
1246 OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,
1247 OPT_Bsymbolic_functions, OPT_Bsymbolic_non_weak, OPT_Bsymbolic)) {
1248 if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
1249 ctx.arg.bsymbolic = BsymbolicKind::NonWeakFunctions;
1250 else if (arg->getOption().matches(OPT_Bsymbolic_functions))
1251 ctx.arg.bsymbolic = BsymbolicKind::Functions;
1252 else if (arg->getOption().matches(OPT_Bsymbolic_non_weak))
1253 ctx.arg.bsymbolic = BsymbolicKind::NonWeak;
1254 else if (arg->getOption().matches(OPT_Bsymbolic))
1255 ctx.arg.bsymbolic = BsymbolicKind::All;
1257 ctx.arg.callGraphProfileSort = getCGProfileSortKind(ctx, args);
1258 ctx.arg.checkSections =
1259 args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
1260 ctx.arg.chroot = args.getLastArgValue(OPT_chroot);
1261 if (auto *arg = args.getLastArg(OPT_compress_debug_sections)) {
1262 ctx.arg.compressDebugSections =
1263 getCompressionType(ctx, arg->getValue(), "--compress-debug-sections");
1265 ctx.arg.cref = args.hasArg(OPT_cref);
1266 ctx.arg.optimizeBBJumps =
1267 args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
1268 ctx.arg.debugNames = args.hasFlag(OPT_debug_names, OPT_no_debug_names, false);
1269 ctx.arg.demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
1270 ctx.arg.dependencyFile = args.getLastArgValue(OPT_dependency_file);
1271 ctx.arg.dependentLibraries =
1272 args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
1273 ctx.arg.disableVerify = args.hasArg(OPT_disable_verify);
1274 ctx.arg.discard = getDiscard(args);
1275 ctx.arg.dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
1276 ctx.arg.dynamicLinker = getDynamicLinker(ctx, args);
1277 ctx.arg.ehFrameHdr =
1278 args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
1279 ctx.arg.emitLLVM = args.hasArg(OPT_lto_emit_llvm);
1280 ctx.arg.emitRelocs = args.hasArg(OPT_emit_relocs);
1281 ctx.arg.enableNewDtags =
1282 args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
1283 ctx.arg.enableNonContiguousRegions =
1284 args.hasArg(OPT_enable_non_contiguous_regions);
1285 ctx.arg.entry = args.getLastArgValue(OPT_entry);
1287 ctx.e.errorHandlingScript = args.getLastArgValue(OPT_error_handling_script);
1289 ctx.arg.executeOnly =
1290 args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
1291 ctx.arg.exportDynamic =
1292 args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) ||
1293 args.hasArg(OPT_shared);
1294 ctx.arg.filterList = args::getStrings(args, OPT_filter);
1295 ctx.arg.fini = args.getLastArgValue(OPT_fini, "_fini");
1296 ctx.arg.fixCortexA53Errata843419 =
1297 args.hasArg(OPT_fix_cortex_a53_843419) && !args.hasArg(OPT_relocatable);
1298 ctx.arg.cmseImplib = args.hasArg(OPT_cmse_implib);
1299 ctx.arg.cmseInputLib = args.getLastArgValue(OPT_in_implib);
1300 ctx.arg.cmseOutputLib = args.getLastArgValue(OPT_out_implib);
1301 ctx.arg.fixCortexA8 =
1302 args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
1303 ctx.arg.fortranCommon =
1304 args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false);
1305 ctx.arg.gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
1306 ctx.arg.gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
1307 ctx.arg.gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
1308 ctx.arg.icf = getICF(args);
1309 ctx.arg.ignoreDataAddressEquality =
1310 args.hasArg(OPT_ignore_data_address_equality);
1311 ctx.arg.ignoreFunctionAddressEquality =
1312 args.hasArg(OPT_ignore_function_address_equality);
1313 ctx.arg.init = args.getLastArgValue(OPT_init, "_init");
1314 ctx.arg.ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
1315 ctx.arg.ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1316 ctx.arg.ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1317 ctx.arg.ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1318 OPT_no_lto_pgo_warn_mismatch, true);
1319 ctx.arg.ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
1320 ctx.arg.ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
1321 ctx.arg.ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
1322 ctx.arg.ltoWholeProgramVisibility =
1323 args.hasFlag(OPT_lto_whole_program_visibility,
1324 OPT_no_lto_whole_program_visibility, false);
1325 ctx.arg.ltoValidateAllVtablesHaveTypeInfos =
1326 args.hasFlag(OPT_lto_validate_all_vtables_have_type_infos,
1327 OPT_no_lto_validate_all_vtables_have_type_infos, false);
1328 ctx.arg.ltoo = args::getInteger(args, OPT_lto_O, 2);
1329 if (ctx.arg.ltoo > 3)
1330 ErrAlways(ctx) << "invalid optimization level for LTO: " << ctx.arg.ltoo;
1331 unsigned ltoCgo =
1332 args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(ctx.arg.ltoo));
1333 if (auto level = CodeGenOpt::getLevel(ltoCgo))
1334 ctx.arg.ltoCgo = *level;
1335 else
1336 ErrAlways(ctx) << "invalid codegen optimization level for LTO: " << ltoCgo;
1337 ctx.arg.ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
1338 ctx.arg.ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
1339 ctx.arg.ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
1340 ctx.arg.ltoBBAddrMap =
1341 args.hasFlag(OPT_lto_basic_block_address_map,
1342 OPT_no_lto_basic_block_address_map, false);
1343 ctx.arg.ltoBasicBlockSections =
1344 args.getLastArgValue(OPT_lto_basic_block_sections);
1345 ctx.arg.ltoUniqueBasicBlockSectionNames =
1346 args.hasFlag(OPT_lto_unique_basic_block_section_names,
1347 OPT_no_lto_unique_basic_block_section_names, false);
1348 ctx.arg.mapFile = args.getLastArgValue(OPT_Map);
1349 ctx.arg.mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
1350 ctx.arg.mergeArmExidx =
1351 args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
1352 ctx.arg.mmapOutputFile =
1353 args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
1354 ctx.arg.nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
1355 ctx.arg.noinhibitExec = args.hasArg(OPT_noinhibit_exec);
1356 ctx.arg.nostdlib = args.hasArg(OPT_nostdlib);
1357 ctx.arg.oFormatBinary = isOutputFormatBinary(ctx, args);
1358 ctx.arg.omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
1359 ctx.arg.optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
1360 ctx.arg.optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file);
1362 // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1363 if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {
1364 auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());
1365 if (!resultOrErr)
1366 ErrAlways(ctx) << arg->getSpelling() << ": invalid argument '"
1367 << arg->getValue()
1368 << "', only integer or 'auto' is supported";
1369 else
1370 ctx.arg.optRemarksHotnessThreshold = *resultOrErr;
1373 ctx.arg.optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
1374 ctx.arg.optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
1375 ctx.arg.optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
1376 ctx.arg.optimize = args::getInteger(args, OPT_O, 1);
1377 ctx.arg.orphanHandling = getOrphanHandling(ctx, args);
1378 ctx.arg.outputFile = args.getLastArgValue(OPT_o);
1379 ctx.arg.packageMetadata = args.getLastArgValue(OPT_package_metadata);
1380 ctx.arg.pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
1381 ctx.arg.printIcfSections =
1382 args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
1383 ctx.arg.printGcSections =
1384 args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
1385 ctx.arg.printMemoryUsage = args.hasArg(OPT_print_memory_usage);
1386 ctx.arg.printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
1387 ctx.arg.printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order);
1388 ctx.arg.rejectMismatch = !args.hasArg(OPT_no_warn_mismatch);
1389 ctx.arg.relax = args.hasFlag(OPT_relax, OPT_no_relax, true);
1390 ctx.arg.relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false);
1391 ctx.arg.rpath = getRpath(args);
1392 ctx.arg.relocatable = args.hasArg(OPT_relocatable);
1393 ctx.arg.resolveGroups =
1394 !args.hasArg(OPT_relocatable) || args.hasArg(OPT_force_group_allocation);
1396 if (args.hasArg(OPT_save_temps)) {
1397 // --save-temps implies saving all temps.
1398 for (const char *s : saveTempsValues)
1399 ctx.arg.saveTempsArgs.insert(s);
1400 } else {
1401 for (auto *arg : args.filtered(OPT_save_temps_eq)) {
1402 StringRef s = arg->getValue();
1403 if (llvm::is_contained(saveTempsValues, s))
1404 ctx.arg.saveTempsArgs.insert(s);
1405 else
1406 ErrAlways(ctx) << "unknown --save-temps value: " << s;
1410 ctx.arg.searchPaths = args::getStrings(args, OPT_library_path);
1411 ctx.arg.sectionStartMap = getSectionStartMap(ctx, args);
1412 ctx.arg.shared = args.hasArg(OPT_shared);
1413 if (args.hasArg(OPT_randomize_section_padding))
1414 ctx.arg.randomizeSectionPadding =
1415 args::getInteger(args, OPT_randomize_section_padding, 0);
1416 ctx.arg.singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
1417 ctx.arg.soName = args.getLastArgValue(OPT_soname);
1418 ctx.arg.sortSection = getSortSection(ctx, args);
1419 ctx.arg.splitStackAdjustSize =
1420 args::getInteger(args, OPT_split_stack_adjust_size, 16384);
1421 ctx.arg.zSectionHeader =
1422 getZFlag(args, "sectionheader", "nosectionheader", true);
1423 ctx.arg.strip = getStrip(ctx, args); // needs zSectionHeader
1424 ctx.arg.sysroot = args.getLastArgValue(OPT_sysroot);
1425 ctx.arg.target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
1426 ctx.arg.target2 = getTarget2(ctx, args);
1427 ctx.arg.thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
1428 ctx.arg.thinLTOCachePolicy = CHECK(
1429 parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
1430 "--thinlto-cache-policy: invalid cache policy");
1431 ctx.arg.thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1432 ctx.arg.thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||
1433 args.hasArg(OPT_thinlto_index_only) ||
1434 args.hasArg(OPT_thinlto_index_only_eq);
1435 ctx.arg.thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1436 args.hasArg(OPT_thinlto_index_only_eq);
1437 ctx.arg.thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1438 ctx.arg.thinLTOObjectSuffixReplace =
1439 getOldNewOptions(ctx, args, OPT_thinlto_object_suffix_replace_eq);
1440 std::tie(ctx.arg.thinLTOPrefixReplaceOld, ctx.arg.thinLTOPrefixReplaceNew,
1441 ctx.arg.thinLTOPrefixReplaceNativeObject) =
1442 getOldNewOptionsExtra(ctx, args, OPT_thinlto_prefix_replace_eq);
1443 if (ctx.arg.thinLTOEmitIndexFiles && !ctx.arg.thinLTOIndexOnly) {
1444 if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))
1445 ErrAlways(ctx) << "--thinlto-object-suffix-replace is not supported with "
1446 "--thinlto-emit-index-files";
1447 else if (args.hasArg(OPT_thinlto_prefix_replace_eq))
1448 ErrAlways(ctx) << "--thinlto-prefix-replace is not supported with "
1449 "--thinlto-emit-index-files";
1451 if (!ctx.arg.thinLTOPrefixReplaceNativeObject.empty() &&
1452 ctx.arg.thinLTOIndexOnlyArg.empty()) {
1453 ErrAlways(ctx)
1454 << "--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "
1455 "--thinlto-index-only=";
1457 ctx.arg.thinLTOModulesToCompile =
1458 args::getStrings(args, OPT_thinlto_single_module_eq);
1459 ctx.arg.timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
1460 ctx.arg.timeTraceGranularity =
1461 args::getInteger(args, OPT_time_trace_granularity, 500);
1462 ctx.arg.trace = args.hasArg(OPT_trace);
1463 ctx.arg.undefined = args::getStrings(args, OPT_undefined);
1464 ctx.arg.undefinedVersion =
1465 args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, false);
1466 ctx.arg.unique = args.hasArg(OPT_unique);
1467 ctx.arg.useAndroidRelrTags = args.hasFlag(
1468 OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
1469 ctx.arg.warnBackrefs =
1470 args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
1471 ctx.arg.warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
1472 ctx.arg.warnSymbolOrdering =
1473 args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1474 ctx.arg.whyExtract = args.getLastArgValue(OPT_why_extract);
1475 ctx.arg.zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
1476 ctx.arg.zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
1477 ctx.arg.zForceBti = hasZOption(args, "force-bti");
1478 ctx.arg.zForceIbt = hasZOption(args, "force-ibt");
1479 ctx.arg.zGcs = getZGcs(ctx, args);
1480 ctx.arg.zGlobal = hasZOption(args, "global");
1481 ctx.arg.zGnustack = getZGnuStack(args);
1482 ctx.arg.zHazardplt = hasZOption(args, "hazardplt");
1483 ctx.arg.zIfuncNoplt = hasZOption(args, "ifunc-noplt");
1484 ctx.arg.zInitfirst = hasZOption(args, "initfirst");
1485 ctx.arg.zInterpose = hasZOption(args, "interpose");
1486 ctx.arg.zKeepTextSectionPrefix = getZFlag(
1487 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
1488 ctx.arg.zLrodataAfterBss =
1489 getZFlag(args, "lrodata-after-bss", "nolrodata-after-bss", false);
1490 ctx.arg.zNoBtCfi = hasZOption(args, "nobtcfi");
1491 ctx.arg.zNodefaultlib = hasZOption(args, "nodefaultlib");
1492 ctx.arg.zNodelete = hasZOption(args, "nodelete");
1493 ctx.arg.zNodlopen = hasZOption(args, "nodlopen");
1494 ctx.arg.zNow = getZFlag(args, "now", "lazy", false);
1495 ctx.arg.zOrigin = hasZOption(args, "origin");
1496 ctx.arg.zPacPlt = hasZOption(args, "pac-plt");
1497 ctx.arg.zRelro = getZFlag(args, "relro", "norelro", true);
1498 ctx.arg.zRetpolineplt = hasZOption(args, "retpolineplt");
1499 ctx.arg.zRodynamic = hasZOption(args, "rodynamic");
1500 ctx.arg.zSeparate = getZSeparate(args);
1501 ctx.arg.zShstk = hasZOption(args, "shstk");
1502 ctx.arg.zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1503 ctx.arg.zStartStopGC =
1504 getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);
1505 ctx.arg.zStartStopVisibility = getZStartStopVisibility(ctx, args);
1506 ctx.arg.zText = getZFlag(args, "text", "notext", true);
1507 ctx.arg.zWxneeded = hasZOption(args, "wxneeded");
1508 setUnresolvedSymbolPolicy(ctx, args);
1509 ctx.arg.power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";
1511 if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {
1512 if (arg->getOption().matches(OPT_eb))
1513 ctx.arg.optEB = true;
1514 else
1515 ctx.arg.optEL = true;
1518 for (opt::Arg *arg : args.filtered(OPT_remap_inputs)) {
1519 StringRef value(arg->getValue());
1520 remapInputs(ctx, value, arg->getSpelling());
1522 for (opt::Arg *arg : args.filtered(OPT_remap_inputs_file)) {
1523 StringRef filename(arg->getValue());
1524 std::optional<MemoryBufferRef> buffer = readFile(ctx, filename);
1525 if (!buffer)
1526 continue;
1527 // Parse 'from-glob=to-file' lines, ignoring #-led comments.
1528 for (auto [lineno, line] : llvm::enumerate(args::getLines(*buffer)))
1529 if (remapInputs(ctx, line, filename + ":" + Twine(lineno + 1)))
1530 break;
1533 for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {
1534 constexpr StringRef errPrefix = "--shuffle-sections=: ";
1535 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
1536 if (kv.first.empty() || kv.second.empty()) {
1537 ErrAlways(ctx) << errPrefix << "expected <section_glob>=<seed>, but got '"
1538 << arg->getValue() << "'";
1539 continue;
1541 // Signed so that <section_glob>=-1 is allowed.
1542 int64_t v;
1543 if (!to_integer(kv.second, v))
1544 ErrAlways(ctx) << errPrefix << "expected an integer, but got '"
1545 << kv.second << "'";
1546 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1547 ctx.arg.shuffleSections.emplace_back(std::move(*pat), uint32_t(v));
1548 else
1549 ErrAlways(ctx) << errPrefix << pat.takeError() << ": " << kv.first;
1552 auto reports = {std::make_pair("bti-report", &ctx.arg.zBtiReport),
1553 std::make_pair("cet-report", &ctx.arg.zCetReport),
1554 std::make_pair("gcs-report", &ctx.arg.zGcsReport),
1555 std::make_pair("pauth-report", &ctx.arg.zPauthReport)};
1556 for (opt::Arg *arg : args.filtered(OPT_z)) {
1557 std::pair<StringRef, StringRef> option =
1558 StringRef(arg->getValue()).split('=');
1559 for (auto reportArg : reports) {
1560 if (option.first != reportArg.first)
1561 continue;
1562 arg->claim();
1563 if (!isValidReportString(option.second)) {
1564 ErrAlways(ctx) << "-z " << reportArg.first << "= parameter "
1565 << option.second << " is not recognized";
1566 continue;
1568 *reportArg.second = option.second;
1572 for (opt::Arg *arg : args.filtered(OPT_compress_sections)) {
1573 SmallVector<StringRef, 0> fields;
1574 StringRef(arg->getValue()).split(fields, '=');
1575 if (fields.size() != 2 || fields[1].empty()) {
1576 ErrAlways(ctx) << arg->getSpelling()
1577 << ": parse error, not 'section-glob=[none|zlib|zstd]'";
1578 continue;
1580 auto [typeStr, levelStr] = fields[1].split(':');
1581 auto type = getCompressionType(ctx, typeStr, arg->getSpelling());
1582 unsigned level = 0;
1583 if (fields[1].size() != typeStr.size() &&
1584 !llvm::to_integer(levelStr, level)) {
1585 ErrAlways(ctx)
1586 << arg->getSpelling()
1587 << ": expected a non-negative integer compression level, but got '"
1588 << levelStr << "'";
1590 if (Expected<GlobPattern> pat = GlobPattern::create(fields[0])) {
1591 ctx.arg.compressSections.emplace_back(std::move(*pat), type, level);
1592 } else {
1593 ErrAlways(ctx) << arg->getSpelling() << ": " << pat.takeError();
1594 continue;
1598 for (opt::Arg *arg : args.filtered(OPT_z)) {
1599 std::pair<StringRef, StringRef> option =
1600 StringRef(arg->getValue()).split('=');
1601 if (option.first != "dead-reloc-in-nonalloc")
1602 continue;
1603 arg->claim();
1604 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
1605 std::pair<StringRef, StringRef> kv = option.second.split('=');
1606 if (kv.first.empty() || kv.second.empty()) {
1607 ErrAlways(ctx) << errPrefix << "expected <section_glob>=<value>";
1608 continue;
1610 uint64_t v;
1611 if (!to_integer(kv.second, v))
1612 ErrAlways(ctx) << errPrefix
1613 << "expected a non-negative integer, but got '"
1614 << kv.second << "'";
1615 else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1616 ctx.arg.deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
1617 else
1618 ErrAlways(ctx) << errPrefix << pat.takeError() << ": " << kv.first;
1621 cl::ResetAllOptionOccurrences();
1623 // Parse LTO options.
1624 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
1625 parseClangOption(ctx, ctx.saver.save("-mcpu=" + StringRef(arg->getValue())),
1626 arg->getSpelling());
1628 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
1629 parseClangOption(ctx, std::string("-") + arg->getValue(),
1630 arg->getSpelling());
1632 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1633 // relative path. Just ignore. If not ended with "lto-wrapper" (or
1634 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
1635 // unsupported LLVMgold.so option and error.
1636 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) {
1637 StringRef v(arg->getValue());
1638 if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe"))
1639 ErrAlways(ctx) << arg->getSpelling() << ": unknown plugin option '"
1640 << arg->getValue() << "'";
1643 ctx.arg.passPlugins = args::getStrings(args, OPT_load_pass_plugins);
1645 // Parse -mllvm options.
1646 for (const auto *arg : args.filtered(OPT_mllvm)) {
1647 parseClangOption(ctx, arg->getValue(), arg->getSpelling());
1648 ctx.arg.mllvmOpts.emplace_back(arg->getValue());
1651 ctx.arg.ltoKind = LtoKind::Default;
1652 if (auto *arg = args.getLastArg(OPT_lto)) {
1653 StringRef s = arg->getValue();
1654 if (s == "thin")
1655 ctx.arg.ltoKind = LtoKind::UnifiedThin;
1656 else if (s == "full")
1657 ctx.arg.ltoKind = LtoKind::UnifiedRegular;
1658 else if (s == "default")
1659 ctx.arg.ltoKind = LtoKind::Default;
1660 else
1661 ErrAlways(ctx) << "unknown LTO mode: " << s;
1664 // --threads= takes a positive integer and provides the default value for
1665 // --thinlto-jobs=. If unspecified, cap the number of threads since
1666 // overhead outweighs optimization for used parallel algorithms for the
1667 // non-LTO parts.
1668 if (auto *arg = args.getLastArg(OPT_threads)) {
1669 StringRef v(arg->getValue());
1670 unsigned threads = 0;
1671 if (!llvm::to_integer(v, threads, 0) || threads == 0)
1672 ErrAlways(ctx) << arg->getSpelling()
1673 << ": expected a positive integer, but got '"
1674 << arg->getValue() << "'";
1675 parallel::strategy = hardware_concurrency(threads);
1676 ctx.arg.thinLTOJobs = v;
1677 } else if (parallel::strategy.compute_thread_count() > 16) {
1678 Log(ctx) << "set maximum concurrency to 16, specify --threads= to change";
1679 parallel::strategy = hardware_concurrency(16);
1681 if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
1682 ctx.arg.thinLTOJobs = arg->getValue();
1683 ctx.arg.threadCount = parallel::strategy.compute_thread_count();
1685 if (ctx.arg.ltoPartitions == 0)
1686 ErrAlways(ctx) << "--lto-partitions: number of threads must be > 0";
1687 if (!get_threadpool_strategy(ctx.arg.thinLTOJobs))
1688 ErrAlways(ctx) << "--thinlto-jobs: invalid job count: "
1689 << ctx.arg.thinLTOJobs;
1691 if (ctx.arg.splitStackAdjustSize < 0)
1692 ErrAlways(ctx) << "--split-stack-adjust-size: size must be >= 0";
1694 // The text segment is traditionally the first segment, whose address equals
1695 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1696 // is an old-fashioned option that does not play well with lld's layout.
1697 // Suggest --image-base as a likely alternative.
1698 if (args.hasArg(OPT_Ttext_segment))
1699 ErrAlways(ctx)
1700 << "-Ttext-segment is not supported. Use --image-base if you "
1701 "intend to set the base address";
1703 // Parse ELF{32,64}{LE,BE} and CPU type.
1704 if (auto *arg = args.getLastArg(OPT_m)) {
1705 StringRef s = arg->getValue();
1706 std::tie(ctx.arg.ekind, ctx.arg.emachine, ctx.arg.osabi) =
1707 parseEmulation(ctx, s);
1708 ctx.arg.mipsN32Abi =
1709 (s.starts_with("elf32btsmipn32") || s.starts_with("elf32ltsmipn32"));
1710 ctx.arg.emulation = s;
1713 // Parse --hash-style={sysv,gnu,both}.
1714 if (auto *arg = args.getLastArg(OPT_hash_style)) {
1715 StringRef s = arg->getValue();
1716 if (s == "sysv")
1717 ctx.arg.sysvHash = true;
1718 else if (s == "gnu")
1719 ctx.arg.gnuHash = true;
1720 else if (s == "both")
1721 ctx.arg.sysvHash = ctx.arg.gnuHash = true;
1722 else
1723 ErrAlways(ctx) << "unknown --hash-style: " << s;
1726 if (args.hasArg(OPT_print_map))
1727 ctx.arg.mapFile = "-";
1729 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1730 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1731 // it. Also disable RELRO for -r.
1732 if (ctx.arg.nmagic || ctx.arg.omagic || ctx.arg.relocatable)
1733 ctx.arg.zRelro = false;
1735 std::tie(ctx.arg.buildId, ctx.arg.buildIdVector) = getBuildId(ctx, args);
1737 if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) {
1738 ctx.arg.relrGlibc = true;
1739 ctx.arg.relrPackDynRelocs = true;
1740 } else {
1741 std::tie(ctx.arg.androidPackDynRelocs, ctx.arg.relrPackDynRelocs) =
1742 getPackDynRelocs(ctx, args);
1745 if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1746 if (args.hasArg(OPT_call_graph_ordering_file))
1747 ErrAlways(ctx) << "--symbol-ordering-file and --call-graph-order-file "
1748 "may not be used together";
1749 if (std::optional<MemoryBufferRef> buffer =
1750 readFile(ctx, arg->getValue())) {
1751 ctx.arg.symbolOrderingFile = getSymbolOrderingFile(ctx, *buffer);
1752 // Also need to disable CallGraphProfileSort to prevent
1753 // LLD order symbols with CGProfile
1754 ctx.arg.callGraphProfileSort = CGProfileSortKind::None;
1758 assert(ctx.arg.versionDefinitions.empty());
1759 ctx.arg.versionDefinitions.push_back(
1760 {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});
1761 ctx.arg.versionDefinitions.push_back(
1762 {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});
1764 // If --retain-symbol-file is used, we'll keep only the symbols listed in
1765 // the file and discard all others.
1766 if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1767 ctx.arg.versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
1768 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1769 if (std::optional<MemoryBufferRef> buffer = readFile(ctx, arg->getValue()))
1770 for (StringRef s : args::getLines(*buffer))
1771 ctx.arg.versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
1772 {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1775 for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
1776 StringRef pattern(arg->getValue());
1777 if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
1778 ctx.arg.warnBackrefsExclude.push_back(std::move(*pat));
1779 else
1780 ErrAlways(ctx) << arg->getSpelling() << ": " << pat.takeError() << ": "
1781 << pattern;
1784 // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1785 // which should be exported. For -shared, references to matched non-local
1786 // STV_DEFAULT symbols are not bound to definitions within the shared object,
1787 // even if other options express a symbolic intention: -Bsymbolic,
1788 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1789 for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1790 ctx.arg.dynamicList.push_back(
1791 {arg->getValue(), /*isExternCpp=*/false,
1792 /*hasWildcard=*/hasWildcard(arg->getValue())});
1794 // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1795 // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1796 // like semantics.
1797 ctx.arg.symbolic =
1798 ctx.arg.bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1799 for (auto *arg :
1800 args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))
1801 if (std::optional<MemoryBufferRef> buffer = readFile(ctx, arg->getValue()))
1802 readDynamicList(ctx, *buffer);
1804 for (auto *arg : args.filtered(OPT_version_script))
1805 if (std::optional<std::string> path = searchScript(ctx, arg->getValue())) {
1806 if (std::optional<MemoryBufferRef> buffer = readFile(ctx, *path))
1807 readVersionScript(ctx, *buffer);
1808 } else {
1809 ErrAlways(ctx) << "cannot find version script " << arg->getValue();
1813 // Some Config members do not directly correspond to any particular
1814 // command line options, but computed based on other Config values.
1815 // This function initialize such members. See Config.h for the details
1816 // of these values.
1817 static void setConfigs(Ctx &ctx, opt::InputArgList &args) {
1818 ELFKind k = ctx.arg.ekind;
1819 uint16_t m = ctx.arg.emachine;
1821 ctx.arg.copyRelocs = (ctx.arg.relocatable || ctx.arg.emitRelocs);
1822 ctx.arg.is64 = (k == ELF64LEKind || k == ELF64BEKind);
1823 ctx.arg.isLE = (k == ELF32LEKind || k == ELF64LEKind);
1824 ctx.arg.endianness = ctx.arg.isLE ? endianness::little : endianness::big;
1825 ctx.arg.isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1826 ctx.arg.isPic = ctx.arg.pie || ctx.arg.shared;
1827 ctx.arg.picThunk = args.hasArg(OPT_pic_veneer, ctx.arg.isPic);
1828 ctx.arg.wordsize = ctx.arg.is64 ? 8 : 4;
1830 // ELF defines two different ways to store relocation addends as shown below:
1832 // Rel: Addends are stored to the location where relocations are applied. It
1833 // cannot pack the full range of addend values for all relocation types, but
1834 // this only affects relocation types that we don't support emitting as
1835 // dynamic relocations (see getDynRel).
1836 // Rela: Addends are stored as part of relocation entry.
1838 // In other words, Rela makes it easy to read addends at the price of extra
1839 // 4 or 8 byte for each relocation entry.
1841 // We pick the format for dynamic relocations according to the psABI for each
1842 // processor, but a contrary choice can be made if the dynamic loader
1843 // supports.
1844 ctx.arg.isRela = getIsRela(ctx, args);
1846 // If the output uses REL relocations we must store the dynamic relocation
1847 // addends to the output sections. We also store addends for RELA relocations
1848 // if --apply-dynamic-relocs is used.
1849 // We default to not writing the addends when using RELA relocations since
1850 // any standard conforming tool can find it in r_addend.
1851 ctx.arg.writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1852 OPT_no_apply_dynamic_relocs, false) ||
1853 !ctx.arg.isRela;
1854 // Validation of dynamic relocation addends is on by default for assertions
1855 // builds and disabled otherwise. This check is enabled when writeAddends is
1856 // true.
1857 #ifndef NDEBUG
1858 bool checkDynamicRelocsDefault = true;
1859 #else
1860 bool checkDynamicRelocsDefault = false;
1861 #endif
1862 ctx.arg.checkDynamicRelocs =
1863 args.hasFlag(OPT_check_dynamic_relocations,
1864 OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);
1865 ctx.arg.tocOptimize =
1866 args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1867 ctx.arg.pcRelOptimize =
1868 args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
1870 if (!args.hasArg(OPT_hash_style)) {
1871 if (ctx.arg.emachine == EM_MIPS)
1872 ctx.arg.sysvHash = true;
1873 else
1874 ctx.arg.sysvHash = ctx.arg.gnuHash = true;
1877 // Set default entry point and output file if not specified by command line or
1878 // linker scripts.
1879 ctx.arg.warnMissingEntry =
1880 (!ctx.arg.entry.empty() || (!ctx.arg.shared && !ctx.arg.relocatable));
1881 if (ctx.arg.entry.empty() && !ctx.arg.relocatable)
1882 ctx.arg.entry = ctx.arg.emachine == EM_MIPS ? "__start" : "_start";
1883 if (ctx.arg.outputFile.empty())
1884 ctx.arg.outputFile = "a.out";
1886 // Fail early if the output file or map file is not writable. If a user has a
1887 // long link, e.g. due to a large LTO link, they do not wish to run it and
1888 // find that it failed because there was a mistake in their command-line.
1890 llvm::TimeTraceScope timeScope("Create output files");
1891 if (auto e = tryCreateFile(ctx.arg.outputFile))
1892 ErrAlways(ctx) << "cannot open output file " << ctx.arg.outputFile << ": "
1893 << e.message();
1894 if (auto e = tryCreateFile(ctx.arg.mapFile))
1895 ErrAlways(ctx) << "cannot open map file " << ctx.arg.mapFile << ": "
1896 << e.message();
1897 if (auto e = tryCreateFile(ctx.arg.whyExtract))
1898 ErrAlways(ctx) << "cannot open --why-extract= file " << ctx.arg.whyExtract
1899 << ": " << e.message();
1903 static bool isFormatBinary(Ctx &ctx, StringRef s) {
1904 if (s == "binary")
1905 return true;
1906 if (s == "elf" || s == "default")
1907 return false;
1908 ErrAlways(ctx) << "unknown --format value: " << s
1909 << " (supported formats: elf, default, binary)";
1910 return false;
1913 void LinkerDriver::createFiles(opt::InputArgList &args) {
1914 llvm::TimeTraceScope timeScope("Load input files");
1915 // For --{push,pop}-state.
1916 std::vector<std::tuple<bool, bool, bool>> stack;
1918 // -r implies -Bstatic and has precedence over -Bdynamic.
1919 ctx.arg.isStatic = ctx.arg.relocatable;
1921 // Iterate over argv to process input files and positional arguments.
1922 std::optional<MemoryBufferRef> defaultScript;
1923 nextGroupId = 0;
1924 isInGroup = false;
1925 bool hasInput = false, hasScript = false;
1926 for (auto *arg : args) {
1927 switch (arg->getOption().getID()) {
1928 case OPT_library:
1929 addLibrary(arg->getValue());
1930 hasInput = true;
1931 break;
1932 case OPT_INPUT:
1933 addFile(arg->getValue(), /*withLOption=*/false);
1934 hasInput = true;
1935 break;
1936 case OPT_defsym: {
1937 readDefsym(ctx, MemoryBufferRef(arg->getValue(), "--defsym"));
1938 break;
1940 case OPT_script:
1941 case OPT_default_script:
1942 if (std::optional<std::string> path =
1943 searchScript(ctx, arg->getValue())) {
1944 if (std::optional<MemoryBufferRef> mb = readFile(ctx, *path)) {
1945 if (arg->getOption().matches(OPT_default_script)) {
1946 defaultScript = mb;
1947 } else {
1948 readLinkerScript(ctx, *mb);
1949 hasScript = true;
1952 break;
1954 ErrAlways(ctx) << "cannot find linker script " << arg->getValue();
1955 break;
1956 case OPT_as_needed:
1957 ctx.arg.asNeeded = true;
1958 break;
1959 case OPT_format:
1960 ctx.arg.formatBinary = isFormatBinary(ctx, arg->getValue());
1961 break;
1962 case OPT_no_as_needed:
1963 ctx.arg.asNeeded = false;
1964 break;
1965 case OPT_Bstatic:
1966 case OPT_omagic:
1967 case OPT_nmagic:
1968 ctx.arg.isStatic = true;
1969 break;
1970 case OPT_Bdynamic:
1971 if (!ctx.arg.relocatable)
1972 ctx.arg.isStatic = false;
1973 break;
1974 case OPT_whole_archive:
1975 inWholeArchive = true;
1976 break;
1977 case OPT_no_whole_archive:
1978 inWholeArchive = false;
1979 break;
1980 case OPT_just_symbols:
1981 if (std::optional<MemoryBufferRef> mb = readFile(ctx, arg->getValue())) {
1982 files.push_back(createObjFile(ctx, *mb));
1983 files.back()->justSymbols = true;
1985 break;
1986 case OPT_in_implib:
1987 if (armCmseImpLib)
1988 ErrAlways(ctx) << "multiple CMSE import libraries not supported";
1989 else if (std::optional<MemoryBufferRef> mb =
1990 readFile(ctx, arg->getValue()))
1991 armCmseImpLib = createObjFile(ctx, *mb);
1992 break;
1993 case OPT_start_group:
1994 if (isInGroup)
1995 ErrAlways(ctx) << "nested --start-group";
1996 isInGroup = true;
1997 break;
1998 case OPT_end_group:
1999 if (!isInGroup)
2000 ErrAlways(ctx) << "stray --end-group";
2001 isInGroup = false;
2002 ++nextGroupId;
2003 break;
2004 case OPT_start_lib:
2005 if (inLib)
2006 ErrAlways(ctx) << "nested --start-lib";
2007 if (isInGroup)
2008 ErrAlways(ctx) << "may not nest --start-lib in --start-group";
2009 inLib = true;
2010 isInGroup = true;
2011 break;
2012 case OPT_end_lib:
2013 if (!inLib)
2014 ErrAlways(ctx) << "stray --end-lib";
2015 inLib = false;
2016 isInGroup = false;
2017 ++nextGroupId;
2018 break;
2019 case OPT_push_state:
2020 stack.emplace_back(ctx.arg.asNeeded, ctx.arg.isStatic, inWholeArchive);
2021 break;
2022 case OPT_pop_state:
2023 if (stack.empty()) {
2024 ErrAlways(ctx) << "unbalanced --push-state/--pop-state";
2025 break;
2027 std::tie(ctx.arg.asNeeded, ctx.arg.isStatic, inWholeArchive) =
2028 stack.back();
2029 stack.pop_back();
2030 break;
2034 if (defaultScript && !hasScript)
2035 readLinkerScript(ctx, *defaultScript);
2036 if (files.empty() && !hasInput && errCount(ctx) == 0)
2037 ErrAlways(ctx) << "no input files";
2040 // If -m <machine_type> was not given, infer it from object files.
2041 void LinkerDriver::inferMachineType() {
2042 if (ctx.arg.ekind != ELFNoneKind)
2043 return;
2045 bool inferred = false;
2046 for (auto &f : files) {
2047 if (f->ekind == ELFNoneKind)
2048 continue;
2049 if (!inferred) {
2050 inferred = true;
2051 ctx.arg.ekind = f->ekind;
2052 ctx.arg.emachine = f->emachine;
2053 ctx.arg.mipsN32Abi = ctx.arg.emachine == EM_MIPS && isMipsN32Abi(ctx, *f);
2055 ctx.arg.osabi = f->osabi;
2056 if (f->osabi != ELFOSABI_NONE)
2057 return;
2059 if (!inferred)
2060 ErrAlways(ctx)
2061 << "target emulation unknown: -m or at least one .o file required";
2064 // Parse -z max-page-size=<value>. The default value is defined by
2065 // each target.
2066 static uint64_t getMaxPageSize(Ctx &ctx, opt::InputArgList &args) {
2067 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
2068 ctx.target->defaultMaxPageSize);
2069 if (!isPowerOf2_64(val)) {
2070 ErrAlways(ctx) << "max-page-size: value isn't a power of 2";
2071 return ctx.target->defaultMaxPageSize;
2073 if (ctx.arg.nmagic || ctx.arg.omagic) {
2074 if (val != ctx.target->defaultMaxPageSize)
2075 Warn(ctx)
2076 << "-z max-page-size set, but paging disabled by omagic or nmagic";
2077 return 1;
2079 return val;
2082 // Parse -z common-page-size=<value>. The default value is defined by
2083 // each target.
2084 static uint64_t getCommonPageSize(Ctx &ctx, opt::InputArgList &args) {
2085 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
2086 ctx.target->defaultCommonPageSize);
2087 if (!isPowerOf2_64(val)) {
2088 ErrAlways(ctx) << "common-page-size: value isn't a power of 2";
2089 return ctx.target->defaultCommonPageSize;
2091 if (ctx.arg.nmagic || ctx.arg.omagic) {
2092 if (val != ctx.target->defaultCommonPageSize)
2093 Warn(ctx)
2094 << "-z common-page-size set, but paging disabled by omagic or nmagic";
2095 return 1;
2097 // commonPageSize can't be larger than maxPageSize.
2098 if (val > ctx.arg.maxPageSize)
2099 val = ctx.arg.maxPageSize;
2100 return val;
2103 // Parses --image-base option.
2104 static std::optional<uint64_t> getImageBase(Ctx &ctx, opt::InputArgList &args) {
2105 // Because we are using `ctx.arg.maxPageSize` here, this function has to be
2106 // called after the variable is initialized.
2107 auto *arg = args.getLastArg(OPT_image_base);
2108 if (!arg)
2109 return std::nullopt;
2111 StringRef s = arg->getValue();
2112 uint64_t v;
2113 if (!to_integer(s, v)) {
2114 ErrAlways(ctx) << "--image-base: number expected, but got " << s;
2115 return 0;
2117 if ((v % ctx.arg.maxPageSize) != 0)
2118 Warn(ctx) << "--image-base: address isn't multiple of page size: " << s;
2119 return v;
2122 // Parses `--exclude-libs=lib,lib,...`.
2123 // The library names may be delimited by commas or colons.
2124 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
2125 DenseSet<StringRef> ret;
2126 for (auto *arg : args.filtered(OPT_exclude_libs)) {
2127 StringRef s = arg->getValue();
2128 for (;;) {
2129 size_t pos = s.find_first_of(",:");
2130 if (pos == StringRef::npos)
2131 break;
2132 ret.insert(s.substr(0, pos));
2133 s = s.substr(pos + 1);
2135 ret.insert(s);
2137 return ret;
2140 // Handles the --exclude-libs option. If a static library file is specified
2141 // by the --exclude-libs option, all public symbols from the archive become
2142 // private unless otherwise specified by version scripts or something.
2143 // A special library name "ALL" means all archive files.
2145 // This is not a popular option, but some programs such as bionic libc use it.
2146 static void excludeLibs(Ctx &ctx, opt::InputArgList &args) {
2147 DenseSet<StringRef> libs = getExcludeLibs(args);
2148 bool all = libs.count("ALL");
2150 auto visit = [&](InputFile *file) {
2151 if (file->archiveName.empty() ||
2152 !(all || libs.count(path::filename(file->archiveName))))
2153 return;
2154 ArrayRef<Symbol *> symbols = file->getSymbols();
2155 if (isa<ELFFileBase>(file))
2156 symbols = cast<ELFFileBase>(file)->getGlobalSymbols();
2157 for (Symbol *sym : symbols)
2158 if (!sym->isUndefined() && sym->file == file)
2159 sym->versionId = VER_NDX_LOCAL;
2162 for (ELFFileBase *file : ctx.objectFiles)
2163 visit(file);
2165 for (BitcodeFile *file : ctx.bitcodeFiles)
2166 visit(file);
2169 // Force Sym to be entered in the output.
2170 static void handleUndefined(Ctx &ctx, Symbol *sym, const char *option) {
2171 // Since a symbol may not be used inside the program, LTO may
2172 // eliminate it. Mark the symbol as "used" to prevent it.
2173 sym->isUsedInRegularObj = true;
2175 if (!sym->isLazy())
2176 return;
2177 sym->extract(ctx);
2178 if (!ctx.arg.whyExtract.empty())
2179 ctx.whyExtractRecords.emplace_back(option, sym->file, *sym);
2182 // As an extension to GNU linkers, lld supports a variant of `-u`
2183 // which accepts wildcard patterns. All symbols that match a given
2184 // pattern are handled as if they were given by `-u`.
2185 static void handleUndefinedGlob(Ctx &ctx, StringRef arg) {
2186 Expected<GlobPattern> pat = GlobPattern::create(arg);
2187 if (!pat) {
2188 ErrAlways(ctx) << "--undefined-glob: " << pat.takeError() << ": " << arg;
2189 return;
2192 // Calling sym->extract() in the loop is not safe because it may add new
2193 // symbols to the symbol table, invalidating the current iterator.
2194 SmallVector<Symbol *, 0> syms;
2195 for (Symbol *sym : ctx.symtab->getSymbols())
2196 if (!sym->isPlaceholder() && pat->match(sym->getName()))
2197 syms.push_back(sym);
2199 for (Symbol *sym : syms)
2200 handleUndefined(ctx, sym, "--undefined-glob");
2203 static void handleLibcall(Ctx &ctx, StringRef name) {
2204 Symbol *sym = ctx.symtab->find(name);
2205 if (sym && sym->isLazy() && isa<BitcodeFile>(sym->file)) {
2206 if (!ctx.arg.whyExtract.empty())
2207 ctx.whyExtractRecords.emplace_back("<libcall>", sym->file, *sym);
2208 sym->extract(ctx);
2212 static void writeArchiveStats(Ctx &ctx) {
2213 if (ctx.arg.printArchiveStats.empty())
2214 return;
2216 std::error_code ec;
2217 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.printArchiveStats, ec);
2218 if (ec) {
2219 ErrAlways(ctx) << "--print-archive-stats=: cannot open "
2220 << ctx.arg.printArchiveStats << ": " << ec.message();
2221 return;
2224 os << "members\textracted\tarchive\n";
2226 SmallVector<StringRef, 0> archives;
2227 DenseMap<CachedHashStringRef, unsigned> all, extracted;
2228 for (ELFFileBase *file : ctx.objectFiles)
2229 if (file->archiveName.size())
2230 ++extracted[CachedHashStringRef(file->archiveName)];
2231 for (BitcodeFile *file : ctx.bitcodeFiles)
2232 if (file->archiveName.size())
2233 ++extracted[CachedHashStringRef(file->archiveName)];
2234 for (std::pair<StringRef, unsigned> f : ctx.driver.archiveFiles) {
2235 unsigned &v = extracted[CachedHashString(f.first)];
2236 os << f.second << '\t' << v << '\t' << f.first << '\n';
2237 // If the archive occurs multiple times, other instances have a count of 0.
2238 v = 0;
2242 static void writeWhyExtract(Ctx &ctx) {
2243 if (ctx.arg.whyExtract.empty())
2244 return;
2246 std::error_code ec;
2247 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.whyExtract, ec);
2248 if (ec) {
2249 ErrAlways(ctx) << "cannot open --why-extract= file " << ctx.arg.whyExtract
2250 << ": " << ec.message();
2251 return;
2254 os << "reference\textracted\tsymbol\n";
2255 for (auto &entry : ctx.whyExtractRecords) {
2256 os << std::get<0>(entry) << '\t' << toStr(ctx, std::get<1>(entry)) << '\t'
2257 << toStr(ctx, std::get<2>(entry)) << '\n';
2261 static void reportBackrefs(Ctx &ctx) {
2262 for (auto &ref : ctx.backwardReferences) {
2263 const Symbol &sym = *ref.first;
2264 std::string to = toStr(ctx, ref.second.second);
2265 // Some libraries have known problems and can cause noise. Filter them out
2266 // with --warn-backrefs-exclude=. The value may look like (for --start-lib)
2267 // *.o or (archive member) *.a(*.o).
2268 bool exclude = false;
2269 for (const llvm::GlobPattern &pat : ctx.arg.warnBackrefsExclude)
2270 if (pat.match(to)) {
2271 exclude = true;
2272 break;
2274 if (!exclude)
2275 Warn(ctx) << "backward reference detected: " << sym.getName() << " in "
2276 << ref.second.first << " refers to " << to;
2280 // Handle --dependency-file=<path>. If that option is given, lld creates a
2281 // file at a given path with the following contents:
2283 // <output-file>: <input-file> ...
2285 // <input-file>:
2287 // where <output-file> is a pathname of an output file and <input-file>
2288 // ... is a list of pathnames of all input files. `make` command can read a
2289 // file in the above format and interpret it as a dependency info. We write
2290 // phony targets for every <input-file> to avoid an error when that file is
2291 // removed.
2293 // This option is useful if you want to make your final executable to depend
2294 // on all input files including system libraries. Here is why.
2296 // When you write a Makefile, you usually write it so that the final
2297 // executable depends on all user-generated object files. Normally, you
2298 // don't make your executable to depend on system libraries (such as libc)
2299 // because you don't know the exact paths of libraries, even though system
2300 // libraries that are linked to your executable statically are technically a
2301 // part of your program. By using --dependency-file option, you can make
2302 // lld to dump dependency info so that you can maintain exact dependencies
2303 // easily.
2304 static void writeDependencyFile(Ctx &ctx) {
2305 std::error_code ec;
2306 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.dependencyFile, ec);
2307 if (ec) {
2308 ErrAlways(ctx) << "cannot open " << ctx.arg.dependencyFile << ": "
2309 << ec.message();
2310 return;
2313 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
2314 // * A space is escaped by a backslash which itself must be escaped.
2315 // * A hash sign is escaped by a single backslash.
2316 // * $ is escapes as $$.
2317 auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
2318 llvm::SmallString<256> nativePath;
2319 llvm::sys::path::native(filename.str(), nativePath);
2320 llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
2321 for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
2322 if (nativePath[i] == '#') {
2323 os << '\\';
2324 } else if (nativePath[i] == ' ') {
2325 os << '\\';
2326 unsigned j = i;
2327 while (j > 0 && nativePath[--j] == '\\')
2328 os << '\\';
2329 } else if (nativePath[i] == '$') {
2330 os << '$';
2332 os << nativePath[i];
2336 os << ctx.arg.outputFile << ":";
2337 for (StringRef path : ctx.arg.dependencyFiles) {
2338 os << " \\\n ";
2339 printFilename(os, path);
2341 os << "\n";
2343 for (StringRef path : ctx.arg.dependencyFiles) {
2344 os << "\n";
2345 printFilename(os, path);
2346 os << ":\n";
2350 // Replaces common symbols with defined symbols reside in .bss sections.
2351 // This function is called after all symbol names are resolved. As a
2352 // result, the passes after the symbol resolution won't see any
2353 // symbols of type CommonSymbol.
2354 static void replaceCommonSymbols(Ctx &ctx) {
2355 llvm::TimeTraceScope timeScope("Replace common symbols");
2356 for (ELFFileBase *file : ctx.objectFiles) {
2357 if (!file->hasCommonSyms)
2358 continue;
2359 for (Symbol *sym : file->getGlobalSymbols()) {
2360 auto *s = dyn_cast<CommonSymbol>(sym);
2361 if (!s)
2362 continue;
2364 auto *bss = make<BssSection>(ctx, "COMMON", s->size, s->alignment);
2365 bss->file = s->file;
2366 ctx.inputSections.push_back(bss);
2367 Defined(ctx, s->file, StringRef(), s->binding, s->stOther, s->type,
2368 /*value=*/0, s->size, bss)
2369 .overwrite(*s);
2374 // The section referred to by `s` is considered address-significant. Set the
2375 // keepUnique flag on the section if appropriate.
2376 static void markAddrsig(bool icfSafe, Symbol *s) {
2377 // We don't need to keep text sections unique under --icf=all even if they
2378 // are address-significant.
2379 if (auto *d = dyn_cast_or_null<Defined>(s))
2380 if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section))
2381 if (icfSafe || !(sec->flags & SHF_EXECINSTR))
2382 sec->keepUnique = true;
2385 // Record sections that define symbols mentioned in --keep-unique <symbol>
2386 // and symbols referred to by address-significance tables. These sections are
2387 // ineligible for ICF.
2388 template <class ELFT>
2389 static void findKeepUniqueSections(Ctx &ctx, opt::InputArgList &args) {
2390 for (auto *arg : args.filtered(OPT_keep_unique)) {
2391 StringRef name = arg->getValue();
2392 auto *d = dyn_cast_or_null<Defined>(ctx.symtab->find(name));
2393 if (!d || !d->section) {
2394 Warn(ctx) << "could not find symbol " << name << " to keep unique";
2395 continue;
2397 if (auto *sec = dyn_cast<InputSectionBase>(d->section))
2398 sec->keepUnique = true;
2401 // --icf=all --ignore-data-address-equality means that we can ignore
2402 // the dynsym and address-significance tables entirely.
2403 if (ctx.arg.icf == ICFLevel::All && ctx.arg.ignoreDataAddressEquality)
2404 return;
2406 // Symbols in the dynsym could be address-significant in other executables
2407 // or DSOs, so we conservatively mark them as address-significant.
2408 bool icfSafe = ctx.arg.icf == ICFLevel::Safe;
2409 for (Symbol *sym : ctx.symtab->getSymbols())
2410 if (sym->includeInDynsym(ctx))
2411 markAddrsig(icfSafe, sym);
2413 // Visit the address-significance table in each object file and mark each
2414 // referenced symbol as address-significant.
2415 for (InputFile *f : ctx.objectFiles) {
2416 auto *obj = cast<ObjFile<ELFT>>(f);
2417 ArrayRef<Symbol *> syms = obj->getSymbols();
2418 if (obj->addrsigSec) {
2419 ArrayRef<uint8_t> contents =
2420 check(obj->getObj().getSectionContents(*obj->addrsigSec));
2421 const uint8_t *cur = contents.begin();
2422 while (cur != contents.end()) {
2423 unsigned size;
2424 const char *err = nullptr;
2425 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
2426 if (err)
2427 Fatal(ctx) << f << ": could not decode addrsig section: " << err;
2428 markAddrsig(icfSafe, syms[symIndex]);
2429 cur += size;
2431 } else {
2432 // If an object file does not have an address-significance table,
2433 // conservatively mark all of its symbols as address-significant.
2434 for (Symbol *s : syms)
2435 markAddrsig(icfSafe, s);
2440 // This function reads a symbol partition specification section. These sections
2441 // are used to control which partition a symbol is allocated to. See
2442 // https://lld.llvm.org/Partitions.html for more details on partitions.
2443 template <typename ELFT>
2444 static void readSymbolPartitionSection(Ctx &ctx, InputSectionBase *s) {
2445 // Read the relocation that refers to the partition's entry point symbol.
2446 Symbol *sym;
2447 const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
2448 auto readEntry = [](InputFile *file, const auto &rels) -> Symbol * {
2449 for (const auto &rel : rels)
2450 return &file->getRelocTargetSym(rel);
2451 return nullptr;
2453 if (rels.areRelocsCrel())
2454 sym = readEntry(s->file, rels.crels);
2455 else if (rels.areRelocsRel())
2456 sym = readEntry(s->file, rels.rels);
2457 else
2458 sym = readEntry(s->file, rels.relas);
2459 if (!isa_and_nonnull<Defined>(sym) || !sym->isExported)
2460 return;
2462 StringRef partName = reinterpret_cast<const char *>(s->content().data());
2463 for (Partition &part : ctx.partitions) {
2464 if (part.name == partName) {
2465 sym->partition = part.getNumber(ctx);
2466 return;
2470 // Forbid partitions from being used on incompatible targets, and forbid them
2471 // from being used together with various linker features that assume a single
2472 // set of output sections.
2473 if (ctx.script->hasSectionsCommand)
2474 ErrAlways(ctx) << s->file
2475 << ": partitions cannot be used with the SECTIONS command";
2476 if (ctx.script->hasPhdrsCommands())
2477 ErrAlways(ctx) << s->file
2478 << ": partitions cannot be used with the PHDRS command";
2479 if (!ctx.arg.sectionStartMap.empty())
2480 ErrAlways(ctx) << s->file
2481 << ": partitions cannot be used with "
2482 "--section-start, -Ttext, -Tdata or -Tbss";
2483 if (ctx.arg.emachine == EM_MIPS)
2484 ErrAlways(ctx) << s->file << ": partitions cannot be used on this target";
2486 // Impose a limit of no more than 254 partitions. This limit comes from the
2487 // sizes of the Partition fields in InputSectionBase and Symbol, as well as
2488 // the amount of space devoted to the partition number in RankFlags.
2489 if (ctx.partitions.size() == 254)
2490 Fatal(ctx) << "may not have more than 254 partitions";
2492 ctx.partitions.emplace_back(ctx);
2493 Partition &newPart = ctx.partitions.back();
2494 newPart.name = partName;
2495 sym->partition = newPart.getNumber(ctx);
2498 static void markBuffersAsDontNeed(Ctx &ctx, bool skipLinkedOutput) {
2499 // With --thinlto-index-only, all buffers are nearly unused from now on
2500 // (except symbol/section names used by infrequent passes). Mark input file
2501 // buffers as MADV_DONTNEED so that these pages can be reused by the expensive
2502 // thin link, saving memory.
2503 if (skipLinkedOutput) {
2504 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))
2505 mb.dontNeedIfMmap();
2506 return;
2509 // Otherwise, just mark MemoryBuffers backing BitcodeFiles.
2510 DenseSet<const char *> bufs;
2511 for (BitcodeFile *file : ctx.bitcodeFiles)
2512 bufs.insert(file->mb.getBufferStart());
2513 for (BitcodeFile *file : ctx.lazyBitcodeFiles)
2514 bufs.insert(file->mb.getBufferStart());
2515 for (MemoryBuffer &mb : llvm::make_pointee_range(ctx.memoryBuffers))
2516 if (bufs.count(mb.getBufferStart()))
2517 mb.dontNeedIfMmap();
2520 // This function is where all the optimizations of link-time
2521 // optimization takes place. When LTO is in use, some input files are
2522 // not in native object file format but in the LLVM bitcode format.
2523 // This function compiles bitcode files into a few big native files
2524 // using LLVM functions and replaces bitcode symbols with the results.
2525 // Because all bitcode files that the program consists of are passed to
2526 // the compiler at once, it can do a whole-program optimization.
2527 template <class ELFT>
2528 void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) {
2529 llvm::TimeTraceScope timeScope("LTO");
2530 // Compile bitcode files and replace bitcode symbols.
2531 lto.reset(new BitcodeCompiler(ctx));
2532 for (BitcodeFile *file : ctx.bitcodeFiles)
2533 lto->add(*file);
2535 if (!ctx.bitcodeFiles.empty())
2536 markBuffersAsDontNeed(ctx, skipLinkedOutput);
2538 ltoObjectFiles = lto->compile();
2539 for (auto &file : ltoObjectFiles) {
2540 auto *obj = cast<ObjFile<ELFT>>(file.get());
2541 obj->parse(/*ignoreComdats=*/true);
2543 // Parse '@' in symbol names for non-relocatable output.
2544 if (!ctx.arg.relocatable)
2545 for (Symbol *sym : obj->getGlobalSymbols())
2546 if (sym->hasVersionSuffix)
2547 sym->parseSymbolVersion(ctx);
2548 ctx.objectFiles.push_back(obj);
2552 // The --wrap option is a feature to rename symbols so that you can write
2553 // wrappers for existing functions. If you pass `--wrap=foo`, all
2554 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
2555 // expected to write `__wrap_foo` function as a wrapper). The original
2556 // symbol becomes accessible as `__real_foo`, so you can call that from your
2557 // wrapper.
2559 // This data structure is instantiated for each --wrap option.
2560 struct WrappedSymbol {
2561 Symbol *sym;
2562 Symbol *real;
2563 Symbol *wrap;
2566 // Handles --wrap option.
2568 // This function instantiates wrapper symbols. At this point, they seem
2569 // like they are not being used at all, so we explicitly set some flags so
2570 // that LTO won't eliminate them.
2571 static std::vector<WrappedSymbol> addWrappedSymbols(Ctx &ctx,
2572 opt::InputArgList &args) {
2573 std::vector<WrappedSymbol> v;
2574 DenseSet<StringRef> seen;
2575 auto &ss = ctx.saver;
2576 for (auto *arg : args.filtered(OPT_wrap)) {
2577 StringRef name = arg->getValue();
2578 if (!seen.insert(name).second)
2579 continue;
2581 Symbol *sym = ctx.symtab->find(name);
2582 if (!sym)
2583 continue;
2585 Symbol *wrap =
2586 ctx.symtab->addUnusedUndefined(ss.save("__wrap_" + name), sym->binding);
2588 // If __real_ is referenced, pull in the symbol if it is lazy. Do this after
2589 // processing __wrap_ as that may have referenced __real_.
2590 StringRef realName = ctx.saver.save("__real_" + name);
2591 if (Symbol *real = ctx.symtab->find(realName)) {
2592 ctx.symtab->addUnusedUndefined(name, sym->binding);
2593 // Update sym's binding, which will replace real's later in
2594 // SymbolTable::wrap.
2595 sym->binding = real->binding;
2598 Symbol *real = ctx.symtab->addUnusedUndefined(realName);
2599 v.push_back({sym, real, wrap});
2601 // We want to tell LTO not to inline symbols to be overwritten
2602 // because LTO doesn't know the final symbol contents after renaming.
2603 real->scriptDefined = true;
2604 sym->scriptDefined = true;
2606 // If a symbol is referenced in any object file, bitcode file or shared
2607 // object, mark its redirection target (foo for __real_foo and __wrap_foo
2608 // for foo) as referenced after redirection, which will be used to tell LTO
2609 // to not eliminate the redirection target. If the object file defining the
2610 // symbol also references it, we cannot easily distinguish the case from
2611 // cases where the symbol is not referenced. Retain the redirection target
2612 // in this case because we choose to wrap symbol references regardless of
2613 // whether the symbol is defined
2614 // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
2615 if (real->referenced || real->isDefined())
2616 sym->referencedAfterWrap = true;
2617 if (sym->referenced || sym->isDefined())
2618 wrap->referencedAfterWrap = true;
2620 return v;
2623 static void combineVersionedSymbol(Ctx &ctx, Symbol &sym,
2624 DenseMap<Symbol *, Symbol *> &map) {
2625 const char *suffix1 = sym.getVersionSuffix();
2626 if (suffix1[0] != '@' || suffix1[1] == '@')
2627 return;
2629 // Check the existing symbol foo. We have two special cases to handle:
2631 // * There is a definition of foo@v1 and foo@@v1.
2632 // * There is a definition of foo@v1 and foo.
2633 Defined *sym2 = dyn_cast_or_null<Defined>(ctx.symtab->find(sym.getName()));
2634 if (!sym2)
2635 return;
2636 const char *suffix2 = sym2->getVersionSuffix();
2637 if (suffix2[0] == '@' && suffix2[1] == '@' &&
2638 strcmp(suffix1 + 1, suffix2 + 2) == 0) {
2639 // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
2640 map.try_emplace(&sym, sym2);
2641 // If both foo@v1 and foo@@v1 are defined and non-weak, report a
2642 // duplicate definition error.
2643 if (sym.isDefined()) {
2644 sym2->checkDuplicate(ctx, cast<Defined>(sym));
2645 sym2->resolve(ctx, cast<Defined>(sym));
2646 } else if (sym.isUndefined()) {
2647 sym2->resolve(ctx, cast<Undefined>(sym));
2648 } else {
2649 sym2->resolve(ctx, cast<SharedSymbol>(sym));
2651 // Eliminate foo@v1 from the symbol table.
2652 sym.symbolKind = Symbol::PlaceholderKind;
2653 sym.isUsedInRegularObj = false;
2654 } else if (auto *sym1 = dyn_cast<Defined>(&sym)) {
2655 if (sym2->versionId > VER_NDX_GLOBAL
2656 ? ctx.arg.versionDefinitions[sym2->versionId].name == suffix1 + 1
2657 : sym1->section == sym2->section && sym1->value == sym2->value) {
2658 // Due to an assembler design flaw, if foo is defined, .symver foo,
2659 // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2660 // different version, GNU ld makes foo@v1 canonical and eliminates
2661 // foo. Emulate its behavior, otherwise we would have foo or foo@@v1
2662 // beside foo@v1. foo@v1 and foo combining does not apply if they are
2663 // not defined in the same place.
2664 map.try_emplace(sym2, &sym);
2665 sym2->symbolKind = Symbol::PlaceholderKind;
2666 sym2->isUsedInRegularObj = false;
2671 // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
2673 // When this function is executed, only InputFiles and symbol table
2674 // contain pointers to symbol objects. We visit them to replace pointers,
2675 // so that wrapped symbols are swapped as instructed by the command line.
2676 static void redirectSymbols(Ctx &ctx, ArrayRef<WrappedSymbol> wrapped) {
2677 llvm::TimeTraceScope timeScope("Redirect symbols");
2678 DenseMap<Symbol *, Symbol *> map;
2679 for (const WrappedSymbol &w : wrapped) {
2680 map[w.sym] = w.wrap;
2681 map[w.real] = w.sym;
2684 // If there are version definitions (versionDefinitions.size() > 2), enumerate
2685 // symbols with a non-default version (foo@v1) and check whether it should be
2686 // combined with foo or foo@@v1.
2687 if (ctx.arg.versionDefinitions.size() > 2)
2688 for (Symbol *sym : ctx.symtab->getSymbols())
2689 if (sym->hasVersionSuffix)
2690 combineVersionedSymbol(ctx, *sym, map);
2692 if (map.empty())
2693 return;
2695 // Update pointers in input files.
2696 parallelForEach(ctx.objectFiles, [&](ELFFileBase *file) {
2697 for (Symbol *&sym : file->getMutableGlobalSymbols())
2698 if (Symbol *s = map.lookup(sym))
2699 sym = s;
2702 // Update pointers in the symbol table.
2703 for (const WrappedSymbol &w : wrapped)
2704 ctx.symtab->wrap(w.sym, w.real, w.wrap);
2707 // To enable CET (x86's hardware-assisted control flow enforcement), each
2708 // source file must be compiled with -fcf-protection. Object files compiled
2709 // with the flag contain feature flags indicating that they are compatible
2710 // with CET. We enable the feature only when all object files are compatible
2711 // with CET.
2713 // This is also the case with AARCH64's BTI and PAC which use the similar
2714 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
2716 // For AArch64 PAuth-enabled object files, the core info of all of them must
2717 // match. Missing info for some object files with matching info for remaining
2718 // ones can be allowed (see -z pauth-report).
2719 static void readSecurityNotes(Ctx &ctx) {
2720 if (ctx.arg.emachine != EM_386 && ctx.arg.emachine != EM_X86_64 &&
2721 ctx.arg.emachine != EM_AARCH64)
2722 return;
2724 ctx.arg.andFeatures = -1;
2726 StringRef referenceFileName;
2727 if (ctx.arg.emachine == EM_AARCH64) {
2728 auto it = llvm::find_if(ctx.objectFiles, [](const ELFFileBase *f) {
2729 return !f->aarch64PauthAbiCoreInfo.empty();
2731 if (it != ctx.objectFiles.end()) {
2732 ctx.aarch64PauthAbiCoreInfo = (*it)->aarch64PauthAbiCoreInfo;
2733 referenceFileName = (*it)->getName();
2736 bool hasValidPauthAbiCoreInfo = llvm::any_of(
2737 ctx.aarch64PauthAbiCoreInfo, [](uint8_t c) { return c != 0; });
2739 auto report = [&](StringRef config) -> ELFSyncStream {
2740 if (config == "error")
2741 return {ctx, DiagLevel::Err};
2742 else if (config == "warning")
2743 return {ctx, DiagLevel::Warn};
2744 return {ctx, DiagLevel::None};
2746 auto reportUnless = [&](StringRef config, bool cond) -> ELFSyncStream {
2747 if (cond)
2748 return {ctx, DiagLevel::None};
2749 return report(config);
2751 for (ELFFileBase *f : ctx.objectFiles) {
2752 uint32_t features = f->andFeatures;
2754 reportUnless(ctx.arg.zBtiReport,
2755 features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)
2756 << f
2757 << ": -z bti-report: file does not have "
2758 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property";
2760 reportUnless(ctx.arg.zGcsReport,
2761 features & GNU_PROPERTY_AARCH64_FEATURE_1_GCS)
2762 << f
2763 << ": -z gcs-report: file does not have "
2764 "GNU_PROPERTY_AARCH64_FEATURE_1_GCS property";
2766 reportUnless(ctx.arg.zCetReport, features & GNU_PROPERTY_X86_FEATURE_1_IBT)
2767 << f
2768 << ": -z cet-report: file does not have "
2769 "GNU_PROPERTY_X86_FEATURE_1_IBT property";
2771 reportUnless(ctx.arg.zCetReport,
2772 features & GNU_PROPERTY_X86_FEATURE_1_SHSTK)
2773 << f
2774 << ": -z cet-report: file does not have "
2775 "GNU_PROPERTY_X86_FEATURE_1_SHSTK property";
2777 if (ctx.arg.zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
2778 features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
2779 if (ctx.arg.zBtiReport == "none")
2780 Warn(ctx) << f
2781 << ": -z force-bti: file does not have "
2782 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property";
2783 } else if (ctx.arg.zForceIbt &&
2784 !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
2785 if (ctx.arg.zCetReport == "none")
2786 Warn(ctx) << f
2787 << ": -z force-ibt: file does not have "
2788 "GNU_PROPERTY_X86_FEATURE_1_IBT property";
2789 features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
2791 if (ctx.arg.zPacPlt && !(hasValidPauthAbiCoreInfo ||
2792 (features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC))) {
2793 Warn(ctx) << f
2794 << ": -z pac-plt: file does not have "
2795 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property and no valid "
2796 "PAuth core info present for this link job";
2797 features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
2799 ctx.arg.andFeatures &= features;
2801 if (ctx.aarch64PauthAbiCoreInfo.empty())
2802 continue;
2804 if (f->aarch64PauthAbiCoreInfo.empty()) {
2805 report(ctx.arg.zPauthReport)
2806 << f
2807 << ": -z pauth-report: file does not have AArch64 "
2808 "PAuth core info while '"
2809 << referenceFileName << "' has one";
2810 continue;
2813 if (ctx.aarch64PauthAbiCoreInfo != f->aarch64PauthAbiCoreInfo)
2814 Err(ctx) << "incompatible values of AArch64 PAuth core info found\n>>> "
2815 << referenceFileName << ": 0x"
2816 << toHex(ctx.aarch64PauthAbiCoreInfo, /*LowerCase=*/true)
2817 << "\n>>> " << f << ": 0x"
2818 << toHex(f->aarch64PauthAbiCoreInfo, /*LowerCase=*/true);
2821 // Force enable Shadow Stack.
2822 if (ctx.arg.zShstk)
2823 ctx.arg.andFeatures |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
2825 // Force enable/disable GCS
2826 if (ctx.arg.zGcs == GcsPolicy::Always)
2827 ctx.arg.andFeatures |= GNU_PROPERTY_AARCH64_FEATURE_1_GCS;
2828 else if (ctx.arg.zGcs == GcsPolicy::Never)
2829 ctx.arg.andFeatures &= ~GNU_PROPERTY_AARCH64_FEATURE_1_GCS;
2832 static void initSectionsAndLocalSyms(ELFFileBase *file, bool ignoreComdats) {
2833 switch (file->ekind) {
2834 case ELF32LEKind:
2835 cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2836 break;
2837 case ELF32BEKind:
2838 cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2839 break;
2840 case ELF64LEKind:
2841 cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2842 break;
2843 case ELF64BEKind:
2844 cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2845 break;
2846 default:
2847 llvm_unreachable("");
2851 static void postParseObjectFile(ELFFileBase *file) {
2852 switch (file->ekind) {
2853 case ELF32LEKind:
2854 cast<ObjFile<ELF32LE>>(file)->postParse();
2855 break;
2856 case ELF32BEKind:
2857 cast<ObjFile<ELF32BE>>(file)->postParse();
2858 break;
2859 case ELF64LEKind:
2860 cast<ObjFile<ELF64LE>>(file)->postParse();
2861 break;
2862 case ELF64BEKind:
2863 cast<ObjFile<ELF64BE>>(file)->postParse();
2864 break;
2865 default:
2866 llvm_unreachable("");
2870 // Do actual linking. Note that when this function is called,
2871 // all linker scripts have already been parsed.
2872 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
2873 llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
2875 // Handle --trace-symbol.
2876 for (auto *arg : args.filtered(OPT_trace_symbol))
2877 ctx.symtab->insert(arg->getValue())->traced = true;
2879 ctx.internalFile = createInternalFile(ctx, "<internal>");
2881 // Handle -u/--undefined before input files. If both a.a and b.so define foo,
2882 // -u foo a.a b.so will extract a.a.
2883 for (StringRef name : ctx.arg.undefined)
2884 ctx.symtab->addUnusedUndefined(name)->referenced = true;
2886 parseFiles(ctx, files);
2888 // Create dynamic sections for dynamic linking and static PIE.
2889 ctx.arg.hasDynSymTab = !ctx.sharedFiles.empty() || ctx.arg.isPic;
2891 // If an entry symbol is in a static archive, pull out that file now.
2892 if (Symbol *sym = ctx.symtab->find(ctx.arg.entry))
2893 handleUndefined(ctx, sym, "--entry");
2895 // Handle the `--undefined-glob <pattern>` options.
2896 for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
2897 handleUndefinedGlob(ctx, pat);
2899 // After potential archive member extraction involving ENTRY and
2900 // -u/--undefined-glob, check whether PROVIDE symbols should be defined (the
2901 // RHS may refer to definitions in just extracted object files).
2902 ctx.script->addScriptReferencedSymbolsToSymTable();
2904 // Prevent LTO from removing any definition referenced by -u.
2905 for (StringRef name : ctx.arg.undefined)
2906 if (Defined *sym = dyn_cast_or_null<Defined>(ctx.symtab->find(name)))
2907 sym->isUsedInRegularObj = true;
2909 // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2910 if (Symbol *sym = dyn_cast_or_null<Defined>(ctx.symtab->find(ctx.arg.init)))
2911 sym->isUsedInRegularObj = true;
2912 if (Symbol *sym = dyn_cast_or_null<Defined>(ctx.symtab->find(ctx.arg.fini)))
2913 sym->isUsedInRegularObj = true;
2915 // If any of our inputs are bitcode files, the LTO code generator may create
2916 // references to certain library functions that might not be explicit in the
2917 // bitcode file's symbol table. If any of those library functions are defined
2918 // in a bitcode file in an archive member, we need to arrange to use LTO to
2919 // compile those archive members by adding them to the link beforehand.
2921 // However, adding all libcall symbols to the link can have undesired
2922 // consequences. For example, the libgcc implementation of
2923 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
2924 // that aborts the program if the Linux kernel does not support 64-bit
2925 // atomics, which would prevent the program from running even if it does not
2926 // use 64-bit atomics.
2928 // Therefore, we only add libcall symbols to the link before LTO if we have
2929 // to, i.e. if the symbol's definition is in bitcode. Any other required
2930 // libcall symbols will be added to the link after LTO when we add the LTO
2931 // object file to the link.
2932 if (!ctx.bitcodeFiles.empty()) {
2933 llvm::Triple TT(ctx.bitcodeFiles.front()->obj->getTargetTriple());
2934 for (auto *s : lto::LTO::getRuntimeLibcallSymbols(TT))
2935 handleLibcall(ctx, s);
2938 // Archive members defining __wrap symbols may be extracted.
2939 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args);
2941 // No more lazy bitcode can be extracted at this point. Do post parse work
2942 // like checking duplicate symbols.
2943 parallelForEach(ctx.objectFiles, [](ELFFileBase *file) {
2944 initSectionsAndLocalSyms(file, /*ignoreComdats=*/false);
2946 parallelForEach(ctx.objectFiles, postParseObjectFile);
2947 parallelForEach(ctx.bitcodeFiles,
2948 [](BitcodeFile *file) { file->postParse(); });
2949 for (auto &it : ctx.nonPrevailingSyms) {
2950 Symbol &sym = *it.first;
2951 Undefined(sym.file, sym.getName(), sym.binding, sym.stOther, sym.type,
2952 it.second)
2953 .overwrite(sym);
2954 cast<Undefined>(sym).nonPrevailing = true;
2956 ctx.nonPrevailingSyms.clear();
2957 for (const DuplicateSymbol &d : ctx.duplicates)
2958 reportDuplicate(ctx, *d.sym, d.file, d.section, d.value);
2959 ctx.duplicates.clear();
2961 // Return if there were name resolution errors.
2962 if (errCount(ctx))
2963 return;
2965 // We want to declare linker script's symbols early,
2966 // so that we can version them.
2967 // They also might be exported if referenced by DSOs.
2968 ctx.script->declareSymbols();
2970 // Handle --exclude-libs. This is before scanVersionScript() due to a
2971 // workaround for Android ndk: for a defined versioned symbol in an archive
2972 // without a version node in the version script, Android does not expect a
2973 // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2974 // GNU ld errors in this case.
2975 if (args.hasArg(OPT_exclude_libs))
2976 excludeLibs(ctx, args);
2978 // Create elfHeader early. We need a dummy section in
2979 // addReservedSymbols to mark the created symbols as not absolute.
2980 ctx.out.elfHeader = std::make_unique<OutputSection>(ctx, "", 0, SHF_ALLOC);
2982 // We need to create some reserved symbols such as _end. Create them.
2983 if (!ctx.arg.relocatable)
2984 addReservedSymbols(ctx);
2986 // Apply version scripts.
2988 // For a relocatable output, version scripts don't make sense, and
2989 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
2990 // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2991 if (!ctx.arg.relocatable) {
2992 llvm::TimeTraceScope timeScope("Process symbol versions");
2993 ctx.symtab->scanVersionScript();
2995 parseVersionAndComputeIsPreemptible(ctx);
2998 // Skip the normal linked output if some LTO options are specified.
3000 // For --thinlto-index-only, index file creation is performed in
3001 // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and
3002 // --plugin-opt=emit-asm create output files in bitcode or assembly code,
3003 // respectively. When only certain thinLTO modules are specified for
3004 // compilation, the intermediate object file are the expected output.
3005 const bool skipLinkedOutput = ctx.arg.thinLTOIndexOnly || ctx.arg.emitLLVM ||
3006 ctx.arg.ltoEmitAsm ||
3007 !ctx.arg.thinLTOModulesToCompile.empty();
3009 // Handle --lto-validate-all-vtables-have-type-infos.
3010 if (ctx.arg.ltoValidateAllVtablesHaveTypeInfos)
3011 ltoValidateAllVtablesHaveTypeInfos<ELFT>(ctx, args);
3013 // Do link-time optimization if given files are LLVM bitcode files.
3014 // This compiles bitcode files into real object files.
3016 // With this the symbol table should be complete. After this, no new names
3017 // except a few linker-synthesized ones will be added to the symbol table.
3018 const size_t numObjsBeforeLTO = ctx.objectFiles.size();
3019 const size_t numInputFilesBeforeLTO = ctx.driver.files.size();
3020 compileBitcodeFiles<ELFT>(skipLinkedOutput);
3022 // Symbol resolution finished. Report backward reference problems,
3023 // --print-archive-stats=, and --why-extract=.
3024 reportBackrefs(ctx);
3025 writeArchiveStats(ctx);
3026 writeWhyExtract(ctx);
3027 if (errCount(ctx))
3028 return;
3030 // Bail out if normal linked output is skipped due to LTO.
3031 if (skipLinkedOutput)
3032 return;
3034 // compileBitcodeFiles may have produced lto.tmp object files. After this, no
3035 // more file will be added.
3036 auto newObjectFiles = ArrayRef(ctx.objectFiles).slice(numObjsBeforeLTO);
3037 parallelForEach(newObjectFiles, [](ELFFileBase *file) {
3038 initSectionsAndLocalSyms(file, /*ignoreComdats=*/true);
3040 parallelForEach(newObjectFiles, postParseObjectFile);
3041 for (const DuplicateSymbol &d : ctx.duplicates)
3042 reportDuplicate(ctx, *d.sym, d.file, d.section, d.value);
3044 // ELF dependent libraries may have introduced new input files after LTO has
3045 // completed. This is an error if the files haven't already been parsed, since
3046 // changing the symbol table could break the semantic assumptions of LTO.
3047 auto newInputFiles = ArrayRef(ctx.driver.files).slice(numInputFilesBeforeLTO);
3048 if (!newInputFiles.empty()) {
3049 DenseSet<StringRef> oldFilenames;
3050 for (auto &f : ArrayRef(ctx.driver.files).slice(0, numInputFilesBeforeLTO))
3051 oldFilenames.insert(f->getName());
3052 for (auto &newFile : newInputFiles)
3053 if (!oldFilenames.contains(newFile->getName()))
3054 Err(ctx) << "input file '" << newFile->getName() << "' added after LTO";
3057 // Handle --exclude-libs again because lto.tmp may reference additional
3058 // libcalls symbols defined in an excluded archive. This may override
3059 // versionId set by scanVersionScript().
3060 if (args.hasArg(OPT_exclude_libs))
3061 excludeLibs(ctx, args);
3063 // Record [__acle_se_<sym>, <sym>] pairs for later processing.
3064 processArmCmseSymbols(ctx);
3066 // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
3067 redirectSymbols(ctx, wrapped);
3069 // Replace common symbols with regular symbols.
3070 replaceCommonSymbols(ctx);
3073 llvm::TimeTraceScope timeScope("Aggregate sections");
3074 // Now that we have a complete list of input files.
3075 // Beyond this point, no new files are added.
3076 // Aggregate all input sections into one place.
3077 for (InputFile *f : ctx.objectFiles) {
3078 for (InputSectionBase *s : f->getSections()) {
3079 if (!s || s == &InputSection::discarded)
3080 continue;
3081 if (LLVM_UNLIKELY(isa<EhInputSection>(s)))
3082 ctx.ehInputSections.push_back(cast<EhInputSection>(s));
3083 else
3084 ctx.inputSections.push_back(s);
3087 for (BinaryFile *f : ctx.binaryFiles)
3088 for (InputSectionBase *s : f->getSections())
3089 ctx.inputSections.push_back(cast<InputSection>(s));
3093 llvm::TimeTraceScope timeScope("Strip sections");
3094 if (ctx.hasSympart.load(std::memory_order_relaxed)) {
3095 llvm::erase_if(ctx.inputSections, [&ctx = ctx](InputSectionBase *s) {
3096 if (s->type != SHT_LLVM_SYMPART)
3097 return false;
3098 readSymbolPartitionSection<ELFT>(ctx, s);
3099 return true;
3102 // We do not want to emit debug sections if --strip-all
3103 // or --strip-debug are given.
3104 if (ctx.arg.strip != StripPolicy::None) {
3105 llvm::erase_if(ctx.inputSections, [](InputSectionBase *s) {
3106 if (isDebugSection(*s))
3107 return true;
3108 if (auto *isec = dyn_cast<InputSection>(s))
3109 if (InputSectionBase *rel = isec->getRelocatedSection())
3110 if (isDebugSection(*rel))
3111 return true;
3113 return false;
3118 // Since we now have a complete set of input files, we can create
3119 // a .d file to record build dependencies.
3120 if (!ctx.arg.dependencyFile.empty())
3121 writeDependencyFile(ctx);
3123 // Now that the number of partitions is fixed, save a pointer to the main
3124 // partition.
3125 ctx.mainPart = &ctx.partitions[0];
3127 // Read .note.gnu.property sections from input object files which
3128 // contain a hint to tweak linker's and loader's behaviors.
3129 readSecurityNotes(ctx);
3131 // The Target instance handles target-specific stuff, such as applying
3132 // relocations or writing a PLT section. It also contains target-dependent
3133 // values such as a default image base address.
3134 setTarget(ctx);
3136 ctx.arg.eflags = ctx.target->calcEFlags();
3137 // maxPageSize (sometimes called abi page size) is the maximum page size that
3138 // the output can be run on. For example if the OS can use 4k or 64k page
3139 // sizes then maxPageSize must be 64k for the output to be useable on both.
3140 // All important alignment decisions must use this value.
3141 ctx.arg.maxPageSize = getMaxPageSize(ctx, args);
3142 // commonPageSize is the most common page size that the output will be run on.
3143 // For example if an OS can use 4k or 64k page sizes and 4k is more common
3144 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
3145 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
3146 // is limited to writing trap instructions on the last executable segment.
3147 ctx.arg.commonPageSize = getCommonPageSize(ctx, args);
3149 ctx.arg.imageBase = getImageBase(ctx, args);
3151 // This adds a .comment section containing a version string.
3152 if (!ctx.arg.relocatable)
3153 ctx.inputSections.push_back(createCommentSection(ctx));
3155 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
3156 splitSections<ELFT>(ctx);
3158 // Garbage collection and removal of shared symbols from unused shared objects.
3159 markLive<ELFT>(ctx);
3161 // Make copies of any input sections that need to be copied into each
3162 // partition.
3163 copySectionsIntoPartitions(ctx);
3165 if (canHaveMemtagGlobals(ctx)) {
3166 llvm::TimeTraceScope timeScope("Process memory tagged symbols");
3167 createTaggedSymbols(ctx);
3170 // Create synthesized sections such as .got and .plt. This is called before
3171 // processSectionCommands() so that they can be placed by SECTIONS commands.
3172 createSyntheticSections<ELFT>(ctx);
3174 // Some input sections that are used for exception handling need to be moved
3175 // into synthetic sections. Do that now so that they aren't assigned to
3176 // output sections in the usual way.
3177 if (!ctx.arg.relocatable)
3178 combineEhSections(ctx);
3180 // Merge .riscv.attributes sections.
3181 if (ctx.arg.emachine == EM_RISCV)
3182 mergeRISCVAttributesSections(ctx);
3185 llvm::TimeTraceScope timeScope("Assign sections");
3187 // Create output sections described by SECTIONS commands.
3188 ctx.script->processSectionCommands();
3190 // Linker scripts control how input sections are assigned to output
3191 // sections. Input sections that were not handled by scripts are called
3192 // "orphans", and they are assigned to output sections by the default rule.
3193 // Process that.
3194 ctx.script->addOrphanSections();
3198 llvm::TimeTraceScope timeScope("Merge/finalize input sections");
3200 // Migrate InputSectionDescription::sectionBases to sections. This includes
3201 // merging MergeInputSections into a single MergeSyntheticSection. From this
3202 // point onwards InputSectionDescription::sections should be used instead of
3203 // sectionBases.
3204 for (SectionCommand *cmd : ctx.script->sectionCommands)
3205 if (auto *osd = dyn_cast<OutputDesc>(cmd))
3206 osd->osec.finalizeInputSections();
3209 // Two input sections with different output sections should not be folded.
3210 // ICF runs after processSectionCommands() so that we know the output sections.
3211 if (ctx.arg.icf != ICFLevel::None) {
3212 findKeepUniqueSections<ELFT>(ctx, args);
3213 doIcf<ELFT>(ctx);
3216 // Read the callgraph now that we know what was gced or icfed
3217 if (ctx.arg.callGraphProfileSort != CGProfileSortKind::None) {
3218 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
3219 if (std::optional<MemoryBufferRef> buffer =
3220 readFile(ctx, arg->getValue()))
3221 readCallGraph(ctx, *buffer);
3222 readCallGraphsFromObjectFiles<ELFT>(ctx);
3225 // Write the result to the file.
3226 writeResult<ELFT>(ctx);