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