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