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