1 //===- Driver.cpp ---------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // The driver drives the entire linking process. It is responsible for
10 // parsing command line options and doing whatever it is instructed to do.
12 // One notable thing in the LLD's driver when compared to other linkers is
13 // that the LLD's driver is agnostic on the host operating system.
14 // Other linkers usually have implicit default values (such as a dynamic
15 // linker path or library paths) for each host OS.
17 // I don't think implicit default values are useful because they are
18 // usually explicitly specified by the compiler ctx.driver. They can even
19 // be harmful when you are doing cross-linking. Therefore, in LLD, we
20 // simply trust the compiler driver to pass all required options and
21 // don't try to make effort on our side.
23 //===----------------------------------------------------------------------===//
28 #include "InputFiles.h"
29 #include "InputSection.h"
31 #include "LinkerScript.h"
33 #include "OutputSections.h"
34 #include "ScriptParser.h"
35 #include "SymbolTable.h"
37 #include "SyntheticSections.h"
40 #include "lld/Common/Args.h"
41 #include "lld/Common/CommonLinkerContext.h"
42 #include "lld/Common/Driver.h"
43 #include "lld/Common/ErrorHandler.h"
44 #include "lld/Common/Filesystem.h"
45 #include "lld/Common/Memory.h"
46 #include "lld/Common/Strings.h"
47 #include "lld/Common/TargetOptionsCommandFlags.h"
48 #include "lld/Common/Version.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSwitch.h"
53 #include "llvm/Config/llvm-config.h"
54 #include "llvm/LTO/LTO.h"
55 #include "llvm/Object/Archive.h"
56 #include "llvm/Object/IRObjectFile.h"
57 #include "llvm/Remarks/HotnessThresholdParser.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/Compression.h"
60 #include "llvm/Support/FileSystem.h"
61 #include "llvm/Support/GlobPattern.h"
62 #include "llvm/Support/LEB128.h"
63 #include "llvm/Support/Parallel.h"
64 #include "llvm/Support/Path.h"
65 #include "llvm/Support/TarWriter.h"
66 #include "llvm/Support/TargetSelect.h"
67 #include "llvm/Support/TimeProfiler.h"
68 #include "llvm/Support/raw_ostream.h"
74 using namespace llvm::ELF
;
75 using namespace llvm::object
;
76 using namespace llvm::sys
;
77 using namespace llvm::support
;
79 using namespace lld::elf
;
81 ConfigWrapper
elf::config
;
84 static void setConfigs(opt::InputArgList
&args
);
85 static void readConfigs(opt::InputArgList
&args
);
87 void elf::errorOrWarn(const Twine
&msg
) {
88 if (config
->noinhibitExec
)
95 driver
= LinkerDriver();
96 memoryBuffers
.clear();
100 bitcodeFiles
.clear();
101 lazyBitcodeFiles
.clear();
102 inputSections
.clear();
103 ehInputSections
.clear();
105 nonPrevailingSyms
.clear();
106 whyExtractRecords
.clear();
107 backwardReferences
.clear();
108 auxiliaryFiles
.clear();
109 internalFile
= nullptr;
110 hasSympart
.store(false, std::memory_order_relaxed
);
111 hasTlsIe
.store(false, std::memory_order_relaxed
);
112 needsTlsLd
.store(false, std::memory_order_relaxed
);
113 scriptSymOrderCounter
= 1;
114 scriptSymOrder
.clear();
115 ltoAllVtablesHaveTypeInfos
= false;
118 llvm::raw_fd_ostream
Ctx::openAuxiliaryFile(llvm::StringRef filename
,
119 std::error_code
&ec
) {
120 using namespace llvm::sys::fs
;
122 auxiliaryFiles
.insert(filename
).second
? OF_None
: OF_Append
;
123 return {filename
, ec
, flags
};
128 bool link(ArrayRef
<const char *> args
, llvm::raw_ostream
&stdoutOS
,
129 llvm::raw_ostream
&stderrOS
, bool exitEarly
, bool disableOutput
) {
130 // This driver-specific context will be freed later by unsafeLldMain().
131 auto *ctx
= new CommonLinkerContext
;
133 ctx
->e
.initialize(stdoutOS
, stderrOS
, exitEarly
, disableOutput
);
134 ctx
->e
.cleanupCallback
= []() {
136 symtab
= SymbolTable();
138 outputSections
.clear();
145 partitions
.emplace_back();
147 SharedFile::vernauxNum
= 0;
149 ctx
->e
.logName
= args::getFilenameWithoutExe(args
[0]);
150 ctx
->e
.errorLimitExceededMsg
= "too many errors emitted, stopping now (use "
151 "--error-limit=0 to see all errors)";
153 config
= ConfigWrapper();
154 script
= ScriptWrapper();
156 symAux
.emplace_back();
159 partitions
.emplace_back();
161 config
->progName
= args
[0];
163 elf::ctx
.driver
.linkerMain(args
);
165 return errorCount() == 0;
170 // Parses a linker -m option.
171 static std::tuple
<ELFKind
, uint16_t, uint8_t> parseEmulation(StringRef emul
) {
174 if (s
.ends_with("_fbsd")) {
176 osabi
= ELFOSABI_FREEBSD
;
179 std::pair
<ELFKind
, uint16_t> ret
=
180 StringSwitch
<std::pair
<ELFKind
, uint16_t>>(s
)
181 .Cases("aarch64elf", "aarch64linux", {ELF64LEKind
, EM_AARCH64
})
182 .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind
, EM_AARCH64
})
183 .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind
, EM_ARM
})
184 .Cases("armelfb", "armelfb_linux_eabi", {ELF32BEKind
, EM_ARM
})
185 .Case("elf32_x86_64", {ELF32LEKind
, EM_X86_64
})
186 .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind
, EM_MIPS
})
187 .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind
, EM_MIPS
})
188 .Case("elf32lriscv", {ELF32LEKind
, EM_RISCV
})
189 .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind
, EM_PPC
})
190 .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind
, EM_PPC
})
191 .Case("elf32loongarch", {ELF32LEKind
, EM_LOONGARCH
})
192 .Case("elf64btsmip", {ELF64BEKind
, EM_MIPS
})
193 .Case("elf64ltsmip", {ELF64LEKind
, EM_MIPS
})
194 .Case("elf64lriscv", {ELF64LEKind
, EM_RISCV
})
195 .Case("elf64ppc", {ELF64BEKind
, EM_PPC64
})
196 .Case("elf64lppc", {ELF64LEKind
, EM_PPC64
})
197 .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind
, EM_X86_64
})
198 .Case("elf_i386", {ELF32LEKind
, EM_386
})
199 .Case("elf_iamcu", {ELF32LEKind
, EM_IAMCU
})
200 .Case("elf64_sparc", {ELF64BEKind
, EM_SPARCV9
})
201 .Case("msp430elf", {ELF32LEKind
, EM_MSP430
})
202 .Case("elf64_amdgpu", {ELF64LEKind
, EM_AMDGPU
})
203 .Case("elf64loongarch", {ELF64LEKind
, EM_LOONGARCH
})
204 .Case("elf64_s390", {ELF64BEKind
, EM_S390
})
205 .Default({ELFNoneKind
, EM_NONE
});
207 if (ret
.first
== ELFNoneKind
)
208 error("unknown emulation: " + emul
);
209 if (ret
.second
== EM_MSP430
)
210 osabi
= ELFOSABI_STANDALONE
;
211 else if (ret
.second
== EM_AMDGPU
)
212 osabi
= ELFOSABI_AMDGPU_HSA
;
213 return std::make_tuple(ret
.first
, ret
.second
, osabi
);
216 // Returns slices of MB by parsing MB as an archive file.
217 // Each slice consists of a member file in the archive.
218 std::vector
<std::pair
<MemoryBufferRef
, uint64_t>> static getArchiveMembers(
219 MemoryBufferRef mb
) {
220 std::unique_ptr
<Archive
> file
=
221 CHECK(Archive::create(mb
),
222 mb
.getBufferIdentifier() + ": failed to parse archive");
224 std::vector
<std::pair
<MemoryBufferRef
, uint64_t>> v
;
225 Error err
= Error::success();
226 bool addToTar
= file
->isThin() && tar
;
227 for (const Archive::Child
&c
: file
->children(err
)) {
228 MemoryBufferRef mbref
=
229 CHECK(c
.getMemoryBufferRef(),
230 mb
.getBufferIdentifier() +
231 ": could not get the buffer for a child of the archive");
233 tar
->append(relativeToRoot(check(c
.getFullName())), mbref
.getBuffer());
234 v
.push_back(std::make_pair(mbref
, c
.getChildOffset()));
237 fatal(mb
.getBufferIdentifier() + ": Archive::children failed: " +
238 toString(std::move(err
)));
240 // Take ownership of memory buffers created for members of thin archives.
241 std::vector
<std::unique_ptr
<MemoryBuffer
>> mbs
= file
->takeThinBuffers();
242 std::move(mbs
.begin(), mbs
.end(), std::back_inserter(ctx
.memoryBuffers
));
247 static bool isBitcode(MemoryBufferRef mb
) {
248 return identify_magic(mb
.getBuffer()) == llvm::file_magic::bitcode
;
251 bool LinkerDriver::tryAddFatLTOFile(MemoryBufferRef mb
, StringRef archiveName
,
252 uint64_t offsetInArchive
, bool lazy
) {
253 if (!config
->fatLTOObjects
)
255 Expected
<MemoryBufferRef
> fatLTOData
=
256 IRObjectFile::findBitcodeInMemBuffer(mb
);
257 if (errorToBool(fatLTOData
.takeError()))
260 make
<BitcodeFile
>(*fatLTOData
, archiveName
, offsetInArchive
, lazy
));
264 // Opens a file and create a file object. Path has to be resolved already.
265 void LinkerDriver::addFile(StringRef path
, bool withLOption
) {
266 using namespace sys::fs
;
268 std::optional
<MemoryBufferRef
> buffer
= readFile(path
);
271 MemoryBufferRef mbref
= *buffer
;
273 if (config
->formatBinary
) {
274 files
.push_back(make
<BinaryFile
>(mbref
));
278 switch (identify_magic(mbref
.getBuffer())) {
279 case file_magic::unknown
:
280 readLinkerScript(mbref
);
282 case file_magic::archive
: {
283 auto members
= getArchiveMembers(mbref
);
284 if (inWholeArchive
) {
285 for (const std::pair
<MemoryBufferRef
, uint64_t> &p
: members
) {
286 if (isBitcode(p
.first
))
287 files
.push_back(make
<BitcodeFile
>(p
.first
, path
, p
.second
, false));
288 else if (!tryAddFatLTOFile(p
.first
, path
, p
.second
, false))
289 files
.push_back(createObjFile(p
.first
, path
));
294 archiveFiles
.emplace_back(path
, members
.size());
296 // Handle archives and --start-lib/--end-lib using the same code path. This
297 // scans all the ELF relocatable object files and bitcode files in the
298 // archive rather than just the index file, with the benefit that the
299 // symbols are only loaded once. For many projects archives see high
300 // utilization rates and it is a net performance win. --start-lib scans
301 // symbols in the same order that llvm-ar adds them to the index, so in the
302 // common case the semantics are identical. If the archive symbol table was
303 // created in a different order, or is incomplete, this strategy has
304 // different semantics. Such output differences are considered user error.
306 // All files within the archive get the same group ID to allow mutual
307 // references for --warn-backrefs.
308 bool saved
= InputFile::isInGroup
;
309 InputFile::isInGroup
= true;
310 for (const std::pair
<MemoryBufferRef
, uint64_t> &p
: members
) {
311 auto magic
= identify_magic(p
.first
.getBuffer());
312 if (magic
== file_magic::elf_relocatable
) {
313 if (!tryAddFatLTOFile(p
.first
, path
, p
.second
, true))
314 files
.push_back(createObjFile(p
.first
, path
, true));
315 } else if (magic
== file_magic::bitcode
)
316 files
.push_back(make
<BitcodeFile
>(p
.first
, path
, p
.second
, true));
318 warn(path
+ ": archive member '" + p
.first
.getBufferIdentifier() +
319 "' is neither ET_REL nor LLVM bitcode");
321 InputFile::isInGroup
= saved
;
323 ++InputFile::nextGroupId
;
326 case file_magic::elf_shared_object
: {
327 if (config
->isStatic
) {
328 error("attempted static link of dynamic object " + path
);
332 // Shared objects are identified by soname. soname is (if specified)
333 // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
334 // the directory part is ignored. Note that path may be a temporary and
335 // cannot be stored into SharedFile::soName.
336 path
= mbref
.getBufferIdentifier();
338 make
<SharedFile
>(mbref
, withLOption
? path::filename(path
) : path
);
343 case file_magic::bitcode
:
344 files
.push_back(make
<BitcodeFile
>(mbref
, "", 0, inLib
));
346 case file_magic::elf_relocatable
:
347 if (!tryAddFatLTOFile(mbref
, "", 0, inLib
))
348 files
.push_back(createObjFile(mbref
, "", inLib
));
351 error(path
+ ": unknown file type");
355 // Add a given library by searching it from input search paths.
356 void LinkerDriver::addLibrary(StringRef name
) {
357 if (std::optional
<std::string
> path
= searchLibrary(name
))
358 addFile(saver().save(*path
), /*withLOption=*/true);
360 error("unable to find library -l" + name
, ErrorTag::LibNotFound
, {name
});
363 // This function is called on startup. We need this for LTO since
364 // LTO calls LLVM functions to compile bitcode files to native code.
365 // Technically this can be delayed until we read bitcode files, but
366 // we don't bother to do lazily because the initialization is fast.
367 static void initLLVM() {
368 InitializeAllTargets();
369 InitializeAllTargetMCs();
370 InitializeAllAsmPrinters();
371 InitializeAllAsmParsers();
374 // Some command line options or some combinations of them are not allowed.
375 // This function checks for such errors.
376 static void checkOptions() {
377 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
378 // table which is a relatively new feature.
379 if (config
->emachine
== EM_MIPS
&& config
->gnuHash
)
380 error("the .gnu.hash section is not compatible with the MIPS target");
382 if (config
->emachine
== EM_ARM
) {
383 if (!config
->cmseImplib
) {
384 if (!config
->cmseInputLib
.empty())
385 error("--in-implib may not be used without --cmse-implib");
386 if (!config
->cmseOutputLib
.empty())
387 error("--out-implib may not be used without --cmse-implib");
390 if (config
->cmseImplib
)
391 error("--cmse-implib is only supported on ARM targets");
392 if (!config
->cmseInputLib
.empty())
393 error("--in-implib is only supported on ARM targets");
394 if (!config
->cmseOutputLib
.empty())
395 error("--out-implib is only supported on ARM targets");
398 if (config
->fixCortexA53Errata843419
&& config
->emachine
!= EM_AARCH64
)
399 error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
401 if (config
->fixCortexA8
&& config
->emachine
!= EM_ARM
)
402 error("--fix-cortex-a8 is only supported on ARM targets");
404 if (config
->armBe8
&& config
->emachine
!= EM_ARM
)
405 error("--be8 is only supported on ARM targets");
407 if (config
->fixCortexA8
&& !config
->isLE
)
408 error("--fix-cortex-a8 is not supported on big endian targets");
410 if (config
->tocOptimize
&& config
->emachine
!= EM_PPC64
)
411 error("--toc-optimize is only supported on PowerPC64 targets");
413 if (config
->pcRelOptimize
&& config
->emachine
!= EM_PPC64
)
414 error("--pcrel-optimize is only supported on PowerPC64 targets");
416 if (config
->relaxGP
&& config
->emachine
!= EM_RISCV
)
417 error("--relax-gp is only supported on RISC-V targets");
419 if (config
->pie
&& config
->shared
)
420 error("-shared and -pie may not be used together");
422 if (!config
->shared
&& !config
->filterList
.empty())
423 error("-F may not be used without -shared");
425 if (!config
->shared
&& !config
->auxiliaryList
.empty())
426 error("-f may not be used without -shared");
428 if (config
->strip
== StripPolicy::All
&& config
->emitRelocs
)
429 error("--strip-all and --emit-relocs may not be used together");
431 if (config
->zText
&& config
->zIfuncNoplt
)
432 error("-z text and -z ifunc-noplt may not be used together");
434 if (config
->relocatable
) {
436 error("-r and -shared may not be used together");
437 if (config
->gdbIndex
)
438 error("-r and --gdb-index may not be used together");
439 if (config
->icf
!= ICFLevel::None
)
440 error("-r and --icf may not be used together");
442 error("-r and -pie may not be used together");
443 if (config
->exportDynamic
)
444 error("-r and --export-dynamic may not be used together");
445 if (config
->debugNames
)
446 error("-r and --debug-names may not be used together");
449 if (config
->executeOnly
) {
450 if (config
->emachine
!= EM_AARCH64
)
451 error("--execute-only is only supported on AArch64 targets");
453 if (config
->singleRoRx
&& !script
->hasSectionsCommand
)
454 error("--execute-only and --no-rosegment cannot be used together");
457 if (config
->zRetpolineplt
&& config
->zForceIbt
)
458 error("-z force-ibt may not be used with -z retpolineplt");
460 if (config
->emachine
!= EM_AARCH64
) {
462 error("-z pac-plt only supported on AArch64");
463 if (config
->zForceBti
)
464 error("-z force-bti only supported on AArch64");
465 if (config
->zBtiReport
!= "none")
466 error("-z bti-report only supported on AArch64");
467 if (config
->zPauthReport
!= "none")
468 error("-z pauth-report only supported on AArch64");
469 if (config
->zGcsReport
!= "none")
470 error("-z gcs-report only supported on AArch64");
471 if (config
->zGcs
!= GcsPolicy::Implicit
)
472 error("-z gcs only supported on AArch64");
475 if (config
->emachine
!= EM_386
&& config
->emachine
!= EM_X86_64
&&
476 config
->zCetReport
!= "none")
477 error("-z cet-report only supported on X86 and X86_64");
480 static const char *getReproduceOption(opt::InputArgList
&args
) {
481 if (auto *arg
= args
.getLastArg(OPT_reproduce
))
482 return arg
->getValue();
483 return getenv("LLD_REPRODUCE");
486 static bool hasZOption(opt::InputArgList
&args
, StringRef key
) {
488 for (auto *arg
: args
.filtered(OPT_z
))
489 if (key
== arg
->getValue()) {
496 static bool getZFlag(opt::InputArgList
&args
, StringRef k1
, StringRef k2
,
498 for (auto *arg
: args
.filtered(OPT_z
)) {
499 StringRef v
= arg
->getValue();
503 defaultValue
= false;
511 static SeparateSegmentKind
getZSeparate(opt::InputArgList
&args
) {
512 auto ret
= SeparateSegmentKind::None
;
513 for (auto *arg
: args
.filtered(OPT_z
)) {
514 StringRef v
= arg
->getValue();
515 if (v
== "noseparate-code")
516 ret
= SeparateSegmentKind::None
;
517 else if (v
== "separate-code")
518 ret
= SeparateSegmentKind::Code
;
519 else if (v
== "separate-loadable-segments")
520 ret
= SeparateSegmentKind::Loadable
;
528 static GnuStackKind
getZGnuStack(opt::InputArgList
&args
) {
529 auto ret
= GnuStackKind::NoExec
;
530 for (auto *arg
: args
.filtered(OPT_z
)) {
531 StringRef v
= arg
->getValue();
532 if (v
== "execstack")
533 ret
= GnuStackKind::Exec
;
534 else if (v
== "noexecstack")
535 ret
= GnuStackKind::NoExec
;
536 else if (v
== "nognustack")
537 ret
= GnuStackKind::None
;
545 static uint8_t getZStartStopVisibility(opt::InputArgList
&args
) {
546 uint8_t ret
= STV_PROTECTED
;
547 for (auto *arg
: args
.filtered(OPT_z
)) {
548 std::pair
<StringRef
, StringRef
> kv
= StringRef(arg
->getValue()).split('=');
549 if (kv
.first
== "start-stop-visibility") {
551 if (kv
.second
== "default")
553 else if (kv
.second
== "internal")
555 else if (kv
.second
== "hidden")
557 else if (kv
.second
== "protected")
560 error("unknown -z start-stop-visibility= value: " +
561 StringRef(kv
.second
));
567 static GcsPolicy
getZGcs(opt::InputArgList
&args
) {
568 GcsPolicy ret
= GcsPolicy::Implicit
;
569 for (auto *arg
: args
.filtered(OPT_z
)) {
570 std::pair
<StringRef
, StringRef
> kv
= StringRef(arg
->getValue()).split('=');
571 if (kv
.first
== "gcs") {
573 if (kv
.second
== "implicit")
574 ret
= GcsPolicy::Implicit
;
575 else if (kv
.second
== "never")
576 ret
= GcsPolicy::Never
;
577 else if (kv
.second
== "always")
578 ret
= GcsPolicy::Always
;
580 error("unknown -z gcs= value: " + kv
.second
);
586 // Report a warning for an unknown -z option.
587 static void checkZOptions(opt::InputArgList
&args
) {
588 // This function is called before getTarget(), when certain options are not
589 // initialized yet. Claim them here.
590 args::getZOptionValue(args
, OPT_z
, "max-page-size", 0);
591 args::getZOptionValue(args
, OPT_z
, "common-page-size", 0);
592 getZFlag(args
, "rel", "rela", false);
593 for (auto *arg
: args
.filtered(OPT_z
))
594 if (!arg
->isClaimed())
595 warn("unknown -z value: " + StringRef(arg
->getValue()));
598 constexpr const char *saveTempsValues
[] = {
599 "resolution", "preopt", "promote", "internalize", "import",
600 "opt", "precodegen", "prelink", "combinedindex"};
602 void LinkerDriver::linkerMain(ArrayRef
<const char *> argsArr
) {
604 opt::InputArgList args
= parser
.parse(argsArr
.slice(1));
606 // Interpret these flags early because error()/warn() depend on them.
607 errorHandler().errorLimit
= args::getInteger(args
, OPT_error_limit
, 20);
608 errorHandler().fatalWarnings
=
609 args
.hasFlag(OPT_fatal_warnings
, OPT_no_fatal_warnings
, false) &&
610 !args
.hasArg(OPT_no_warnings
);
611 errorHandler().suppressWarnings
= args
.hasArg(OPT_no_warnings
);
614 if (args
.hasArg(OPT_help
)) {
619 // Handle -v or -version.
621 // A note about "compatible with GNU linkers" message: this is a hack for
622 // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
623 // a GNU compatible linker. See
624 // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
626 // This is somewhat ugly hack, but in reality, we had no choice other
627 // than doing this. Considering the very long release cycle of Libtool,
628 // it is not easy to improve it to recognize LLD as a GNU compatible
629 // linker in a timely manner. Even if we can make it, there are still a
630 // lot of "configure" scripts out there that are generated by old version
631 // of Libtool. We cannot convince every software developer to migrate to
632 // the latest version and re-generate scripts. So we have this hack.
633 if (args
.hasArg(OPT_v
) || args
.hasArg(OPT_version
))
634 message(getLLDVersion() + ", compatible with GNU linkers");
636 if (const char *path
= getReproduceOption(args
)) {
637 // Note that --reproduce is a debug option so you can ignore it
638 // if you are trying to understand the whole picture of the code.
639 Expected
<std::unique_ptr
<TarWriter
>> errOrWriter
=
640 TarWriter::create(path
, path::stem(path
));
642 tar
= std::move(*errOrWriter
);
643 tar
->append("response.txt", createResponseFile(args
));
644 tar
->append("version.txt", getLLDVersion() + "\n");
645 StringRef ltoSampleProfile
= args
.getLastArgValue(OPT_lto_sample_profile
);
646 if (!ltoSampleProfile
.empty())
647 readFile(ltoSampleProfile
);
649 error("--reproduce: " + toString(errOrWriter
.takeError()));
656 // The behavior of -v or --version is a bit strange, but this is
657 // needed for compatibility with GNU linkers.
658 if (args
.hasArg(OPT_v
) && !args
.hasArg(OPT_INPUT
))
660 if (args
.hasArg(OPT_version
))
663 // Initialize time trace profiler.
664 if (config
->timeTraceEnabled
)
665 timeTraceProfilerInitialize(config
->timeTraceGranularity
, config
->progName
);
668 llvm::TimeTraceScope
timeScope("ExecuteLinker");
681 invokeELFT(link
, args
);
684 if (config
->timeTraceEnabled
) {
685 checkError(timeTraceProfilerWrite(
686 args
.getLastArgValue(OPT_time_trace_eq
).str(), config
->outputFile
));
687 timeTraceProfilerCleanup();
691 static std::string
getRpath(opt::InputArgList
&args
) {
692 SmallVector
<StringRef
, 0> v
= args::getStrings(args
, OPT_rpath
);
693 return llvm::join(v
.begin(), v
.end(), ":");
696 // Determines what we should do if there are remaining unresolved
697 // symbols after the name resolution.
698 static void setUnresolvedSymbolPolicy(opt::InputArgList
&args
) {
699 UnresolvedPolicy errorOrWarn
= args
.hasFlag(OPT_error_unresolved_symbols
,
700 OPT_warn_unresolved_symbols
, true)
701 ? UnresolvedPolicy::ReportError
702 : UnresolvedPolicy::Warn
;
703 // -shared implies --unresolved-symbols=ignore-all because missing
704 // symbols are likely to be resolved at runtime.
705 bool diagRegular
= !config
->shared
, diagShlib
= !config
->shared
;
707 for (const opt::Arg
*arg
: args
) {
708 switch (arg
->getOption().getID()) {
709 case OPT_unresolved_symbols
: {
710 StringRef s
= arg
->getValue();
711 if (s
== "ignore-all") {
714 } else if (s
== "ignore-in-object-files") {
717 } else if (s
== "ignore-in-shared-libs") {
720 } else if (s
== "report-all") {
724 error("unknown --unresolved-symbols value: " + s
);
728 case OPT_no_undefined
:
732 if (StringRef(arg
->getValue()) == "defs")
734 else if (StringRef(arg
->getValue()) == "undefs")
740 case OPT_allow_shlib_undefined
:
743 case OPT_no_allow_shlib_undefined
:
749 config
->unresolvedSymbols
=
750 diagRegular
? errorOrWarn
: UnresolvedPolicy::Ignore
;
751 config
->unresolvedSymbolsInShlib
=
752 diagShlib
? errorOrWarn
: UnresolvedPolicy::Ignore
;
755 static Target2Policy
getTarget2(opt::InputArgList
&args
) {
756 StringRef s
= args
.getLastArgValue(OPT_target2
, "got-rel");
758 return Target2Policy::Rel
;
760 return Target2Policy::Abs
;
762 return Target2Policy::GotRel
;
763 error("unknown --target2 option: " + s
);
764 return Target2Policy::GotRel
;
767 static bool isOutputFormatBinary(opt::InputArgList
&args
) {
768 StringRef s
= args
.getLastArgValue(OPT_oformat
, "elf");
771 if (!s
.starts_with("elf"))
772 error("unknown --oformat value: " + s
);
776 static DiscardPolicy
getDiscard(opt::InputArgList
&args
) {
778 args
.getLastArg(OPT_discard_all
, OPT_discard_locals
, OPT_discard_none
);
780 return DiscardPolicy::Default
;
781 if (arg
->getOption().getID() == OPT_discard_all
)
782 return DiscardPolicy::All
;
783 if (arg
->getOption().getID() == OPT_discard_locals
)
784 return DiscardPolicy::Locals
;
785 return DiscardPolicy::None
;
788 static StringRef
getDynamicLinker(opt::InputArgList
&args
) {
789 auto *arg
= args
.getLastArg(OPT_dynamic_linker
, OPT_no_dynamic_linker
);
792 if (arg
->getOption().getID() == OPT_no_dynamic_linker
) {
793 // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
794 config
->noDynamicLinker
= true;
797 return arg
->getValue();
800 static int getMemtagMode(opt::InputArgList
&args
) {
801 StringRef memtagModeArg
= args
.getLastArgValue(OPT_android_memtag_mode
);
802 if (memtagModeArg
.empty()) {
803 if (config
->androidMemtagStack
)
804 warn("--android-memtag-mode is unspecified, leaving "
805 "--android-memtag-stack a no-op");
806 else if (config
->androidMemtagHeap
)
807 warn("--android-memtag-mode is unspecified, leaving "
808 "--android-memtag-heap a no-op");
809 return ELF::NT_MEMTAG_LEVEL_NONE
;
812 if (memtagModeArg
== "sync")
813 return ELF::NT_MEMTAG_LEVEL_SYNC
;
814 if (memtagModeArg
== "async")
815 return ELF::NT_MEMTAG_LEVEL_ASYNC
;
816 if (memtagModeArg
== "none")
817 return ELF::NT_MEMTAG_LEVEL_NONE
;
819 error("unknown --android-memtag-mode value: \"" + memtagModeArg
+
820 "\", should be one of {async, sync, none}");
821 return ELF::NT_MEMTAG_LEVEL_NONE
;
824 static ICFLevel
getICF(opt::InputArgList
&args
) {
825 auto *arg
= args
.getLastArg(OPT_icf_none
, OPT_icf_safe
, OPT_icf_all
);
826 if (!arg
|| arg
->getOption().getID() == OPT_icf_none
)
827 return ICFLevel::None
;
828 if (arg
->getOption().getID() == OPT_icf_safe
)
829 return ICFLevel::Safe
;
830 return ICFLevel::All
;
833 static StripPolicy
getStrip(opt::InputArgList
&args
) {
834 if (args
.hasArg(OPT_relocatable
))
835 return StripPolicy::None
;
837 auto *arg
= args
.getLastArg(OPT_strip_all
, OPT_strip_debug
);
839 return StripPolicy::None
;
840 if (arg
->getOption().getID() == OPT_strip_all
)
841 return StripPolicy::All
;
842 return StripPolicy::Debug
;
845 static uint64_t parseSectionAddress(StringRef s
, opt::InputArgList
&args
,
846 const opt::Arg
&arg
) {
848 if (s
.starts_with("0x"))
850 if (!to_integer(s
, va
, 16))
851 error("invalid argument: " + arg
.getAsString(args
));
855 static StringMap
<uint64_t> getSectionStartMap(opt::InputArgList
&args
) {
856 StringMap
<uint64_t> ret
;
857 for (auto *arg
: args
.filtered(OPT_section_start
)) {
860 std::tie(name
, addr
) = StringRef(arg
->getValue()).split('=');
861 ret
[name
] = parseSectionAddress(addr
, args
, *arg
);
864 if (auto *arg
= args
.getLastArg(OPT_Ttext
))
865 ret
[".text"] = parseSectionAddress(arg
->getValue(), args
, *arg
);
866 if (auto *arg
= args
.getLastArg(OPT_Tdata
))
867 ret
[".data"] = parseSectionAddress(arg
->getValue(), args
, *arg
);
868 if (auto *arg
= args
.getLastArg(OPT_Tbss
))
869 ret
[".bss"] = parseSectionAddress(arg
->getValue(), args
, *arg
);
873 static SortSectionPolicy
getSortSection(opt::InputArgList
&args
) {
874 StringRef s
= args
.getLastArgValue(OPT_sort_section
);
875 if (s
== "alignment")
876 return SortSectionPolicy::Alignment
;
878 return SortSectionPolicy::Name
;
880 error("unknown --sort-section rule: " + s
);
881 return SortSectionPolicy::Default
;
884 static OrphanHandlingPolicy
getOrphanHandling(opt::InputArgList
&args
) {
885 StringRef s
= args
.getLastArgValue(OPT_orphan_handling
, "place");
887 return OrphanHandlingPolicy::Warn
;
889 return OrphanHandlingPolicy::Error
;
891 error("unknown --orphan-handling mode: " + s
);
892 return OrphanHandlingPolicy::Place
;
895 // Parse --build-id or --build-id=<style>. We handle "tree" as a
896 // synonym for "sha1" because all our hash functions including
897 // --build-id=sha1 are actually tree hashes for performance reasons.
898 static std::pair
<BuildIdKind
, SmallVector
<uint8_t, 0>>
899 getBuildId(opt::InputArgList
&args
) {
900 auto *arg
= args
.getLastArg(OPT_build_id
);
902 return {BuildIdKind::None
, {}};
904 StringRef s
= arg
->getValue();
906 return {BuildIdKind::Fast
, {}};
908 return {BuildIdKind::Md5
, {}};
909 if (s
== "sha1" || s
== "tree")
910 return {BuildIdKind::Sha1
, {}};
912 return {BuildIdKind::Uuid
, {}};
913 if (s
.starts_with("0x"))
914 return {BuildIdKind::Hexstring
, parseHex(s
.substr(2))};
917 error("unknown --build-id style: " + s
);
918 return {BuildIdKind::None
, {}};
921 static std::pair
<bool, bool> getPackDynRelocs(opt::InputArgList
&args
) {
922 StringRef s
= args
.getLastArgValue(OPT_pack_dyn_relocs
, "none");
924 return {true, false};
926 return {false, true};
927 if (s
== "android+relr")
931 error("unknown --pack-dyn-relocs format: " + s
);
932 return {false, false};
935 static void readCallGraph(MemoryBufferRef mb
) {
936 // Build a map from symbol name to section
937 DenseMap
<StringRef
, Symbol
*> map
;
938 for (ELFFileBase
*file
: ctx
.objectFiles
)
939 for (Symbol
*sym
: file
->getSymbols())
940 map
[sym
->getName()] = sym
;
942 auto findSection
= [&](StringRef name
) -> InputSectionBase
* {
943 Symbol
*sym
= map
.lookup(name
);
945 if (config
->warnSymbolOrdering
)
946 warn(mb
.getBufferIdentifier() + ": no such symbol: " + name
);
949 maybeWarnUnorderableSymbol(sym
);
951 if (Defined
*dr
= dyn_cast_or_null
<Defined
>(sym
))
952 return dyn_cast_or_null
<InputSectionBase
>(dr
->section
);
956 for (StringRef line
: args::getLines(mb
)) {
957 SmallVector
<StringRef
, 3> fields
;
958 line
.split(fields
, ' ');
961 if (fields
.size() != 3 || !to_integer(fields
[2], count
)) {
962 error(mb
.getBufferIdentifier() + ": parse error");
966 if (InputSectionBase
*from
= findSection(fields
[0]))
967 if (InputSectionBase
*to
= findSection(fields
[1]))
968 config
->callGraphProfile
[std::make_pair(from
, to
)] += count
;
972 // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
973 // true and populates cgProfile and symbolIndices.
974 template <class ELFT
>
976 processCallGraphRelocations(SmallVector
<uint32_t, 32> &symbolIndices
,
977 ArrayRef
<typename
ELFT::CGProfile
> &cgProfile
,
978 ObjFile
<ELFT
> *inputObj
) {
979 if (inputObj
->cgProfileSectionIndex
== SHN_UNDEF
)
982 ArrayRef
<Elf_Shdr_Impl
<ELFT
>> objSections
=
983 inputObj
->template getELFShdrs
<ELFT
>();
984 symbolIndices
.clear();
985 const ELFFile
<ELFT
> &obj
= inputObj
->getObj();
987 check(obj
.template getSectionContentsAsArray
<typename
ELFT::CGProfile
>(
988 objSections
[inputObj
->cgProfileSectionIndex
]));
990 for (size_t i
= 0, e
= objSections
.size(); i
< e
; ++i
) {
991 const Elf_Shdr_Impl
<ELFT
> &sec
= objSections
[i
];
992 if (sec
.sh_info
== inputObj
->cgProfileSectionIndex
) {
993 if (sec
.sh_type
== SHT_RELA
) {
994 ArrayRef
<typename
ELFT::Rela
> relas
=
995 CHECK(obj
.relas(sec
), "could not retrieve cg profile rela section");
996 for (const typename
ELFT::Rela
&rel
: relas
)
997 symbolIndices
.push_back(rel
.getSymbol(config
->isMips64EL
));
1000 if (sec
.sh_type
== SHT_REL
) {
1001 ArrayRef
<typename
ELFT::Rel
> rels
=
1002 CHECK(obj
.rels(sec
), "could not retrieve cg profile rel section");
1003 for (const typename
ELFT::Rel
&rel
: rels
)
1004 symbolIndices
.push_back(rel
.getSymbol(config
->isMips64EL
));
1009 if (symbolIndices
.empty())
1010 warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");
1011 return !symbolIndices
.empty();
1014 template <class ELFT
> static void readCallGraphsFromObjectFiles() {
1015 SmallVector
<uint32_t, 32> symbolIndices
;
1016 ArrayRef
<typename
ELFT::CGProfile
> cgProfile
;
1017 for (auto file
: ctx
.objectFiles
) {
1018 auto *obj
= cast
<ObjFile
<ELFT
>>(file
);
1019 if (!processCallGraphRelocations(symbolIndices
, cgProfile
, obj
))
1022 if (symbolIndices
.size() != cgProfile
.size() * 2)
1023 fatal("number of relocations doesn't match Weights");
1025 for (uint32_t i
= 0, size
= cgProfile
.size(); i
< size
; ++i
) {
1026 const Elf_CGProfile_Impl
<ELFT
> &cgpe
= cgProfile
[i
];
1027 uint32_t fromIndex
= symbolIndices
[i
* 2];
1028 uint32_t toIndex
= symbolIndices
[i
* 2 + 1];
1029 auto *fromSym
= dyn_cast
<Defined
>(&obj
->getSymbol(fromIndex
));
1030 auto *toSym
= dyn_cast
<Defined
>(&obj
->getSymbol(toIndex
));
1031 if (!fromSym
|| !toSym
)
1034 auto *from
= dyn_cast_or_null
<InputSectionBase
>(fromSym
->section
);
1035 auto *to
= dyn_cast_or_null
<InputSectionBase
>(toSym
->section
);
1037 config
->callGraphProfile
[{from
, to
}] += cgpe
.cgp_weight
;
1042 template <class ELFT
>
1043 static void ltoValidateAllVtablesHaveTypeInfos(opt::InputArgList
&args
) {
1044 DenseSet
<StringRef
> typeInfoSymbols
;
1045 SmallSetVector
<StringRef
, 0> vtableSymbols
;
1046 auto processVtableAndTypeInfoSymbols
= [&](StringRef name
) {
1047 if (name
.consume_front("_ZTI"))
1048 typeInfoSymbols
.insert(name
);
1049 else if (name
.consume_front("_ZTV"))
1050 vtableSymbols
.insert(name
);
1053 // Examine all native symbol tables.
1054 for (ELFFileBase
*f
: ctx
.objectFiles
) {
1055 using Elf_Sym
= typename
ELFT::Sym
;
1056 for (const Elf_Sym
&s
: f
->template getGlobalELFSyms
<ELFT
>()) {
1057 if (s
.st_shndx
!= SHN_UNDEF
) {
1058 StringRef name
= check(s
.getName(f
->getStringTable()));
1059 processVtableAndTypeInfoSymbols(name
);
1064 for (SharedFile
*f
: ctx
.sharedFiles
) {
1065 using Elf_Sym
= typename
ELFT::Sym
;
1066 for (const Elf_Sym
&s
: f
->template getELFSyms
<ELFT
>()) {
1067 if (s
.st_shndx
!= SHN_UNDEF
) {
1068 StringRef name
= check(s
.getName(f
->getStringTable()));
1069 processVtableAndTypeInfoSymbols(name
);
1074 SmallSetVector
<StringRef
, 0> vtableSymbolsWithNoRTTI
;
1075 for (StringRef s
: vtableSymbols
)
1076 if (!typeInfoSymbols
.count(s
))
1077 vtableSymbolsWithNoRTTI
.insert(s
);
1079 // Remove known safe symbols.
1080 for (auto *arg
: args
.filtered(OPT_lto_known_safe_vtables
)) {
1081 StringRef knownSafeName
= arg
->getValue();
1082 if (!knownSafeName
.consume_front("_ZTV"))
1083 error("--lto-known-safe-vtables=: expected symbol to start with _ZTV, "
1086 Expected
<GlobPattern
> pat
= GlobPattern::create(knownSafeName
);
1088 error("--lto-known-safe-vtables=: " + toString(pat
.takeError()));
1089 vtableSymbolsWithNoRTTI
.remove_if(
1090 [&](StringRef s
) { return pat
->match(s
); });
1093 ctx
.ltoAllVtablesHaveTypeInfos
= vtableSymbolsWithNoRTTI
.empty();
1094 // Check for unmatched RTTI symbols
1095 for (StringRef s
: vtableSymbolsWithNoRTTI
) {
1097 "--lto-validate-all-vtables-have-type-infos: RTTI missing for vtable "
1099 s
+ ", --lto-whole-program-visibility disabled");
1103 static CGProfileSortKind
getCGProfileSortKind(opt::InputArgList
&args
) {
1104 StringRef s
= args
.getLastArgValue(OPT_call_graph_profile_sort
, "cdsort");
1106 return CGProfileSortKind::Hfsort
;
1108 return CGProfileSortKind::Cdsort
;
1110 error("unknown --call-graph-profile-sort= value: " + s
);
1111 return CGProfileSortKind::None
;
1114 static DebugCompressionType
getCompressionType(StringRef s
, StringRef option
) {
1115 DebugCompressionType type
= StringSwitch
<DebugCompressionType
>(s
)
1116 .Case("zlib", DebugCompressionType::Zlib
)
1117 .Case("zstd", DebugCompressionType::Zstd
)
1118 .Default(DebugCompressionType::None
);
1119 if (type
== DebugCompressionType::None
) {
1121 error("unknown " + option
+ " value: " + s
);
1122 } else if (const char *reason
= compression::getReasonIfUnsupported(
1123 compression::formatFor(type
))) {
1124 error(option
+ ": " + reason
);
1129 static StringRef
getAliasSpelling(opt::Arg
*arg
) {
1130 if (const opt::Arg
*alias
= arg
->getAlias())
1131 return alias
->getSpelling();
1132 return arg
->getSpelling();
1135 static std::pair
<StringRef
, StringRef
> getOldNewOptions(opt::InputArgList
&args
,
1137 auto *arg
= args
.getLastArg(id
);
1141 StringRef s
= arg
->getValue();
1142 std::pair
<StringRef
, StringRef
> ret
= s
.split(';');
1143 if (ret
.second
.empty())
1144 error(getAliasSpelling(arg
) + " expects 'old;new' format, but got " + s
);
1148 // Parse options of the form "old;new[;extra]".
1149 static std::tuple
<StringRef
, StringRef
, StringRef
>
1150 getOldNewOptionsExtra(opt::InputArgList
&args
, unsigned id
) {
1151 auto [oldDir
, second
] = getOldNewOptions(args
, id
);
1152 auto [newDir
, extraDir
] = second
.split(';');
1153 return {oldDir
, newDir
, extraDir
};
1156 // Parse the symbol ordering file and warn for any duplicate entries.
1157 static SmallVector
<StringRef
, 0> getSymbolOrderingFile(MemoryBufferRef mb
) {
1158 SetVector
<StringRef
, SmallVector
<StringRef
, 0>> names
;
1159 for (StringRef s
: args::getLines(mb
))
1160 if (!names
.insert(s
) && config
->warnSymbolOrdering
)
1161 warn(mb
.getBufferIdentifier() + ": duplicate ordered symbol: " + s
);
1163 return names
.takeVector();
1166 static bool getIsRela(opt::InputArgList
&args
) {
1167 // The psABI specifies the default relocation entry format.
1168 bool rela
= is_contained({EM_AARCH64
, EM_AMDGPU
, EM_HEXAGON
, EM_LOONGARCH
,
1169 EM_PPC
, EM_PPC64
, EM_RISCV
, EM_S390
, EM_X86_64
},
1171 // If -z rel or -z rela is specified, use the last option.
1172 for (auto *arg
: args
.filtered(OPT_z
)) {
1173 StringRef
s(arg
->getValue());
1176 else if (s
== "rela")
1185 static void parseClangOption(StringRef opt
, const Twine
&msg
) {
1187 raw_string_ostream
os(err
);
1189 const char *argv
[] = {config
->progName
.data(), opt
.data()};
1190 if (cl::ParseCommandLineOptions(2, argv
, "", &os
))
1193 error(msg
+ ": " + StringRef(err
).trim());
1196 // Checks the parameter of the bti-report and cet-report options.
1197 static bool isValidReportString(StringRef arg
) {
1198 return arg
== "none" || arg
== "warning" || arg
== "error";
1201 // Process a remap pattern 'from-glob=to-file'.
1202 static bool remapInputs(StringRef line
, const Twine
&location
) {
1203 SmallVector
<StringRef
, 0> fields
;
1204 line
.split(fields
, '=');
1205 if (fields
.size() != 2 || fields
[1].empty()) {
1206 error(location
+ ": parse error, not 'from-glob=to-file'");
1209 if (!hasWildcard(fields
[0]))
1210 config
->remapInputs
[fields
[0]] = fields
[1];
1211 else if (Expected
<GlobPattern
> pat
= GlobPattern::create(fields
[0]))
1212 config
->remapInputsWildcards
.emplace_back(std::move(*pat
), fields
[1]);
1214 error(location
+ ": " + toString(pat
.takeError()) + ": " + fields
[0]);
1220 // Initializes Config members by the command line options.
1221 static void readConfigs(opt::InputArgList
&args
) {
1222 errorHandler().verbose
= args
.hasArg(OPT_verbose
);
1223 errorHandler().vsDiagnostics
=
1224 args
.hasArg(OPT_visual_studio_diagnostics_format
, false);
1226 config
->allowMultipleDefinition
=
1227 hasZOption(args
, "muldefs") ||
1228 args
.hasFlag(OPT_allow_multiple_definition
,
1229 OPT_no_allow_multiple_definition
, false);
1230 config
->androidMemtagHeap
=
1231 args
.hasFlag(OPT_android_memtag_heap
, OPT_no_android_memtag_heap
, false);
1232 config
->androidMemtagStack
= args
.hasFlag(OPT_android_memtag_stack
,
1233 OPT_no_android_memtag_stack
, false);
1234 config
->fatLTOObjects
=
1235 args
.hasFlag(OPT_fat_lto_objects
, OPT_no_fat_lto_objects
, false);
1236 config
->androidMemtagMode
= getMemtagMode(args
);
1237 config
->auxiliaryList
= args::getStrings(args
, OPT_auxiliary
);
1238 config
->armBe8
= args
.hasArg(OPT_be8
);
1239 if (opt::Arg
*arg
= args
.getLastArg(
1240 OPT_Bno_symbolic
, OPT_Bsymbolic_non_weak_functions
,
1241 OPT_Bsymbolic_functions
, OPT_Bsymbolic_non_weak
, OPT_Bsymbolic
)) {
1242 if (arg
->getOption().matches(OPT_Bsymbolic_non_weak_functions
))
1243 config
->bsymbolic
= BsymbolicKind::NonWeakFunctions
;
1244 else if (arg
->getOption().matches(OPT_Bsymbolic_functions
))
1245 config
->bsymbolic
= BsymbolicKind::Functions
;
1246 else if (arg
->getOption().matches(OPT_Bsymbolic_non_weak
))
1247 config
->bsymbolic
= BsymbolicKind::NonWeak
;
1248 else if (arg
->getOption().matches(OPT_Bsymbolic
))
1249 config
->bsymbolic
= BsymbolicKind::All
;
1251 config
->callGraphProfileSort
= getCGProfileSortKind(args
);
1252 config
->checkSections
=
1253 args
.hasFlag(OPT_check_sections
, OPT_no_check_sections
, true);
1254 config
->chroot
= args
.getLastArgValue(OPT_chroot
);
1255 if (auto *arg
= args
.getLastArg(OPT_compress_debug_sections
)) {
1256 config
->compressDebugSections
=
1257 getCompressionType(arg
->getValue(), "--compress-debug-sections");
1259 config
->cref
= args
.hasArg(OPT_cref
);
1260 config
->optimizeBBJumps
=
1261 args
.hasFlag(OPT_optimize_bb_jumps
, OPT_no_optimize_bb_jumps
, false);
1262 config
->debugNames
= args
.hasFlag(OPT_debug_names
, OPT_no_debug_names
, false);
1263 config
->demangle
= args
.hasFlag(OPT_demangle
, OPT_no_demangle
, true);
1264 config
->dependencyFile
= args
.getLastArgValue(OPT_dependency_file
);
1265 config
->dependentLibraries
= args
.hasFlag(OPT_dependent_libraries
, OPT_no_dependent_libraries
, true);
1266 config
->disableVerify
= args
.hasArg(OPT_disable_verify
);
1267 config
->discard
= getDiscard(args
);
1268 config
->dwoDir
= args
.getLastArgValue(OPT_plugin_opt_dwo_dir_eq
);
1269 config
->dynamicLinker
= getDynamicLinker(args
);
1270 config
->ehFrameHdr
=
1271 args
.hasFlag(OPT_eh_frame_hdr
, OPT_no_eh_frame_hdr
, false);
1272 config
->emitLLVM
= args
.hasArg(OPT_lto_emit_llvm
);
1273 config
->emitRelocs
= args
.hasArg(OPT_emit_relocs
);
1274 config
->enableNewDtags
=
1275 args
.hasFlag(OPT_enable_new_dtags
, OPT_disable_new_dtags
, true);
1276 config
->enableNonContiguousRegions
=
1277 args
.hasArg(OPT_enable_non_contiguous_regions
);
1278 config
->entry
= args
.getLastArgValue(OPT_entry
);
1280 errorHandler().errorHandlingScript
=
1281 args
.getLastArgValue(OPT_error_handling_script
);
1283 config
->executeOnly
=
1284 args
.hasFlag(OPT_execute_only
, OPT_no_execute_only
, false);
1285 config
->exportDynamic
=
1286 args
.hasFlag(OPT_export_dynamic
, OPT_no_export_dynamic
, false) ||
1287 args
.hasArg(OPT_shared
);
1288 config
->filterList
= args::getStrings(args
, OPT_filter
);
1289 config
->fini
= args
.getLastArgValue(OPT_fini
, "_fini");
1290 config
->fixCortexA53Errata843419
= args
.hasArg(OPT_fix_cortex_a53_843419
) &&
1291 !args
.hasArg(OPT_relocatable
);
1292 config
->cmseImplib
= args
.hasArg(OPT_cmse_implib
);
1293 config
->cmseInputLib
= args
.getLastArgValue(OPT_in_implib
);
1294 config
->cmseOutputLib
= args
.getLastArgValue(OPT_out_implib
);
1295 config
->fixCortexA8
=
1296 args
.hasArg(OPT_fix_cortex_a8
) && !args
.hasArg(OPT_relocatable
);
1297 config
->fortranCommon
=
1298 args
.hasFlag(OPT_fortran_common
, OPT_no_fortran_common
, false);
1299 config
->gcSections
= args
.hasFlag(OPT_gc_sections
, OPT_no_gc_sections
, false);
1300 config
->gnuUnique
= args
.hasFlag(OPT_gnu_unique
, OPT_no_gnu_unique
, true);
1301 config
->gdbIndex
= args
.hasFlag(OPT_gdb_index
, OPT_no_gdb_index
, false);
1302 config
->icf
= getICF(args
);
1303 config
->ignoreDataAddressEquality
=
1304 args
.hasArg(OPT_ignore_data_address_equality
);
1305 config
->ignoreFunctionAddressEquality
=
1306 args
.hasArg(OPT_ignore_function_address_equality
);
1307 config
->init
= args
.getLastArgValue(OPT_init
, "_init");
1308 config
->ltoAAPipeline
= args
.getLastArgValue(OPT_lto_aa_pipeline
);
1309 config
->ltoCSProfileGenerate
= args
.hasArg(OPT_lto_cs_profile_generate
);
1310 config
->ltoCSProfileFile
= args
.getLastArgValue(OPT_lto_cs_profile_file
);
1311 config
->ltoPGOWarnMismatch
= args
.hasFlag(OPT_lto_pgo_warn_mismatch
,
1312 OPT_no_lto_pgo_warn_mismatch
, true);
1313 config
->ltoDebugPassManager
= args
.hasArg(OPT_lto_debug_pass_manager
);
1314 config
->ltoEmitAsm
= args
.hasArg(OPT_lto_emit_asm
);
1315 config
->ltoNewPmPasses
= args
.getLastArgValue(OPT_lto_newpm_passes
);
1316 config
->ltoWholeProgramVisibility
=
1317 args
.hasFlag(OPT_lto_whole_program_visibility
,
1318 OPT_no_lto_whole_program_visibility
, false);
1319 config
->ltoValidateAllVtablesHaveTypeInfos
=
1320 args
.hasFlag(OPT_lto_validate_all_vtables_have_type_infos
,
1321 OPT_no_lto_validate_all_vtables_have_type_infos
, false);
1322 config
->ltoo
= args::getInteger(args
, OPT_lto_O
, 2);
1323 if (config
->ltoo
> 3)
1324 error("invalid optimization level for LTO: " + Twine(config
->ltoo
));
1326 args::getInteger(args
, OPT_lto_CGO
, args::getCGOptLevel(config
->ltoo
));
1327 if (auto level
= CodeGenOpt::getLevel(ltoCgo
))
1328 config
->ltoCgo
= *level
;
1330 error("invalid codegen optimization level for LTO: " + Twine(ltoCgo
));
1331 config
->ltoObjPath
= args
.getLastArgValue(OPT_lto_obj_path_eq
);
1332 config
->ltoPartitions
= args::getInteger(args
, OPT_lto_partitions
, 1);
1333 config
->ltoSampleProfile
= args
.getLastArgValue(OPT_lto_sample_profile
);
1334 config
->ltoBBAddrMap
=
1335 args
.hasFlag(OPT_lto_basic_block_address_map
,
1336 OPT_no_lto_basic_block_address_map
, false);
1337 config
->ltoBasicBlockSections
=
1338 args
.getLastArgValue(OPT_lto_basic_block_sections
);
1339 config
->ltoUniqueBasicBlockSectionNames
=
1340 args
.hasFlag(OPT_lto_unique_basic_block_section_names
,
1341 OPT_no_lto_unique_basic_block_section_names
, false);
1342 config
->mapFile
= args
.getLastArgValue(OPT_Map
);
1343 config
->mipsGotSize
= args::getInteger(args
, OPT_mips_got_size
, 0xfff0);
1344 config
->mergeArmExidx
=
1345 args
.hasFlag(OPT_merge_exidx_entries
, OPT_no_merge_exidx_entries
, true);
1346 config
->mmapOutputFile
=
1347 args
.hasFlag(OPT_mmap_output_file
, OPT_no_mmap_output_file
, true);
1348 config
->nmagic
= args
.hasFlag(OPT_nmagic
, OPT_no_nmagic
, false);
1349 config
->noinhibitExec
= args
.hasArg(OPT_noinhibit_exec
);
1350 config
->nostdlib
= args
.hasArg(OPT_nostdlib
);
1351 config
->oFormatBinary
= isOutputFormatBinary(args
);
1352 config
->omagic
= args
.hasFlag(OPT_omagic
, OPT_no_omagic
, false);
1353 config
->optRemarksFilename
= args
.getLastArgValue(OPT_opt_remarks_filename
);
1354 config
->optStatsFilename
= args
.getLastArgValue(OPT_plugin_opt_stats_file
);
1356 // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1357 if (auto *arg
= args
.getLastArg(OPT_opt_remarks_hotness_threshold
)) {
1358 auto resultOrErr
= remarks::parseHotnessThresholdOption(arg
->getValue());
1360 error(arg
->getSpelling() + ": invalid argument '" + arg
->getValue() +
1361 "', only integer or 'auto' is supported");
1363 config
->optRemarksHotnessThreshold
= *resultOrErr
;
1366 config
->optRemarksPasses
= args
.getLastArgValue(OPT_opt_remarks_passes
);
1367 config
->optRemarksWithHotness
= args
.hasArg(OPT_opt_remarks_with_hotness
);
1368 config
->optRemarksFormat
= args
.getLastArgValue(OPT_opt_remarks_format
);
1369 config
->optimize
= args::getInteger(args
, OPT_O
, 1);
1370 config
->orphanHandling
= getOrphanHandling(args
);
1371 config
->outputFile
= args
.getLastArgValue(OPT_o
);
1372 config
->packageMetadata
= args
.getLastArgValue(OPT_package_metadata
);
1373 config
->pie
= args
.hasFlag(OPT_pie
, OPT_no_pie
, false);
1374 config
->printIcfSections
=
1375 args
.hasFlag(OPT_print_icf_sections
, OPT_no_print_icf_sections
, false);
1376 config
->printGcSections
=
1377 args
.hasFlag(OPT_print_gc_sections
, OPT_no_print_gc_sections
, false);
1378 config
->printMemoryUsage
= args
.hasArg(OPT_print_memory_usage
);
1379 config
->printArchiveStats
= args
.getLastArgValue(OPT_print_archive_stats
);
1380 config
->printSymbolOrder
=
1381 args
.getLastArgValue(OPT_print_symbol_order
);
1382 config
->rejectMismatch
= !args
.hasArg(OPT_no_warn_mismatch
);
1383 config
->relax
= args
.hasFlag(OPT_relax
, OPT_no_relax
, true);
1384 config
->relaxGP
= args
.hasFlag(OPT_relax_gp
, OPT_no_relax_gp
, false);
1385 config
->rpath
= getRpath(args
);
1386 config
->relocatable
= args
.hasArg(OPT_relocatable
);
1387 config
->resolveGroups
=
1388 !args
.hasArg(OPT_relocatable
) || args
.hasArg(OPT_force_group_allocation
);
1390 if (args
.hasArg(OPT_save_temps
)) {
1391 // --save-temps implies saving all temps.
1392 for (const char *s
: saveTempsValues
)
1393 config
->saveTempsArgs
.insert(s
);
1395 for (auto *arg
: args
.filtered(OPT_save_temps_eq
)) {
1396 StringRef s
= arg
->getValue();
1397 if (llvm::is_contained(saveTempsValues
, s
))
1398 config
->saveTempsArgs
.insert(s
);
1400 error("unknown --save-temps value: " + s
);
1404 config
->searchPaths
= args::getStrings(args
, OPT_library_path
);
1405 config
->sectionStartMap
= getSectionStartMap(args
);
1406 config
->shared
= args
.hasArg(OPT_shared
);
1407 config
->singleRoRx
= !args
.hasFlag(OPT_rosegment
, OPT_no_rosegment
, true);
1408 config
->soName
= args
.getLastArgValue(OPT_soname
);
1409 config
->sortSection
= getSortSection(args
);
1410 config
->splitStackAdjustSize
= args::getInteger(args
, OPT_split_stack_adjust_size
, 16384);
1411 config
->strip
= getStrip(args
);
1412 config
->sysroot
= args
.getLastArgValue(OPT_sysroot
);
1413 config
->target1Rel
= args
.hasFlag(OPT_target1_rel
, OPT_target1_abs
, false);
1414 config
->target2
= getTarget2(args
);
1415 config
->thinLTOCacheDir
= args
.getLastArgValue(OPT_thinlto_cache_dir
);
1416 config
->thinLTOCachePolicy
= CHECK(
1417 parseCachePruningPolicy(args
.getLastArgValue(OPT_thinlto_cache_policy
)),
1418 "--thinlto-cache-policy: invalid cache policy");
1419 config
->thinLTOEmitImportsFiles
= args
.hasArg(OPT_thinlto_emit_imports_files
);
1420 config
->thinLTOEmitIndexFiles
= args
.hasArg(OPT_thinlto_emit_index_files
) ||
1421 args
.hasArg(OPT_thinlto_index_only
) ||
1422 args
.hasArg(OPT_thinlto_index_only_eq
);
1423 config
->thinLTOIndexOnly
= args
.hasArg(OPT_thinlto_index_only
) ||
1424 args
.hasArg(OPT_thinlto_index_only_eq
);
1425 config
->thinLTOIndexOnlyArg
= args
.getLastArgValue(OPT_thinlto_index_only_eq
);
1426 config
->thinLTOObjectSuffixReplace
=
1427 getOldNewOptions(args
, OPT_thinlto_object_suffix_replace_eq
);
1428 std::tie(config
->thinLTOPrefixReplaceOld
, config
->thinLTOPrefixReplaceNew
,
1429 config
->thinLTOPrefixReplaceNativeObject
) =
1430 getOldNewOptionsExtra(args
, OPT_thinlto_prefix_replace_eq
);
1431 if (config
->thinLTOEmitIndexFiles
&& !config
->thinLTOIndexOnly
) {
1432 if (args
.hasArg(OPT_thinlto_object_suffix_replace_eq
))
1433 error("--thinlto-object-suffix-replace is not supported with "
1434 "--thinlto-emit-index-files");
1435 else if (args
.hasArg(OPT_thinlto_prefix_replace_eq
))
1436 error("--thinlto-prefix-replace is not supported with "
1437 "--thinlto-emit-index-files");
1439 if (!config
->thinLTOPrefixReplaceNativeObject
.empty() &&
1440 config
->thinLTOIndexOnlyArg
.empty()) {
1441 error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "
1442 "--thinlto-index-only=");
1444 config
->thinLTOModulesToCompile
=
1445 args::getStrings(args
, OPT_thinlto_single_module_eq
);
1446 config
->timeTraceEnabled
= args
.hasArg(OPT_time_trace_eq
);
1447 config
->timeTraceGranularity
=
1448 args::getInteger(args
, OPT_time_trace_granularity
, 500);
1449 config
->trace
= args
.hasArg(OPT_trace
);
1450 config
->undefined
= args::getStrings(args
, OPT_undefined
);
1451 config
->undefinedVersion
=
1452 args
.hasFlag(OPT_undefined_version
, OPT_no_undefined_version
, false);
1453 config
->unique
= args
.hasArg(OPT_unique
);
1454 config
->useAndroidRelrTags
= args
.hasFlag(
1455 OPT_use_android_relr_tags
, OPT_no_use_android_relr_tags
, false);
1456 config
->warnBackrefs
=
1457 args
.hasFlag(OPT_warn_backrefs
, OPT_no_warn_backrefs
, false);
1458 config
->warnCommon
= args
.hasFlag(OPT_warn_common
, OPT_no_warn_common
, false);
1459 config
->warnSymbolOrdering
=
1460 args
.hasFlag(OPT_warn_symbol_ordering
, OPT_no_warn_symbol_ordering
, true);
1461 config
->whyExtract
= args
.getLastArgValue(OPT_why_extract
);
1462 config
->zCombreloc
= getZFlag(args
, "combreloc", "nocombreloc", true);
1463 config
->zCopyreloc
= getZFlag(args
, "copyreloc", "nocopyreloc", true);
1464 config
->zForceBti
= hasZOption(args
, "force-bti");
1465 config
->zForceIbt
= hasZOption(args
, "force-ibt");
1466 config
->zGcs
= getZGcs(args
);
1467 config
->zGlobal
= hasZOption(args
, "global");
1468 config
->zGnustack
= getZGnuStack(args
);
1469 config
->zHazardplt
= hasZOption(args
, "hazardplt");
1470 config
->zIfuncNoplt
= hasZOption(args
, "ifunc-noplt");
1471 config
->zInitfirst
= hasZOption(args
, "initfirst");
1472 config
->zInterpose
= hasZOption(args
, "interpose");
1473 config
->zKeepTextSectionPrefix
= getZFlag(
1474 args
, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
1475 config
->zLrodataAfterBss
=
1476 getZFlag(args
, "lrodata-after-bss", "nolrodata-after-bss", false);
1477 config
->zNodefaultlib
= hasZOption(args
, "nodefaultlib");
1478 config
->zNodelete
= hasZOption(args
, "nodelete");
1479 config
->zNodlopen
= hasZOption(args
, "nodlopen");
1480 config
->zNow
= getZFlag(args
, "now", "lazy", false);
1481 config
->zOrigin
= hasZOption(args
, "origin");
1482 config
->zPacPlt
= hasZOption(args
, "pac-plt");
1483 config
->zRelro
= getZFlag(args
, "relro", "norelro", true);
1484 config
->zRetpolineplt
= hasZOption(args
, "retpolineplt");
1485 config
->zRodynamic
= hasZOption(args
, "rodynamic");
1486 config
->zSeparate
= getZSeparate(args
);
1487 config
->zShstk
= hasZOption(args
, "shstk");
1488 config
->zStackSize
= args::getZOptionValue(args
, OPT_z
, "stack-size", 0);
1489 config
->zStartStopGC
=
1490 getZFlag(args
, "start-stop-gc", "nostart-stop-gc", true);
1491 config
->zStartStopVisibility
= getZStartStopVisibility(args
);
1492 config
->zText
= getZFlag(args
, "text", "notext", true);
1493 config
->zWxneeded
= hasZOption(args
, "wxneeded");
1494 setUnresolvedSymbolPolicy(args
);
1495 config
->power10Stubs
= args
.getLastArgValue(OPT_power10_stubs_eq
) != "no";
1497 if (opt::Arg
*arg
= args
.getLastArg(OPT_eb
, OPT_el
)) {
1498 if (arg
->getOption().matches(OPT_eb
))
1499 config
->optEB
= true;
1501 config
->optEL
= true;
1504 for (opt::Arg
*arg
: args
.filtered(OPT_remap_inputs
)) {
1505 StringRef
value(arg
->getValue());
1506 remapInputs(value
, arg
->getSpelling());
1508 for (opt::Arg
*arg
: args
.filtered(OPT_remap_inputs_file
)) {
1509 StringRef
filename(arg
->getValue());
1510 std::optional
<MemoryBufferRef
> buffer
= readFile(filename
);
1513 // Parse 'from-glob=to-file' lines, ignoring #-led comments.
1514 for (auto [lineno
, line
] : llvm::enumerate(args::getLines(*buffer
)))
1515 if (remapInputs(line
, filename
+ ":" + Twine(lineno
+ 1)))
1519 for (opt::Arg
*arg
: args
.filtered(OPT_shuffle_sections
)) {
1520 constexpr StringRef errPrefix
= "--shuffle-sections=: ";
1521 std::pair
<StringRef
, StringRef
> kv
= StringRef(arg
->getValue()).split('=');
1522 if (kv
.first
.empty() || kv
.second
.empty()) {
1523 error(errPrefix
+ "expected <section_glob>=<seed>, but got '" +
1524 arg
->getValue() + "'");
1527 // Signed so that <section_glob>=-1 is allowed.
1529 if (!to_integer(kv
.second
, v
))
1530 error(errPrefix
+ "expected an integer, but got '" + kv
.second
+ "'");
1531 else if (Expected
<GlobPattern
> pat
= GlobPattern::create(kv
.first
))
1532 config
->shuffleSections
.emplace_back(std::move(*pat
), uint32_t(v
));
1534 error(errPrefix
+ toString(pat
.takeError()) + ": " + kv
.first
);
1537 auto reports
= {std::make_pair("bti-report", &config
->zBtiReport
),
1538 std::make_pair("cet-report", &config
->zCetReport
),
1539 std::make_pair("gcs-report", &config
->zGcsReport
),
1540 std::make_pair("pauth-report", &config
->zPauthReport
)};
1541 for (opt::Arg
*arg
: args
.filtered(OPT_z
)) {
1542 std::pair
<StringRef
, StringRef
> option
=
1543 StringRef(arg
->getValue()).split('=');
1544 for (auto reportArg
: reports
) {
1545 if (option
.first
!= reportArg
.first
)
1548 if (!isValidReportString(option
.second
)) {
1549 error(Twine("-z ") + reportArg
.first
+ "= parameter " + option
.second
+
1550 " is not recognized");
1553 *reportArg
.second
= option
.second
;
1557 for (opt::Arg
*arg
: args
.filtered(OPT_compress_sections
)) {
1558 SmallVector
<StringRef
, 0> fields
;
1559 StringRef(arg
->getValue()).split(fields
, '=');
1560 if (fields
.size() != 2 || fields
[1].empty()) {
1561 error(arg
->getSpelling() +
1562 ": parse error, not 'section-glob=[none|zlib|zstd]'");
1565 auto [typeStr
, levelStr
] = fields
[1].split(':');
1566 auto type
= getCompressionType(typeStr
, arg
->getSpelling());
1568 if (fields
[1].size() != typeStr
.size() &&
1569 !llvm::to_integer(levelStr
, level
)) {
1570 error(arg
->getSpelling() +
1571 ": expected a non-negative integer compression level, but got '" +
1574 if (Expected
<GlobPattern
> pat
= GlobPattern::create(fields
[0])) {
1575 config
->compressSections
.emplace_back(std::move(*pat
), type
, level
);
1577 error(arg
->getSpelling() + ": " + toString(pat
.takeError()));
1582 for (opt::Arg
*arg
: args
.filtered(OPT_z
)) {
1583 std::pair
<StringRef
, StringRef
> option
=
1584 StringRef(arg
->getValue()).split('=');
1585 if (option
.first
!= "dead-reloc-in-nonalloc")
1588 constexpr StringRef errPrefix
= "-z dead-reloc-in-nonalloc=: ";
1589 std::pair
<StringRef
, StringRef
> kv
= option
.second
.split('=');
1590 if (kv
.first
.empty() || kv
.second
.empty()) {
1591 error(errPrefix
+ "expected <section_glob>=<value>");
1595 if (!to_integer(kv
.second
, v
))
1596 error(errPrefix
+ "expected a non-negative integer, but got '" +
1598 else if (Expected
<GlobPattern
> pat
= GlobPattern::create(kv
.first
))
1599 config
->deadRelocInNonAlloc
.emplace_back(std::move(*pat
), v
);
1601 error(errPrefix
+ toString(pat
.takeError()) + ": " + kv
.first
);
1604 cl::ResetAllOptionOccurrences();
1606 // Parse LTO options.
1607 if (auto *arg
= args
.getLastArg(OPT_plugin_opt_mcpu_eq
))
1608 parseClangOption(saver().save("-mcpu=" + StringRef(arg
->getValue())),
1609 arg
->getSpelling());
1611 for (opt::Arg
*arg
: args
.filtered(OPT_plugin_opt_eq_minus
))
1612 parseClangOption(std::string("-") + arg
->getValue(), arg
->getSpelling());
1614 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1615 // relative path. Just ignore. If not ended with "lto-wrapper" (or
1616 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
1617 // unsupported LLVMgold.so option and error.
1618 for (opt::Arg
*arg
: args
.filtered(OPT_plugin_opt_eq
)) {
1619 StringRef
v(arg
->getValue());
1620 if (!v
.ends_with("lto-wrapper") && !v
.ends_with("lto-wrapper.exe"))
1621 error(arg
->getSpelling() + ": unknown plugin option '" + arg
->getValue() +
1625 config
->passPlugins
= args::getStrings(args
, OPT_load_pass_plugins
);
1627 // Parse -mllvm options.
1628 for (const auto *arg
: args
.filtered(OPT_mllvm
)) {
1629 parseClangOption(arg
->getValue(), arg
->getSpelling());
1630 config
->mllvmOpts
.emplace_back(arg
->getValue());
1633 config
->ltoKind
= LtoKind::Default
;
1634 if (auto *arg
= args
.getLastArg(OPT_lto
)) {
1635 StringRef s
= arg
->getValue();
1637 config
->ltoKind
= LtoKind::UnifiedThin
;
1638 else if (s
== "full")
1639 config
->ltoKind
= LtoKind::UnifiedRegular
;
1640 else if (s
== "default")
1641 config
->ltoKind
= LtoKind::Default
;
1643 error("unknown LTO mode: " + s
);
1646 // --threads= takes a positive integer and provides the default value for
1647 // --thinlto-jobs=. If unspecified, cap the number of threads since
1648 // overhead outweighs optimization for used parallel algorithms for the
1650 if (auto *arg
= args
.getLastArg(OPT_threads
)) {
1651 StringRef
v(arg
->getValue());
1652 unsigned threads
= 0;
1653 if (!llvm::to_integer(v
, threads
, 0) || threads
== 0)
1654 error(arg
->getSpelling() + ": expected a positive integer, but got '" +
1655 arg
->getValue() + "'");
1656 parallel::strategy
= hardware_concurrency(threads
);
1657 config
->thinLTOJobs
= v
;
1658 } else if (parallel::strategy
.compute_thread_count() > 16) {
1659 log("set maximum concurrency to 16, specify --threads= to change");
1660 parallel::strategy
= hardware_concurrency(16);
1662 if (auto *arg
= args
.getLastArg(OPT_thinlto_jobs_eq
))
1663 config
->thinLTOJobs
= arg
->getValue();
1664 config
->threadCount
= parallel::strategy
.compute_thread_count();
1666 if (config
->ltoPartitions
== 0)
1667 error("--lto-partitions: number of threads must be > 0");
1668 if (!get_threadpool_strategy(config
->thinLTOJobs
))
1669 error("--thinlto-jobs: invalid job count: " + config
->thinLTOJobs
);
1671 if (config
->splitStackAdjustSize
< 0)
1672 error("--split-stack-adjust-size: size must be >= 0");
1674 // The text segment is traditionally the first segment, whose address equals
1675 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1676 // is an old-fashioned option that does not play well with lld's layout.
1677 // Suggest --image-base as a likely alternative.
1678 if (args
.hasArg(OPT_Ttext_segment
))
1679 error("-Ttext-segment is not supported. Use --image-base if you "
1680 "intend to set the base address");
1682 // Parse ELF{32,64}{LE,BE} and CPU type.
1683 if (auto *arg
= args
.getLastArg(OPT_m
)) {
1684 StringRef s
= arg
->getValue();
1685 std::tie(config
->ekind
, config
->emachine
, config
->osabi
) =
1687 config
->mipsN32Abi
=
1688 (s
.starts_with("elf32btsmipn32") || s
.starts_with("elf32ltsmipn32"));
1689 config
->emulation
= s
;
1692 // Parse --hash-style={sysv,gnu,both}.
1693 if (auto *arg
= args
.getLastArg(OPT_hash_style
)) {
1694 StringRef s
= arg
->getValue();
1696 config
->sysvHash
= true;
1697 else if (s
== "gnu")
1698 config
->gnuHash
= true;
1699 else if (s
== "both")
1700 config
->sysvHash
= config
->gnuHash
= true;
1702 error("unknown --hash-style: " + s
);
1705 if (args
.hasArg(OPT_print_map
))
1706 config
->mapFile
= "-";
1708 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1709 // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1710 // it. Also disable RELRO for -r.
1711 if (config
->nmagic
|| config
->omagic
|| config
->relocatable
)
1712 config
->zRelro
= false;
1714 std::tie(config
->buildId
, config
->buildIdVector
) = getBuildId(args
);
1716 if (getZFlag(args
, "pack-relative-relocs", "nopack-relative-relocs", false)) {
1717 config
->relrGlibc
= true;
1718 config
->relrPackDynRelocs
= true;
1720 std::tie(config
->androidPackDynRelocs
, config
->relrPackDynRelocs
) =
1721 getPackDynRelocs(args
);
1724 if (auto *arg
= args
.getLastArg(OPT_symbol_ordering_file
)){
1725 if (args
.hasArg(OPT_call_graph_ordering_file
))
1726 error("--symbol-ordering-file and --call-graph-order-file "
1727 "may not be used together");
1728 if (std::optional
<MemoryBufferRef
> buffer
= readFile(arg
->getValue())) {
1729 config
->symbolOrderingFile
= getSymbolOrderingFile(*buffer
);
1730 // Also need to disable CallGraphProfileSort to prevent
1731 // LLD order symbols with CGProfile
1732 config
->callGraphProfileSort
= CGProfileSortKind::None
;
1736 assert(config
->versionDefinitions
.empty());
1737 config
->versionDefinitions
.push_back(
1738 {"local", (uint16_t)VER_NDX_LOCAL
, {}, {}});
1739 config
->versionDefinitions
.push_back(
1740 {"global", (uint16_t)VER_NDX_GLOBAL
, {}, {}});
1742 // If --retain-symbol-file is used, we'll keep only the symbols listed in
1743 // the file and discard all others.
1744 if (auto *arg
= args
.getLastArg(OPT_retain_symbols_file
)) {
1745 config
->versionDefinitions
[VER_NDX_LOCAL
].nonLocalPatterns
.push_back(
1746 {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1747 if (std::optional
<MemoryBufferRef
> buffer
= readFile(arg
->getValue()))
1748 for (StringRef s
: args::getLines(*buffer
))
1749 config
->versionDefinitions
[VER_NDX_GLOBAL
].nonLocalPatterns
.push_back(
1750 {s
, /*isExternCpp=*/false, /*hasWildcard=*/false});
1753 for (opt::Arg
*arg
: args
.filtered(OPT_warn_backrefs_exclude
)) {
1754 StringRef
pattern(arg
->getValue());
1755 if (Expected
<GlobPattern
> pat
= GlobPattern::create(pattern
))
1756 config
->warnBackrefsExclude
.push_back(std::move(*pat
));
1758 error(arg
->getSpelling() + ": " + toString(pat
.takeError()) + ": " +
1762 // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1763 // which should be exported. For -shared, references to matched non-local
1764 // STV_DEFAULT symbols are not bound to definitions within the shared object,
1765 // even if other options express a symbolic intention: -Bsymbolic,
1766 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1767 for (auto *arg
: args
.filtered(OPT_export_dynamic_symbol
))
1768 config
->dynamicList
.push_back(
1769 {arg
->getValue(), /*isExternCpp=*/false,
1770 /*hasWildcard=*/hasWildcard(arg
->getValue())});
1772 // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1773 // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1776 config
->bsymbolic
== BsymbolicKind::All
|| args
.hasArg(OPT_dynamic_list
);
1778 args
.filtered(OPT_dynamic_list
, OPT_export_dynamic_symbol_list
))
1779 if (std::optional
<MemoryBufferRef
> buffer
= readFile(arg
->getValue()))
1780 readDynamicList(*buffer
);
1782 for (auto *arg
: args
.filtered(OPT_version_script
))
1783 if (std::optional
<std::string
> path
= searchScript(arg
->getValue())) {
1784 if (std::optional
<MemoryBufferRef
> buffer
= readFile(*path
))
1785 readVersionScript(*buffer
);
1787 error(Twine("cannot find version script ") + arg
->getValue());
1791 // Some Config members do not directly correspond to any particular
1792 // command line options, but computed based on other Config values.
1793 // This function initialize such members. See Config.h for the details
1795 static void setConfigs(opt::InputArgList
&args
) {
1796 ELFKind k
= config
->ekind
;
1797 uint16_t m
= config
->emachine
;
1799 config
->copyRelocs
= (config
->relocatable
|| config
->emitRelocs
);
1800 config
->is64
= (k
== ELF64LEKind
|| k
== ELF64BEKind
);
1801 config
->isLE
= (k
== ELF32LEKind
|| k
== ELF64LEKind
);
1802 config
->endianness
= config
->isLE
? endianness::little
: endianness::big
;
1803 config
->isMips64EL
= (k
== ELF64LEKind
&& m
== EM_MIPS
);
1804 config
->isPic
= config
->pie
|| config
->shared
;
1805 config
->picThunk
= args
.hasArg(OPT_pic_veneer
, config
->isPic
);
1806 config
->wordsize
= config
->is64
? 8 : 4;
1808 // ELF defines two different ways to store relocation addends as shown below:
1810 // Rel: Addends are stored to the location where relocations are applied. It
1811 // cannot pack the full range of addend values for all relocation types, but
1812 // this only affects relocation types that we don't support emitting as
1813 // dynamic relocations (see getDynRel).
1814 // Rela: Addends are stored as part of relocation entry.
1816 // In other words, Rela makes it easy to read addends at the price of extra
1817 // 4 or 8 byte for each relocation entry.
1819 // We pick the format for dynamic relocations according to the psABI for each
1820 // processor, but a contrary choice can be made if the dynamic loader
1822 config
->isRela
= getIsRela(args
);
1824 // If the output uses REL relocations we must store the dynamic relocation
1825 // addends to the output sections. We also store addends for RELA relocations
1826 // if --apply-dynamic-relocs is used.
1827 // We default to not writing the addends when using RELA relocations since
1828 // any standard conforming tool can find it in r_addend.
1829 config
->writeAddends
= args
.hasFlag(OPT_apply_dynamic_relocs
,
1830 OPT_no_apply_dynamic_relocs
, false) ||
1832 // Validation of dynamic relocation addends is on by default for assertions
1833 // builds and disabled otherwise. This check is enabled when writeAddends is
1836 bool checkDynamicRelocsDefault
= true;
1838 bool checkDynamicRelocsDefault
= false;
1840 config
->checkDynamicRelocs
=
1841 args
.hasFlag(OPT_check_dynamic_relocations
,
1842 OPT_no_check_dynamic_relocations
, checkDynamicRelocsDefault
);
1843 config
->tocOptimize
=
1844 args
.hasFlag(OPT_toc_optimize
, OPT_no_toc_optimize
, m
== EM_PPC64
);
1845 config
->pcRelOptimize
=
1846 args
.hasFlag(OPT_pcrel_optimize
, OPT_no_pcrel_optimize
, m
== EM_PPC64
);
1848 if (!args
.hasArg(OPT_hash_style
)) {
1849 if (config
->emachine
== EM_MIPS
)
1850 config
->sysvHash
= true;
1852 config
->sysvHash
= config
->gnuHash
= true;
1855 // Set default entry point and output file if not specified by command line or
1857 config
->warnMissingEntry
=
1858 (!config
->entry
.empty() || (!config
->shared
&& !config
->relocatable
));
1859 if (config
->entry
.empty() && !config
->relocatable
)
1860 config
->entry
= config
->emachine
== EM_MIPS
? "__start" : "_start";
1861 if (config
->outputFile
.empty())
1862 config
->outputFile
= "a.out";
1864 // Fail early if the output file or map file is not writable. If a user has a
1865 // long link, e.g. due to a large LTO link, they do not wish to run it and
1866 // find that it failed because there was a mistake in their command-line.
1868 llvm::TimeTraceScope
timeScope("Create output files");
1869 if (auto e
= tryCreateFile(config
->outputFile
))
1870 error("cannot open output file " + config
->outputFile
+ ": " +
1872 if (auto e
= tryCreateFile(config
->mapFile
))
1873 error("cannot open map file " + config
->mapFile
+ ": " + e
.message());
1874 if (auto e
= tryCreateFile(config
->whyExtract
))
1875 error("cannot open --why-extract= file " + config
->whyExtract
+ ": " +
1880 static bool isFormatBinary(StringRef s
) {
1883 if (s
== "elf" || s
== "default")
1885 error("unknown --format value: " + s
+
1886 " (supported formats: elf, default, binary)");
1890 void LinkerDriver::createFiles(opt::InputArgList
&args
) {
1891 llvm::TimeTraceScope
timeScope("Load input files");
1892 // For --{push,pop}-state.
1893 std::vector
<std::tuple
<bool, bool, bool>> stack
;
1895 // -r implies -Bstatic and has precedence over -Bdynamic.
1896 config
->isStatic
= config
->relocatable
;
1898 // Iterate over argv to process input files and positional arguments.
1899 std::optional
<MemoryBufferRef
> defaultScript
;
1900 InputFile::isInGroup
= false;
1901 bool hasInput
= false, hasScript
= false;
1902 for (auto *arg
: args
) {
1903 switch (arg
->getOption().getID()) {
1905 addLibrary(arg
->getValue());
1909 addFile(arg
->getValue(), /*withLOption=*/false);
1915 std::tie(from
, to
) = StringRef(arg
->getValue()).split('=');
1916 if (from
.empty() || to
.empty())
1917 error("--defsym: syntax error: " + StringRef(arg
->getValue()));
1919 readDefsym(from
, MemoryBufferRef(to
, "--defsym"));
1923 case OPT_default_script
:
1924 if (std::optional
<std::string
> path
= searchScript(arg
->getValue())) {
1925 if (std::optional
<MemoryBufferRef
> mb
= readFile(*path
)) {
1926 if (arg
->getOption().matches(OPT_default_script
)) {
1929 readLinkerScript(*mb
);
1935 error(Twine("cannot find linker script ") + arg
->getValue());
1938 config
->asNeeded
= true;
1941 config
->formatBinary
= isFormatBinary(arg
->getValue());
1943 case OPT_no_as_needed
:
1944 config
->asNeeded
= false;
1949 config
->isStatic
= true;
1952 if (!config
->relocatable
)
1953 config
->isStatic
= false;
1955 case OPT_whole_archive
:
1956 inWholeArchive
= true;
1958 case OPT_no_whole_archive
:
1959 inWholeArchive
= false;
1961 case OPT_just_symbols
:
1962 if (std::optional
<MemoryBufferRef
> mb
= readFile(arg
->getValue())) {
1963 files
.push_back(createObjFile(*mb
));
1964 files
.back()->justSymbols
= true;
1969 error("multiple CMSE import libraries not supported");
1970 else if (std::optional
<MemoryBufferRef
> mb
= readFile(arg
->getValue()))
1971 armCmseImpLib
= createObjFile(*mb
);
1973 case OPT_start_group
:
1974 if (InputFile::isInGroup
)
1975 error("nested --start-group");
1976 InputFile::isInGroup
= true;
1979 if (!InputFile::isInGroup
)
1980 error("stray --end-group");
1981 InputFile::isInGroup
= false;
1982 ++InputFile::nextGroupId
;
1986 error("nested --start-lib");
1987 if (InputFile::isInGroup
)
1988 error("may not nest --start-lib in --start-group");
1990 InputFile::isInGroup
= true;
1994 error("stray --end-lib");
1996 InputFile::isInGroup
= false;
1997 ++InputFile::nextGroupId
;
1999 case OPT_push_state
:
2000 stack
.emplace_back(config
->asNeeded
, config
->isStatic
, inWholeArchive
);
2003 if (stack
.empty()) {
2004 error("unbalanced --push-state/--pop-state");
2007 std::tie(config
->asNeeded
, config
->isStatic
, inWholeArchive
) = stack
.back();
2013 if (defaultScript
&& !hasScript
)
2014 readLinkerScript(*defaultScript
);
2015 if (files
.empty() && !hasInput
&& errorCount() == 0)
2016 error("no input files");
2019 // If -m <machine_type> was not given, infer it from object files.
2020 void LinkerDriver::inferMachineType() {
2021 if (config
->ekind
!= ELFNoneKind
)
2024 bool inferred
= false;
2025 for (InputFile
*f
: files
) {
2026 if (f
->ekind
== ELFNoneKind
)
2030 config
->ekind
= f
->ekind
;
2031 config
->emachine
= f
->emachine
;
2032 config
->mipsN32Abi
= config
->emachine
== EM_MIPS
&& isMipsN32Abi(f
);
2034 config
->osabi
= f
->osabi
;
2035 if (f
->osabi
!= ELFOSABI_NONE
)
2039 error("target emulation unknown: -m or at least one .o file required");
2042 // Parse -z max-page-size=<value>. The default value is defined by
2044 static uint64_t getMaxPageSize(opt::InputArgList
&args
) {
2045 uint64_t val
= args::getZOptionValue(args
, OPT_z
, "max-page-size",
2046 target
->defaultMaxPageSize
);
2047 if (!isPowerOf2_64(val
)) {
2048 error("max-page-size: value isn't a power of 2");
2049 return target
->defaultMaxPageSize
;
2051 if (config
->nmagic
|| config
->omagic
) {
2052 if (val
!= target
->defaultMaxPageSize
)
2053 warn("-z max-page-size set, but paging disabled by omagic or nmagic");
2059 // Parse -z common-page-size=<value>. The default value is defined by
2061 static uint64_t getCommonPageSize(opt::InputArgList
&args
) {
2062 uint64_t val
= args::getZOptionValue(args
, OPT_z
, "common-page-size",
2063 target
->defaultCommonPageSize
);
2064 if (!isPowerOf2_64(val
)) {
2065 error("common-page-size: value isn't a power of 2");
2066 return target
->defaultCommonPageSize
;
2068 if (config
->nmagic
|| config
->omagic
) {
2069 if (val
!= target
->defaultCommonPageSize
)
2070 warn("-z common-page-size set, but paging disabled by omagic or nmagic");
2073 // commonPageSize can't be larger than maxPageSize.
2074 if (val
> config
->maxPageSize
)
2075 val
= config
->maxPageSize
;
2079 // Parses --image-base option.
2080 static std::optional
<uint64_t> getImageBase(opt::InputArgList
&args
) {
2081 // Because we are using "Config->maxPageSize" here, this function has to be
2082 // called after the variable is initialized.
2083 auto *arg
= args
.getLastArg(OPT_image_base
);
2085 return std::nullopt
;
2087 StringRef s
= arg
->getValue();
2089 if (!to_integer(s
, v
)) {
2090 error("--image-base: number expected, but got " + s
);
2093 if ((v
% config
->maxPageSize
) != 0)
2094 warn("--image-base: address isn't multiple of page size: " + s
);
2098 // Parses `--exclude-libs=lib,lib,...`.
2099 // The library names may be delimited by commas or colons.
2100 static DenseSet
<StringRef
> getExcludeLibs(opt::InputArgList
&args
) {
2101 DenseSet
<StringRef
> ret
;
2102 for (auto *arg
: args
.filtered(OPT_exclude_libs
)) {
2103 StringRef s
= arg
->getValue();
2105 size_t pos
= s
.find_first_of(",:");
2106 if (pos
== StringRef::npos
)
2108 ret
.insert(s
.substr(0, pos
));
2109 s
= s
.substr(pos
+ 1);
2116 // Handles the --exclude-libs option. If a static library file is specified
2117 // by the --exclude-libs option, all public symbols from the archive become
2118 // private unless otherwise specified by version scripts or something.
2119 // A special library name "ALL" means all archive files.
2121 // This is not a popular option, but some programs such as bionic libc use it.
2122 static void excludeLibs(opt::InputArgList
&args
) {
2123 DenseSet
<StringRef
> libs
= getExcludeLibs(args
);
2124 bool all
= libs
.count("ALL");
2126 auto visit
= [&](InputFile
*file
) {
2127 if (file
->archiveName
.empty() ||
2128 !(all
|| libs
.count(path::filename(file
->archiveName
))))
2130 ArrayRef
<Symbol
*> symbols
= file
->getSymbols();
2131 if (isa
<ELFFileBase
>(file
))
2132 symbols
= cast
<ELFFileBase
>(file
)->getGlobalSymbols();
2133 for (Symbol
*sym
: symbols
)
2134 if (!sym
->isUndefined() && sym
->file
== file
)
2135 sym
->versionId
= VER_NDX_LOCAL
;
2138 for (ELFFileBase
*file
: ctx
.objectFiles
)
2141 for (BitcodeFile
*file
: ctx
.bitcodeFiles
)
2145 // Force Sym to be entered in the output.
2146 static void handleUndefined(Symbol
*sym
, const char *option
) {
2147 // Since a symbol may not be used inside the program, LTO may
2148 // eliminate it. Mark the symbol as "used" to prevent it.
2149 sym
->isUsedInRegularObj
= true;
2154 if (!config
->whyExtract
.empty())
2155 ctx
.whyExtractRecords
.emplace_back(option
, sym
->file
, *sym
);
2158 // As an extension to GNU linkers, lld supports a variant of `-u`
2159 // which accepts wildcard patterns. All symbols that match a given
2160 // pattern are handled as if they were given by `-u`.
2161 static void handleUndefinedGlob(StringRef arg
) {
2162 Expected
<GlobPattern
> pat
= GlobPattern::create(arg
);
2164 error("--undefined-glob: " + toString(pat
.takeError()) + ": " + arg
);
2168 // Calling sym->extract() in the loop is not safe because it may add new
2169 // symbols to the symbol table, invalidating the current iterator.
2170 SmallVector
<Symbol
*, 0> syms
;
2171 for (Symbol
*sym
: symtab
.getSymbols())
2172 if (!sym
->isPlaceholder() && pat
->match(sym
->getName()))
2173 syms
.push_back(sym
);
2175 for (Symbol
*sym
: syms
)
2176 handleUndefined(sym
, "--undefined-glob");
2179 static void handleLibcall(StringRef name
) {
2180 Symbol
*sym
= symtab
.find(name
);
2181 if (sym
&& sym
->isLazy() && isa
<BitcodeFile
>(sym
->file
)) {
2182 if (!config
->whyExtract
.empty())
2183 ctx
.whyExtractRecords
.emplace_back("<libcall>", sym
->file
, *sym
);
2188 static void writeArchiveStats() {
2189 if (config
->printArchiveStats
.empty())
2193 raw_fd_ostream os
= ctx
.openAuxiliaryFile(config
->printArchiveStats
, ec
);
2195 error("--print-archive-stats=: cannot open " + config
->printArchiveStats
+
2196 ": " + ec
.message());
2200 os
<< "members\textracted\tarchive\n";
2202 SmallVector
<StringRef
, 0> archives
;
2203 DenseMap
<CachedHashStringRef
, unsigned> all
, extracted
;
2204 for (ELFFileBase
*file
: ctx
.objectFiles
)
2205 if (file
->archiveName
.size())
2206 ++extracted
[CachedHashStringRef(file
->archiveName
)];
2207 for (BitcodeFile
*file
: ctx
.bitcodeFiles
)
2208 if (file
->archiveName
.size())
2209 ++extracted
[CachedHashStringRef(file
->archiveName
)];
2210 for (std::pair
<StringRef
, unsigned> f
: ctx
.driver
.archiveFiles
) {
2211 unsigned &v
= extracted
[CachedHashString(f
.first
)];
2212 os
<< f
.second
<< '\t' << v
<< '\t' << f
.first
<< '\n';
2213 // If the archive occurs multiple times, other instances have a count of 0.
2218 static void writeWhyExtract() {
2219 if (config
->whyExtract
.empty())
2223 raw_fd_ostream os
= ctx
.openAuxiliaryFile(config
->whyExtract
, ec
);
2225 error("cannot open --why-extract= file " + config
->whyExtract
+ ": " +
2230 os
<< "reference\textracted\tsymbol\n";
2231 for (auto &entry
: ctx
.whyExtractRecords
) {
2232 os
<< std::get
<0>(entry
) << '\t' << toString(std::get
<1>(entry
)) << '\t'
2233 << toString(std::get
<2>(entry
)) << '\n';
2237 static void reportBackrefs() {
2238 for (auto &ref
: ctx
.backwardReferences
) {
2239 const Symbol
&sym
= *ref
.first
;
2240 std::string to
= toString(ref
.second
.second
);
2241 // Some libraries have known problems and can cause noise. Filter them out
2242 // with --warn-backrefs-exclude=. The value may look like (for --start-lib)
2243 // *.o or (archive member) *.a(*.o).
2244 bool exclude
= false;
2245 for (const llvm::GlobPattern
&pat
: config
->warnBackrefsExclude
)
2246 if (pat
.match(to
)) {
2251 warn("backward reference detected: " + sym
.getName() + " in " +
2252 toString(ref
.second
.first
) + " refers to " + to
);
2256 // Handle --dependency-file=<path>. If that option is given, lld creates a
2257 // file at a given path with the following contents:
2259 // <output-file>: <input-file> ...
2263 // where <output-file> is a pathname of an output file and <input-file>
2264 // ... is a list of pathnames of all input files. `make` command can read a
2265 // file in the above format and interpret it as a dependency info. We write
2266 // phony targets for every <input-file> to avoid an error when that file is
2269 // This option is useful if you want to make your final executable to depend
2270 // on all input files including system libraries. Here is why.
2272 // When you write a Makefile, you usually write it so that the final
2273 // executable depends on all user-generated object files. Normally, you
2274 // don't make your executable to depend on system libraries (such as libc)
2275 // because you don't know the exact paths of libraries, even though system
2276 // libraries that are linked to your executable statically are technically a
2277 // part of your program. By using --dependency-file option, you can make
2278 // lld to dump dependency info so that you can maintain exact dependencies
2280 static void writeDependencyFile() {
2282 raw_fd_ostream os
= ctx
.openAuxiliaryFile(config
->dependencyFile
, ec
);
2284 error("cannot open " + config
->dependencyFile
+ ": " + ec
.message());
2288 // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
2289 // * A space is escaped by a backslash which itself must be escaped.
2290 // * A hash sign is escaped by a single backslash.
2291 // * $ is escapes as $$.
2292 auto printFilename
= [](raw_fd_ostream
&os
, StringRef filename
) {
2293 llvm::SmallString
<256> nativePath
;
2294 llvm::sys::path::native(filename
.str(), nativePath
);
2295 llvm::sys::path::remove_dots(nativePath
, /*remove_dot_dot=*/true);
2296 for (unsigned i
= 0, e
= nativePath
.size(); i
!= e
; ++i
) {
2297 if (nativePath
[i
] == '#') {
2299 } else if (nativePath
[i
] == ' ') {
2302 while (j
> 0 && nativePath
[--j
] == '\\')
2304 } else if (nativePath
[i
] == '$') {
2307 os
<< nativePath
[i
];
2311 os
<< config
->outputFile
<< ":";
2312 for (StringRef path
: config
->dependencyFiles
) {
2314 printFilename(os
, path
);
2318 for (StringRef path
: config
->dependencyFiles
) {
2320 printFilename(os
, path
);
2325 // Replaces common symbols with defined symbols reside in .bss sections.
2326 // This function is called after all symbol names are resolved. As a
2327 // result, the passes after the symbol resolution won't see any
2328 // symbols of type CommonSymbol.
2329 static void replaceCommonSymbols() {
2330 llvm::TimeTraceScope
timeScope("Replace common symbols");
2331 for (ELFFileBase
*file
: ctx
.objectFiles
) {
2332 if (!file
->hasCommonSyms
)
2334 for (Symbol
*sym
: file
->getGlobalSymbols()) {
2335 auto *s
= dyn_cast
<CommonSymbol
>(sym
);
2339 auto *bss
= make
<BssSection
>("COMMON", s
->size
, s
->alignment
);
2340 bss
->file
= s
->file
;
2341 ctx
.inputSections
.push_back(bss
);
2342 Defined(s
->file
, StringRef(), s
->binding
, s
->stOther
, s
->type
,
2343 /*value=*/0, s
->size
, bss
)
2349 // The section referred to by `s` is considered address-significant. Set the
2350 // keepUnique flag on the section if appropriate.
2351 static void markAddrsig(Symbol
*s
) {
2352 if (auto *d
= dyn_cast_or_null
<Defined
>(s
))
2354 // We don't need to keep text sections unique under --icf=all even if they
2355 // are address-significant.
2356 if (config
->icf
== ICFLevel::Safe
|| !(d
->section
->flags
& SHF_EXECINSTR
))
2357 d
->section
->keepUnique
= true;
2360 // Record sections that define symbols mentioned in --keep-unique <symbol>
2361 // and symbols referred to by address-significance tables. These sections are
2362 // ineligible for ICF.
2363 template <class ELFT
>
2364 static void findKeepUniqueSections(opt::InputArgList
&args
) {
2365 for (auto *arg
: args
.filtered(OPT_keep_unique
)) {
2366 StringRef name
= arg
->getValue();
2367 auto *d
= dyn_cast_or_null
<Defined
>(symtab
.find(name
));
2368 if (!d
|| !d
->section
) {
2369 warn("could not find symbol " + name
+ " to keep unique");
2372 d
->section
->keepUnique
= true;
2375 // --icf=all --ignore-data-address-equality means that we can ignore
2376 // the dynsym and address-significance tables entirely.
2377 if (config
->icf
== ICFLevel::All
&& config
->ignoreDataAddressEquality
)
2380 // Symbols in the dynsym could be address-significant in other executables
2381 // or DSOs, so we conservatively mark them as address-significant.
2382 for (Symbol
*sym
: symtab
.getSymbols())
2383 if (sym
->includeInDynsym())
2386 // Visit the address-significance table in each object file and mark each
2387 // referenced symbol as address-significant.
2388 for (InputFile
*f
: ctx
.objectFiles
) {
2389 auto *obj
= cast
<ObjFile
<ELFT
>>(f
);
2390 ArrayRef
<Symbol
*> syms
= obj
->getSymbols();
2391 if (obj
->addrsigSec
) {
2392 ArrayRef
<uint8_t> contents
=
2393 check(obj
->getObj().getSectionContents(*obj
->addrsigSec
));
2394 const uint8_t *cur
= contents
.begin();
2395 while (cur
!= contents
.end()) {
2397 const char *err
= nullptr;
2398 uint64_t symIndex
= decodeULEB128(cur
, &size
, contents
.end(), &err
);
2400 fatal(toString(f
) + ": could not decode addrsig section: " + err
);
2401 markAddrsig(syms
[symIndex
]);
2405 // If an object file does not have an address-significance table,
2406 // conservatively mark all of its symbols as address-significant.
2407 for (Symbol
*s
: syms
)
2413 // This function reads a symbol partition specification section. These sections
2414 // are used to control which partition a symbol is allocated to. See
2415 // https://lld.llvm.org/Partitions.html for more details on partitions.
2416 template <typename ELFT
>
2417 static void readSymbolPartitionSection(InputSectionBase
*s
) {
2418 // Read the relocation that refers to the partition's entry point symbol.
2420 const RelsOrRelas
<ELFT
> rels
= s
->template relsOrRelas
<ELFT
>();
2421 if (rels
.areRelocsRel())
2422 sym
= &s
->file
->getRelocTargetSym(rels
.rels
[0]);
2424 sym
= &s
->file
->getRelocTargetSym(rels
.relas
[0]);
2425 if (!isa
<Defined
>(sym
) || !sym
->includeInDynsym())
2428 StringRef partName
= reinterpret_cast<const char *>(s
->content().data());
2429 for (Partition
&part
: partitions
) {
2430 if (part
.name
== partName
) {
2431 sym
->partition
= part
.getNumber();
2436 // Forbid partitions from being used on incompatible targets, and forbid them
2437 // from being used together with various linker features that assume a single
2438 // set of output sections.
2439 if (script
->hasSectionsCommand
)
2440 error(toString(s
->file
) +
2441 ": partitions cannot be used with the SECTIONS command");
2442 if (script
->hasPhdrsCommands())
2443 error(toString(s
->file
) +
2444 ": partitions cannot be used with the PHDRS command");
2445 if (!config
->sectionStartMap
.empty())
2446 error(toString(s
->file
) + ": partitions cannot be used with "
2447 "--section-start, -Ttext, -Tdata or -Tbss");
2448 if (config
->emachine
== EM_MIPS
)
2449 error(toString(s
->file
) + ": partitions cannot be used on this target");
2451 // Impose a limit of no more than 254 partitions. This limit comes from the
2452 // sizes of the Partition fields in InputSectionBase and Symbol, as well as
2453 // the amount of space devoted to the partition number in RankFlags.
2454 if (partitions
.size() == 254)
2455 fatal("may not have more than 254 partitions");
2457 partitions
.emplace_back();
2458 Partition
&newPart
= partitions
.back();
2459 newPart
.name
= partName
;
2460 sym
->partition
= newPart
.getNumber();
2463 static void markBuffersAsDontNeed(bool skipLinkedOutput
) {
2464 // With --thinlto-index-only, all buffers are nearly unused from now on
2465 // (except symbol/section names used by infrequent passes). Mark input file
2466 // buffers as MADV_DONTNEED so that these pages can be reused by the expensive
2467 // thin link, saving memory.
2468 if (skipLinkedOutput
) {
2469 for (MemoryBuffer
&mb
: llvm::make_pointee_range(ctx
.memoryBuffers
))
2470 mb
.dontNeedIfMmap();
2474 // Otherwise, just mark MemoryBuffers backing BitcodeFiles.
2475 DenseSet
<const char *> bufs
;
2476 for (BitcodeFile
*file
: ctx
.bitcodeFiles
)
2477 bufs
.insert(file
->mb
.getBufferStart());
2478 for (BitcodeFile
*file
: ctx
.lazyBitcodeFiles
)
2479 bufs
.insert(file
->mb
.getBufferStart());
2480 for (MemoryBuffer
&mb
: llvm::make_pointee_range(ctx
.memoryBuffers
))
2481 if (bufs
.count(mb
.getBufferStart()))
2482 mb
.dontNeedIfMmap();
2485 // This function is where all the optimizations of link-time
2486 // optimization takes place. When LTO is in use, some input files are
2487 // not in native object file format but in the LLVM bitcode format.
2488 // This function compiles bitcode files into a few big native files
2489 // using LLVM functions and replaces bitcode symbols with the results.
2490 // Because all bitcode files that the program consists of are passed to
2491 // the compiler at once, it can do a whole-program optimization.
2492 template <class ELFT
>
2493 void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput
) {
2494 llvm::TimeTraceScope
timeScope("LTO");
2495 // Compile bitcode files and replace bitcode symbols.
2496 lto
.reset(new BitcodeCompiler
);
2497 for (BitcodeFile
*file
: ctx
.bitcodeFiles
)
2500 if (!ctx
.bitcodeFiles
.empty())
2501 markBuffersAsDontNeed(skipLinkedOutput
);
2503 for (InputFile
*file
: lto
->compile()) {
2504 auto *obj
= cast
<ObjFile
<ELFT
>>(file
);
2505 obj
->parse(/*ignoreComdats=*/true);
2507 // Parse '@' in symbol names for non-relocatable output.
2508 if (!config
->relocatable
)
2509 for (Symbol
*sym
: obj
->getGlobalSymbols())
2510 if (sym
->hasVersionSuffix
)
2511 sym
->parseSymbolVersion();
2512 ctx
.objectFiles
.push_back(obj
);
2516 // The --wrap option is a feature to rename symbols so that you can write
2517 // wrappers for existing functions. If you pass `--wrap=foo`, all
2518 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
2519 // expected to write `__wrap_foo` function as a wrapper). The original
2520 // symbol becomes accessible as `__real_foo`, so you can call that from your
2523 // This data structure is instantiated for each --wrap option.
2524 struct WrappedSymbol
{
2530 // Handles --wrap option.
2532 // This function instantiates wrapper symbols. At this point, they seem
2533 // like they are not being used at all, so we explicitly set some flags so
2534 // that LTO won't eliminate them.
2535 static std::vector
<WrappedSymbol
> addWrappedSymbols(opt::InputArgList
&args
) {
2536 std::vector
<WrappedSymbol
> v
;
2537 DenseSet
<StringRef
> seen
;
2539 for (auto *arg
: args
.filtered(OPT_wrap
)) {
2540 StringRef name
= arg
->getValue();
2541 if (!seen
.insert(name
).second
)
2544 Symbol
*sym
= symtab
.find(name
);
2549 symtab
.addUnusedUndefined(saver().save("__wrap_" + name
), sym
->binding
);
2551 // If __real_ is referenced, pull in the symbol if it is lazy. Do this after
2552 // processing __wrap_ as that may have referenced __real_.
2553 StringRef realName
= saver().save("__real_" + name
);
2554 if (symtab
.find(realName
))
2555 symtab
.addUnusedUndefined(name
, sym
->binding
);
2557 Symbol
*real
= symtab
.addUnusedUndefined(realName
);
2558 v
.push_back({sym
, real
, wrap
});
2560 // We want to tell LTO not to inline symbols to be overwritten
2561 // because LTO doesn't know the final symbol contents after renaming.
2562 real
->scriptDefined
= true;
2563 sym
->scriptDefined
= true;
2565 // If a symbol is referenced in any object file, bitcode file or shared
2566 // object, mark its redirection target (foo for __real_foo and __wrap_foo
2567 // for foo) as referenced after redirection, which will be used to tell LTO
2568 // to not eliminate the redirection target. If the object file defining the
2569 // symbol also references it, we cannot easily distinguish the case from
2570 // cases where the symbol is not referenced. Retain the redirection target
2571 // in this case because we choose to wrap symbol references regardless of
2572 // whether the symbol is defined
2573 // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
2574 if (real
->referenced
|| real
->isDefined())
2575 sym
->referencedAfterWrap
= true;
2576 if (sym
->referenced
|| sym
->isDefined())
2577 wrap
->referencedAfterWrap
= true;
2582 static void combineVersionedSymbol(Symbol
&sym
,
2583 DenseMap
<Symbol
*, Symbol
*> &map
) {
2584 const char *suffix1
= sym
.getVersionSuffix();
2585 if (suffix1
[0] != '@' || suffix1
[1] == '@')
2588 // Check the existing symbol foo. We have two special cases to handle:
2590 // * There is a definition of foo@v1 and foo@@v1.
2591 // * There is a definition of foo@v1 and foo.
2592 Defined
*sym2
= dyn_cast_or_null
<Defined
>(symtab
.find(sym
.getName()));
2595 const char *suffix2
= sym2
->getVersionSuffix();
2596 if (suffix2
[0] == '@' && suffix2
[1] == '@' &&
2597 strcmp(suffix1
+ 1, suffix2
+ 2) == 0) {
2598 // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
2599 map
.try_emplace(&sym
, sym2
);
2600 // If both foo@v1 and foo@@v1 are defined and non-weak, report a
2601 // duplicate definition error.
2602 if (sym
.isDefined()) {
2603 sym2
->checkDuplicate(cast
<Defined
>(sym
));
2604 sym2
->resolve(cast
<Defined
>(sym
));
2605 } else if (sym
.isUndefined()) {
2606 sym2
->resolve(cast
<Undefined
>(sym
));
2608 sym2
->resolve(cast
<SharedSymbol
>(sym
));
2610 // Eliminate foo@v1 from the symbol table.
2611 sym
.symbolKind
= Symbol::PlaceholderKind
;
2612 sym
.isUsedInRegularObj
= false;
2613 } else if (auto *sym1
= dyn_cast
<Defined
>(&sym
)) {
2614 if (sym2
->versionId
> VER_NDX_GLOBAL
2615 ? config
->versionDefinitions
[sym2
->versionId
].name
== suffix1
+ 1
2616 : sym1
->section
== sym2
->section
&& sym1
->value
== sym2
->value
) {
2617 // Due to an assembler design flaw, if foo is defined, .symver foo,
2618 // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2619 // different version, GNU ld makes foo@v1 canonical and eliminates
2620 // foo. Emulate its behavior, otherwise we would have foo or foo@@v1
2621 // beside foo@v1. foo@v1 and foo combining does not apply if they are
2622 // not defined in the same place.
2623 map
.try_emplace(sym2
, &sym
);
2624 sym2
->symbolKind
= Symbol::PlaceholderKind
;
2625 sym2
->isUsedInRegularObj
= false;
2630 // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
2632 // When this function is executed, only InputFiles and symbol table
2633 // contain pointers to symbol objects. We visit them to replace pointers,
2634 // so that wrapped symbols are swapped as instructed by the command line.
2635 static void redirectSymbols(ArrayRef
<WrappedSymbol
> wrapped
) {
2636 llvm::TimeTraceScope
timeScope("Redirect symbols");
2637 DenseMap
<Symbol
*, Symbol
*> map
;
2638 for (const WrappedSymbol
&w
: wrapped
) {
2639 map
[w
.sym
] = w
.wrap
;
2640 map
[w
.real
] = w
.sym
;
2643 // If there are version definitions (versionDefinitions.size() > 2), enumerate
2644 // symbols with a non-default version (foo@v1) and check whether it should be
2645 // combined with foo or foo@@v1.
2646 if (config
->versionDefinitions
.size() > 2)
2647 for (Symbol
*sym
: symtab
.getSymbols())
2648 if (sym
->hasVersionSuffix
)
2649 combineVersionedSymbol(*sym
, map
);
2654 // Update pointers in input files.
2655 parallelForEach(ctx
.objectFiles
, [&](ELFFileBase
*file
) {
2656 for (Symbol
*&sym
: file
->getMutableGlobalSymbols())
2657 if (Symbol
*s
= map
.lookup(sym
))
2661 // Update pointers in the symbol table.
2662 for (const WrappedSymbol
&w
: wrapped
)
2663 symtab
.wrap(w
.sym
, w
.real
, w
.wrap
);
2666 static void reportMissingFeature(StringRef config
, const Twine
&report
) {
2667 if (config
== "error")
2669 else if (config
== "warning")
2673 static void checkAndReportMissingFeature(StringRef config
, uint32_t features
,
2674 uint32_t mask
, const Twine
&report
) {
2675 if (!(features
& mask
))
2676 reportMissingFeature(config
, report
);
2679 // To enable CET (x86's hardware-assisted control flow enforcement), each
2680 // source file must be compiled with -fcf-protection. Object files compiled
2681 // with the flag contain feature flags indicating that they are compatible
2682 // with CET. We enable the feature only when all object files are compatible
2685 // This is also the case with AARCH64's BTI and PAC which use the similar
2686 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
2688 // For AArch64 PAuth-enabled object files, the core info of all of them must
2689 // match. Missing info for some object files with matching info for remaining
2690 // ones can be allowed (see -z pauth-report).
2691 static void readSecurityNotes() {
2692 if (config
->emachine
!= EM_386
&& config
->emachine
!= EM_X86_64
&&
2693 config
->emachine
!= EM_AARCH64
)
2696 config
->andFeatures
= -1;
2698 StringRef referenceFileName
;
2699 if (config
->emachine
== EM_AARCH64
) {
2700 auto it
= llvm::find_if(ctx
.objectFiles
, [](const ELFFileBase
*f
) {
2701 return !f
->aarch64PauthAbiCoreInfo
.empty();
2703 if (it
!= ctx
.objectFiles
.end()) {
2704 ctx
.aarch64PauthAbiCoreInfo
= (*it
)->aarch64PauthAbiCoreInfo
;
2705 referenceFileName
= (*it
)->getName();
2709 for (ELFFileBase
*f
: ctx
.objectFiles
) {
2710 uint32_t features
= f
->andFeatures
;
2712 checkAndReportMissingFeature(
2713 config
->zBtiReport
, features
, GNU_PROPERTY_AARCH64_FEATURE_1_BTI
,
2714 toString(f
) + ": -z bti-report: file does not have "
2715 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2717 checkAndReportMissingFeature(
2718 config
->zGcsReport
, features
, GNU_PROPERTY_AARCH64_FEATURE_1_GCS
,
2719 toString(f
) + ": -z gcs-report: file does not have "
2720 "GNU_PROPERTY_AARCH64_FEATURE_1_GCS property");
2722 checkAndReportMissingFeature(
2723 config
->zCetReport
, features
, GNU_PROPERTY_X86_FEATURE_1_IBT
,
2724 toString(f
) + ": -z cet-report: file does not have "
2725 "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2727 checkAndReportMissingFeature(
2728 config
->zCetReport
, features
, GNU_PROPERTY_X86_FEATURE_1_SHSTK
,
2729 toString(f
) + ": -z cet-report: file does not have "
2730 "GNU_PROPERTY_X86_FEATURE_1_SHSTK property");
2732 if (config
->zForceBti
&& !(features
& GNU_PROPERTY_AARCH64_FEATURE_1_BTI
)) {
2733 features
|= GNU_PROPERTY_AARCH64_FEATURE_1_BTI
;
2734 if (config
->zBtiReport
== "none")
2735 warn(toString(f
) + ": -z force-bti: file does not have "
2736 "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2737 } else if (config
->zForceIbt
&&
2738 !(features
& GNU_PROPERTY_X86_FEATURE_1_IBT
)) {
2739 if (config
->zCetReport
== "none")
2740 warn(toString(f
) + ": -z force-ibt: file does not have "
2741 "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2742 features
|= GNU_PROPERTY_X86_FEATURE_1_IBT
;
2744 if (config
->zPacPlt
&& !(features
& GNU_PROPERTY_AARCH64_FEATURE_1_PAC
)) {
2745 warn(toString(f
) + ": -z pac-plt: file does not have "
2746 "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
2747 features
|= GNU_PROPERTY_AARCH64_FEATURE_1_PAC
;
2749 config
->andFeatures
&= features
;
2751 if (ctx
.aarch64PauthAbiCoreInfo
.empty())
2754 if (f
->aarch64PauthAbiCoreInfo
.empty()) {
2755 reportMissingFeature(config
->zPauthReport
,
2757 ": -z pauth-report: file does not have AArch64 "
2758 "PAuth core info while '" +
2759 referenceFileName
+ "' has one");
2763 if (ctx
.aarch64PauthAbiCoreInfo
!= f
->aarch64PauthAbiCoreInfo
)
2764 errorOrWarn("incompatible values of AArch64 PAuth core info found\n>>> " +
2765 referenceFileName
+ ": 0x" +
2766 toHex(ctx
.aarch64PauthAbiCoreInfo
, /*LowerCase=*/true) +
2767 "\n>>> " + toString(f
) + ": 0x" +
2768 toHex(f
->aarch64PauthAbiCoreInfo
, /*LowerCase=*/true));
2771 // Force enable Shadow Stack.
2773 config
->andFeatures
|= GNU_PROPERTY_X86_FEATURE_1_SHSTK
;
2775 // Force enable/disable GCS
2776 if (config
->zGcs
== GcsPolicy::Always
)
2777 config
->andFeatures
|= GNU_PROPERTY_AARCH64_FEATURE_1_GCS
;
2778 else if (config
->zGcs
== GcsPolicy::Never
)
2779 config
->andFeatures
&= ~GNU_PROPERTY_AARCH64_FEATURE_1_GCS
;
2782 static void initSectionsAndLocalSyms(ELFFileBase
*file
, bool ignoreComdats
) {
2783 switch (file
->ekind
) {
2785 cast
<ObjFile
<ELF32LE
>>(file
)->initSectionsAndLocalSyms(ignoreComdats
);
2788 cast
<ObjFile
<ELF32BE
>>(file
)->initSectionsAndLocalSyms(ignoreComdats
);
2791 cast
<ObjFile
<ELF64LE
>>(file
)->initSectionsAndLocalSyms(ignoreComdats
);
2794 cast
<ObjFile
<ELF64BE
>>(file
)->initSectionsAndLocalSyms(ignoreComdats
);
2797 llvm_unreachable("");
2801 static void postParseObjectFile(ELFFileBase
*file
) {
2802 switch (file
->ekind
) {
2804 cast
<ObjFile
<ELF32LE
>>(file
)->postParse();
2807 cast
<ObjFile
<ELF32BE
>>(file
)->postParse();
2810 cast
<ObjFile
<ELF64LE
>>(file
)->postParse();
2813 cast
<ObjFile
<ELF64BE
>>(file
)->postParse();
2816 llvm_unreachable("");
2820 // Do actual linking. Note that when this function is called,
2821 // all linker scripts have already been parsed.
2822 template <class ELFT
> void LinkerDriver::link(opt::InputArgList
&args
) {
2823 llvm::TimeTraceScope
timeScope("Link", StringRef("LinkerDriver::Link"));
2825 // Handle --trace-symbol.
2826 for (auto *arg
: args
.filtered(OPT_trace_symbol
))
2827 symtab
.insert(arg
->getValue())->traced
= true;
2829 ctx
.internalFile
= createInternalFile("<internal>");
2831 // Handle -u/--undefined before input files. If both a.a and b.so define foo,
2832 // -u foo a.a b.so will extract a.a.
2833 for (StringRef name
: config
->undefined
)
2834 symtab
.addUnusedUndefined(name
)->referenced
= true;
2836 parseFiles(files
, armCmseImpLib
);
2838 // Create dynamic sections for dynamic linking and static PIE.
2839 config
->hasDynSymTab
= !ctx
.sharedFiles
.empty() || config
->isPic
;
2841 // If an entry symbol is in a static archive, pull out that file now.
2842 if (Symbol
*sym
= symtab
.find(config
->entry
))
2843 handleUndefined(sym
, "--entry");
2845 // Handle the `--undefined-glob <pattern>` options.
2846 for (StringRef pat
: args::getStrings(args
, OPT_undefined_glob
))
2847 handleUndefinedGlob(pat
);
2849 // After potential archive member extraction involving ENTRY and
2850 // -u/--undefined-glob, check whether PROVIDE symbols should be defined (the
2851 // RHS may refer to definitions in just extracted object files).
2852 script
->addScriptReferencedSymbolsToSymTable();
2854 // Prevent LTO from removing any definition referenced by -u.
2855 for (StringRef name
: config
->undefined
)
2856 if (Defined
*sym
= dyn_cast_or_null
<Defined
>(symtab
.find(name
)))
2857 sym
->isUsedInRegularObj
= true;
2859 // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2860 if (Symbol
*sym
= dyn_cast_or_null
<Defined
>(symtab
.find(config
->init
)))
2861 sym
->isUsedInRegularObj
= true;
2862 if (Symbol
*sym
= dyn_cast_or_null
<Defined
>(symtab
.find(config
->fini
)))
2863 sym
->isUsedInRegularObj
= true;
2865 // If any of our inputs are bitcode files, the LTO code generator may create
2866 // references to certain library functions that might not be explicit in the
2867 // bitcode file's symbol table. If any of those library functions are defined
2868 // in a bitcode file in an archive member, we need to arrange to use LTO to
2869 // compile those archive members by adding them to the link beforehand.
2871 // However, adding all libcall symbols to the link can have undesired
2872 // consequences. For example, the libgcc implementation of
2873 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
2874 // that aborts the program if the Linux kernel does not support 64-bit
2875 // atomics, which would prevent the program from running even if it does not
2876 // use 64-bit atomics.
2878 // Therefore, we only add libcall symbols to the link before LTO if we have
2879 // to, i.e. if the symbol's definition is in bitcode. Any other required
2880 // libcall symbols will be added to the link after LTO when we add the LTO
2881 // object file to the link.
2882 if (!ctx
.bitcodeFiles
.empty())
2883 for (auto *s
: lto::LTO::getRuntimeLibcallSymbols())
2886 // Archive members defining __wrap symbols may be extracted.
2887 std::vector
<WrappedSymbol
> wrapped
= addWrappedSymbols(args
);
2889 // No more lazy bitcode can be extracted at this point. Do post parse work
2890 // like checking duplicate symbols.
2891 parallelForEach(ctx
.objectFiles
, [](ELFFileBase
*file
) {
2892 initSectionsAndLocalSyms(file
, /*ignoreComdats=*/false);
2894 parallelForEach(ctx
.objectFiles
, postParseObjectFile
);
2895 parallelForEach(ctx
.bitcodeFiles
,
2896 [](BitcodeFile
*file
) { file
->postParse(); });
2897 for (auto &it
: ctx
.nonPrevailingSyms
) {
2898 Symbol
&sym
= *it
.first
;
2899 Undefined(sym
.file
, sym
.getName(), sym
.binding
, sym
.stOther
, sym
.type
,
2902 cast
<Undefined
>(sym
).nonPrevailing
= true;
2904 ctx
.nonPrevailingSyms
.clear();
2905 for (const DuplicateSymbol
&d
: ctx
.duplicates
)
2906 reportDuplicate(*d
.sym
, d
.file
, d
.section
, d
.value
);
2907 ctx
.duplicates
.clear();
2909 // Return if there were name resolution errors.
2913 // We want to declare linker script's symbols early,
2914 // so that we can version them.
2915 // They also might be exported if referenced by DSOs.
2916 script
->declareSymbols();
2918 // Handle --exclude-libs. This is before scanVersionScript() due to a
2919 // workaround for Android ndk: for a defined versioned symbol in an archive
2920 // without a version node in the version script, Android does not expect a
2921 // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2922 // GNU ld errors in this case.
2923 if (args
.hasArg(OPT_exclude_libs
))
2926 // Create elfHeader early. We need a dummy section in
2927 // addReservedSymbols to mark the created symbols as not absolute.
2928 Out::elfHeader
= make
<OutputSection
>("", 0, SHF_ALLOC
);
2930 // We need to create some reserved symbols such as _end. Create them.
2931 if (!config
->relocatable
)
2932 addReservedSymbols();
2934 // Apply version scripts.
2936 // For a relocatable output, version scripts don't make sense, and
2937 // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
2938 // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2939 if (!config
->relocatable
) {
2940 llvm::TimeTraceScope
timeScope("Process symbol versions");
2941 symtab
.scanVersionScript();
2944 // Skip the normal linked output if some LTO options are specified.
2946 // For --thinlto-index-only, index file creation is performed in
2947 // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and
2948 // --plugin-opt=emit-asm create output files in bitcode or assembly code,
2949 // respectively. When only certain thinLTO modules are specified for
2950 // compilation, the intermediate object file are the expected output.
2951 const bool skipLinkedOutput
= config
->thinLTOIndexOnly
|| config
->emitLLVM
||
2952 config
->ltoEmitAsm
||
2953 !config
->thinLTOModulesToCompile
.empty();
2955 // Handle --lto-validate-all-vtables-have-type-infos.
2956 if (config
->ltoValidateAllVtablesHaveTypeInfos
)
2957 ltoValidateAllVtablesHaveTypeInfos
<ELFT
>(args
);
2959 // Do link-time optimization if given files are LLVM bitcode files.
2960 // This compiles bitcode files into real object files.
2962 // With this the symbol table should be complete. After this, no new names
2963 // except a few linker-synthesized ones will be added to the symbol table.
2964 const size_t numObjsBeforeLTO
= ctx
.objectFiles
.size();
2965 compileBitcodeFiles
<ELFT
>(skipLinkedOutput
);
2967 // Symbol resolution finished. Report backward reference problems,
2968 // --print-archive-stats=, and --why-extract=.
2970 writeArchiveStats();
2975 // Bail out if normal linked output is skipped due to LTO.
2976 if (skipLinkedOutput
)
2979 // compileBitcodeFiles may have produced lto.tmp object files. After this, no
2980 // more file will be added.
2981 auto newObjectFiles
= ArrayRef(ctx
.objectFiles
).slice(numObjsBeforeLTO
);
2982 parallelForEach(newObjectFiles
, [](ELFFileBase
*file
) {
2983 initSectionsAndLocalSyms(file
, /*ignoreComdats=*/true);
2985 parallelForEach(newObjectFiles
, postParseObjectFile
);
2986 for (const DuplicateSymbol
&d
: ctx
.duplicates
)
2987 reportDuplicate(*d
.sym
, d
.file
, d
.section
, d
.value
);
2989 // Handle --exclude-libs again because lto.tmp may reference additional
2990 // libcalls symbols defined in an excluded archive. This may override
2991 // versionId set by scanVersionScript().
2992 if (args
.hasArg(OPT_exclude_libs
))
2995 // Record [__acle_se_<sym>, <sym>] pairs for later processing.
2996 processArmCmseSymbols();
2998 // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
2999 redirectSymbols(wrapped
);
3001 // Replace common symbols with regular symbols.
3002 replaceCommonSymbols();
3005 llvm::TimeTraceScope
timeScope("Aggregate sections");
3006 // Now that we have a complete list of input files.
3007 // Beyond this point, no new files are added.
3008 // Aggregate all input sections into one place.
3009 for (InputFile
*f
: ctx
.objectFiles
) {
3010 for (InputSectionBase
*s
: f
->getSections()) {
3011 if (!s
|| s
== &InputSection::discarded
)
3013 if (LLVM_UNLIKELY(isa
<EhInputSection
>(s
)))
3014 ctx
.ehInputSections
.push_back(cast
<EhInputSection
>(s
));
3016 ctx
.inputSections
.push_back(s
);
3019 for (BinaryFile
*f
: ctx
.binaryFiles
)
3020 for (InputSectionBase
*s
: f
->getSections())
3021 ctx
.inputSections
.push_back(cast
<InputSection
>(s
));
3025 llvm::TimeTraceScope
timeScope("Strip sections");
3026 if (ctx
.hasSympart
.load(std::memory_order_relaxed
)) {
3027 llvm::erase_if(ctx
.inputSections
, [](InputSectionBase
*s
) {
3028 if (s
->type
!= SHT_LLVM_SYMPART
)
3030 readSymbolPartitionSection
<ELFT
>(s
);
3034 // We do not want to emit debug sections if --strip-all
3035 // or --strip-debug are given.
3036 if (config
->strip
!= StripPolicy::None
) {
3037 llvm::erase_if(ctx
.inputSections
, [](InputSectionBase
*s
) {
3038 if (isDebugSection(*s
))
3040 if (auto *isec
= dyn_cast
<InputSection
>(s
))
3041 if (InputSectionBase
*rel
= isec
->getRelocatedSection())
3042 if (isDebugSection(*rel
))
3050 // Since we now have a complete set of input files, we can create
3051 // a .d file to record build dependencies.
3052 if (!config
->dependencyFile
.empty())
3053 writeDependencyFile();
3055 // Now that the number of partitions is fixed, save a pointer to the main
3057 mainPart
= &partitions
[0];
3059 // Read .note.gnu.property sections from input object files which
3060 // contain a hint to tweak linker's and loader's behaviors.
3061 readSecurityNotes();
3063 // The Target instance handles target-specific stuff, such as applying
3064 // relocations or writing a PLT section. It also contains target-dependent
3065 // values such as a default image base address.
3066 target
= getTarget();
3068 config
->eflags
= target
->calcEFlags();
3069 // maxPageSize (sometimes called abi page size) is the maximum page size that
3070 // the output can be run on. For example if the OS can use 4k or 64k page
3071 // sizes then maxPageSize must be 64k for the output to be useable on both.
3072 // All important alignment decisions must use this value.
3073 config
->maxPageSize
= getMaxPageSize(args
);
3074 // commonPageSize is the most common page size that the output will be run on.
3075 // For example if an OS can use 4k or 64k page sizes and 4k is more common
3076 // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
3077 // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
3078 // is limited to writing trap instructions on the last executable segment.
3079 config
->commonPageSize
= getCommonPageSize(args
);
3081 config
->imageBase
= getImageBase(args
);
3083 // This adds a .comment section containing a version string.
3084 if (!config
->relocatable
)
3085 ctx
.inputSections
.push_back(createCommentSection());
3087 // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
3088 splitSections
<ELFT
>();
3090 // Garbage collection and removal of shared symbols from unused shared objects.
3093 // Make copies of any input sections that need to be copied into each
3095 copySectionsIntoPartitions();
3097 if (canHaveMemtagGlobals()) {
3098 llvm::TimeTraceScope
timeScope("Process memory tagged symbols");
3099 createTaggedSymbols(ctx
.objectFiles
);
3102 // Create synthesized sections such as .got and .plt. This is called before
3103 // processSectionCommands() so that they can be placed by SECTIONS commands.
3104 createSyntheticSections
<ELFT
>();
3106 // Some input sections that are used for exception handling need to be moved
3107 // into synthetic sections. Do that now so that they aren't assigned to
3108 // output sections in the usual way.
3109 if (!config
->relocatable
)
3110 combineEhSections();
3112 // Merge .riscv.attributes sections.
3113 if (config
->emachine
== EM_RISCV
)
3114 mergeRISCVAttributesSections();
3117 llvm::TimeTraceScope
timeScope("Assign sections");
3119 // Create output sections described by SECTIONS commands.
3120 script
->processSectionCommands();
3122 // Linker scripts control how input sections are assigned to output
3123 // sections. Input sections that were not handled by scripts are called
3124 // "orphans", and they are assigned to output sections by the default rule.
3126 script
->addOrphanSections();
3130 llvm::TimeTraceScope
timeScope("Merge/finalize input sections");
3132 // Migrate InputSectionDescription::sectionBases to sections. This includes
3133 // merging MergeInputSections into a single MergeSyntheticSection. From this
3134 // point onwards InputSectionDescription::sections should be used instead of
3136 for (SectionCommand
*cmd
: script
->sectionCommands
)
3137 if (auto *osd
= dyn_cast
<OutputDesc
>(cmd
))
3138 osd
->osec
.finalizeInputSections(&script
.s
);
3141 // Two input sections with different output sections should not be folded.
3142 // ICF runs after processSectionCommands() so that we know the output sections.
3143 if (config
->icf
!= ICFLevel::None
) {
3144 findKeepUniqueSections
<ELFT
>(args
);
3148 // Read the callgraph now that we know what was gced or icfed
3149 if (config
->callGraphProfileSort
!= CGProfileSortKind::None
) {
3150 if (auto *arg
= args
.getLastArg(OPT_call_graph_ordering_file
))
3151 if (std::optional
<MemoryBufferRef
> buffer
= readFile(arg
->getValue()))
3152 readCallGraph(*buffer
);
3153 readCallGraphsFromObjectFiles
<ELFT
>();
3156 // Write the result to the file.
3157 writeResult
<ELFT
>();