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