xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision bc08c3cb)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The driver drives the entire linking process. It is responsible for
10 // parsing command line options and doing whatever it is instructed to do.
11 //
12 // One notable thing in the LLD's driver when compared to other linkers is
13 // that the LLD's driver is agnostic on the host operating system.
14 // Other linkers usually have implicit default values (such as a dynamic
15 // linker path or library paths) for each host OS.
16 //
17 // I don't think implicit default values are useful because they are
18 // usually explicitly specified by the compiler driver. They can even
19 // be harmful when you are doing cross-linking. Therefore, in LLD, we
20 // simply trust the compiler driver to pass all required options and
21 // don't try to make effort on our side.
22 //
23 //===----------------------------------------------------------------------===//
24 
25 #include "Driver.h"
26 #include "Config.h"
27 #include "ICF.h"
28 #include "InputFiles.h"
29 #include "InputSection.h"
30 #include "LinkerScript.h"
31 #include "MarkLive.h"
32 #include "OutputSections.h"
33 #include "ScriptParser.h"
34 #include "SymbolTable.h"
35 #include "Symbols.h"
36 #include "SyntheticSections.h"
37 #include "Target.h"
38 #include "Writer.h"
39 #include "lld/Common/Args.h"
40 #include "lld/Common/Driver.h"
41 #include "lld/Common/ErrorHandler.h"
42 #include "lld/Common/Filesystem.h"
43 #include "lld/Common/Memory.h"
44 #include "lld/Common/Strings.h"
45 #include "lld/Common/TargetOptionsCommandFlags.h"
46 #include "lld/Common/Version.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/ADT/StringSwitch.h"
50 #include "llvm/Config/llvm-config.h"
51 #include "llvm/LTO/LTO.h"
52 #include "llvm/Object/Archive.h"
53 #include "llvm/Remarks/HotnessThresholdParser.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Compression.h"
56 #include "llvm/Support/FileSystem.h"
57 #include "llvm/Support/GlobPattern.h"
58 #include "llvm/Support/LEB128.h"
59 #include "llvm/Support/Parallel.h"
60 #include "llvm/Support/Path.h"
61 #include "llvm/Support/TarWriter.h"
62 #include "llvm/Support/TargetSelect.h"
63 #include "llvm/Support/TimeProfiler.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include <cstdlib>
66 #include <utility>
67 
68 using namespace llvm;
69 using namespace llvm::ELF;
70 using namespace llvm::object;
71 using namespace llvm::sys;
72 using namespace llvm::support;
73 using namespace lld;
74 using namespace lld::elf;
75 
76 std::unique_ptr<Configuration> elf::config;
77 std::unique_ptr<Ctx> elf::ctx;
78 std::unique_ptr<LinkerDriver> elf::driver;
79 
80 static void setConfigs(opt::InputArgList &args);
81 static void readConfigs(opt::InputArgList &args);
82 
83 void elf::errorOrWarn(const Twine &msg) {
84   if (config->noinhibitExec)
85     warn(msg);
86   else
87     error(msg);
88 }
89 
90 bool elf::link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
91                llvm::raw_ostream &stderrOS, bool exitEarly,
92                bool disableOutput) {
93   // This driver-specific context will be freed later by lldMain().
94   auto *ctx = new CommonLinkerContext;
95 
96   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
97   ctx->e.cleanupCallback = []() {
98     inputSections.clear();
99     outputSections.clear();
100     symAux.clear();
101 
102     tar = nullptr;
103     in.reset();
104 
105     partitions.clear();
106     partitions.emplace_back();
107 
108     SharedFile::vernauxNum = 0;
109   };
110   ctx->e.logName = args::getFilenameWithoutExe(args[0]);
111   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use "
112                                  "--error-limit=0 to see all errors)";
113 
114   config = std::make_unique<Configuration>();
115   elf::ctx = std::make_unique<Ctx>();
116   driver = std::make_unique<LinkerDriver>();
117   script = std::make_unique<LinkerScript>();
118   symtab = std::make_unique<SymbolTable>();
119 
120   partitions.clear();
121   partitions.emplace_back();
122 
123   config->progName = args[0];
124 
125   driver->linkerMain(args);
126 
127   return errorCount() == 0;
128 }
129 
130 // Parses a linker -m option.
131 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
132   uint8_t osabi = 0;
133   StringRef s = emul;
134   if (s.endswith("_fbsd")) {
135     s = s.drop_back(5);
136     osabi = ELFOSABI_FREEBSD;
137   }
138 
139   std::pair<ELFKind, uint16_t> ret =
140       StringSwitch<std::pair<ELFKind, uint16_t>>(s)
141           .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
142           .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})
143           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
144           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
145           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
146           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
147           .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
148           .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
149           .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})
150           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
151           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
152           .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
153           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
154           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
155           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
156           .Case("elf_i386", {ELF32LEKind, EM_386})
157           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
158           .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
159           .Case("msp430elf", {ELF32LEKind, EM_MSP430})
160           .Default({ELFNoneKind, EM_NONE});
161 
162   if (ret.first == ELFNoneKind)
163     error("unknown emulation: " + emul);
164   if (ret.second == EM_MSP430)
165     osabi = ELFOSABI_STANDALONE;
166   return std::make_tuple(ret.first, ret.second, osabi);
167 }
168 
169 // Returns slices of MB by parsing MB as an archive file.
170 // Each slice consists of a member file in the archive.
171 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
172     MemoryBufferRef mb) {
173   std::unique_ptr<Archive> file =
174       CHECK(Archive::create(mb),
175             mb.getBufferIdentifier() + ": failed to parse archive");
176 
177   std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
178   Error err = Error::success();
179   bool addToTar = file->isThin() && tar;
180   for (const Archive::Child &c : file->children(err)) {
181     MemoryBufferRef mbref =
182         CHECK(c.getMemoryBufferRef(),
183               mb.getBufferIdentifier() +
184                   ": could not get the buffer for a child of the archive");
185     if (addToTar)
186       tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
187     v.push_back(std::make_pair(mbref, c.getChildOffset()));
188   }
189   if (err)
190     fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
191           toString(std::move(err)));
192 
193   // Take ownership of memory buffers created for members of thin archives.
194   std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers();
195   std::move(mbs.begin(), mbs.end(), std::back_inserter(ctx->memoryBuffers));
196 
197   return v;
198 }
199 
200 // Opens a file and create a file object. Path has to be resolved already.
201 void LinkerDriver::addFile(StringRef path, bool withLOption) {
202   using namespace sys::fs;
203 
204   Optional<MemoryBufferRef> buffer = readFile(path);
205   if (!buffer)
206     return;
207   MemoryBufferRef mbref = *buffer;
208 
209   if (config->formatBinary) {
210     files.push_back(make<BinaryFile>(mbref));
211     return;
212   }
213 
214   switch (identify_magic(mbref.getBuffer())) {
215   case file_magic::unknown:
216     readLinkerScript(mbref);
217     return;
218   case file_magic::archive: {
219     if (inWholeArchive) {
220       for (const auto &p : getArchiveMembers(mbref))
221         files.push_back(createObjectFile(p.first, path, p.second));
222       return;
223     }
224 
225     auto members = getArchiveMembers(mbref);
226     archiveFiles.emplace_back(path, members.size());
227 
228     // Handle archives and --start-lib/--end-lib using the same code path. This
229     // scans all the ELF relocatable object files and bitcode files in the
230     // archive rather than just the index file, with the benefit that the
231     // symbols are only loaded once. For many projects archives see high
232     // utilization rates and it is a net performance win. --start-lib scans
233     // symbols in the same order that llvm-ar adds them to the index, so in the
234     // common case the semantics are identical. If the archive symbol table was
235     // created in a different order, or is incomplete, this strategy has
236     // different semantics. Such output differences are considered user error.
237     //
238     // All files within the archive get the same group ID to allow mutual
239     // references for --warn-backrefs.
240     bool saved = InputFile::isInGroup;
241     InputFile::isInGroup = true;
242     for (const std::pair<MemoryBufferRef, uint64_t> &p : members) {
243       auto magic = identify_magic(p.first.getBuffer());
244       if (magic == file_magic::bitcode || magic == file_magic::elf_relocatable)
245         files.push_back(createLazyFile(p.first, path, p.second));
246       else
247         warn(path + ": archive member '" + p.first.getBufferIdentifier() +
248              "' is neither ET_REL nor LLVM bitcode");
249     }
250     InputFile::isInGroup = saved;
251     if (!saved)
252       ++InputFile::nextGroupId;
253     return;
254   }
255   case file_magic::elf_shared_object:
256     if (config->isStatic || config->relocatable) {
257       error("attempted static link of dynamic object " + path);
258       return;
259     }
260 
261     // Shared objects are identified by soname. soname is (if specified)
262     // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
263     // the directory part is ignored. Note that path may be a temporary and
264     // cannot be stored into SharedFile::soName.
265     path = mbref.getBufferIdentifier();
266     files.push_back(
267         make<SharedFile>(mbref, withLOption ? path::filename(path) : path));
268     return;
269   case file_magic::bitcode:
270   case file_magic::elf_relocatable:
271     if (inLib)
272       files.push_back(createLazyFile(mbref, "", 0));
273     else
274       files.push_back(createObjectFile(mbref));
275     break;
276   default:
277     error(path + ": unknown file type");
278   }
279 }
280 
281 // Add a given library by searching it from input search paths.
282 void LinkerDriver::addLibrary(StringRef name) {
283   if (Optional<std::string> path = searchLibrary(name))
284     addFile(*path, /*withLOption=*/true);
285   else
286     error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
287 }
288 
289 // This function is called on startup. We need this for LTO since
290 // LTO calls LLVM functions to compile bitcode files to native code.
291 // Technically this can be delayed until we read bitcode files, but
292 // we don't bother to do lazily because the initialization is fast.
293 static void initLLVM() {
294   InitializeAllTargets();
295   InitializeAllTargetMCs();
296   InitializeAllAsmPrinters();
297   InitializeAllAsmParsers();
298 }
299 
300 // Some command line options or some combinations of them are not allowed.
301 // This function checks for such errors.
302 static void checkOptions() {
303   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
304   // table which is a relatively new feature.
305   if (config->emachine == EM_MIPS && config->gnuHash)
306     error("the .gnu.hash section is not compatible with the MIPS target");
307 
308   if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
309     error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
310 
311   if (config->fixCortexA8 && config->emachine != EM_ARM)
312     error("--fix-cortex-a8 is only supported on ARM targets");
313 
314   if (config->tocOptimize && config->emachine != EM_PPC64)
315     error("--toc-optimize is only supported on PowerPC64 targets");
316 
317   if (config->pcRelOptimize && config->emachine != EM_PPC64)
318     error("--pcrel-optimize is only supported on PowerPC64 targets");
319 
320   if (config->pie && config->shared)
321     error("-shared and -pie may not be used together");
322 
323   if (!config->shared && !config->filterList.empty())
324     error("-F may not be used without -shared");
325 
326   if (!config->shared && !config->auxiliaryList.empty())
327     error("-f may not be used without -shared");
328 
329   if (config->strip == StripPolicy::All && config->emitRelocs)
330     error("--strip-all and --emit-relocs may not be used together");
331 
332   if (config->zText && config->zIfuncNoplt)
333     error("-z text and -z ifunc-noplt may not be used together");
334 
335   if (config->relocatable) {
336     if (config->shared)
337       error("-r and -shared may not be used together");
338     if (config->gdbIndex)
339       error("-r and --gdb-index may not be used together");
340     if (config->icf != ICFLevel::None)
341       error("-r and --icf may not be used together");
342     if (config->pie)
343       error("-r and -pie may not be used together");
344     if (config->exportDynamic)
345       error("-r and --export-dynamic may not be used together");
346   }
347 
348   if (config->executeOnly) {
349     if (config->emachine != EM_AARCH64)
350       error("--execute-only is only supported on AArch64 targets");
351 
352     if (config->singleRoRx && !script->hasSectionsCommand)
353       error("--execute-only and --no-rosegment cannot be used together");
354   }
355 
356   if (config->zRetpolineplt && config->zForceIbt)
357     error("-z force-ibt may not be used with -z retpolineplt");
358 
359   if (config->emachine != EM_AARCH64) {
360     if (config->zPacPlt)
361       error("-z pac-plt only supported on AArch64");
362     if (config->zForceBti)
363       error("-z force-bti only supported on AArch64");
364     if (config->zBtiReport != "none")
365       error("-z bti-report only supported on AArch64");
366   }
367 
368   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
369       config->zCetReport != "none")
370     error("-z cet-report only supported on X86 and X86_64");
371 }
372 
373 static const char *getReproduceOption(opt::InputArgList &args) {
374   if (auto *arg = args.getLastArg(OPT_reproduce))
375     return arg->getValue();
376   return getenv("LLD_REPRODUCE");
377 }
378 
379 static bool hasZOption(opt::InputArgList &args, StringRef key) {
380   for (auto *arg : args.filtered(OPT_z))
381     if (key == arg->getValue())
382       return true;
383   return false;
384 }
385 
386 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
387                      bool Default) {
388   for (auto *arg : args.filtered_reverse(OPT_z)) {
389     if (k1 == arg->getValue())
390       return true;
391     if (k2 == arg->getValue())
392       return false;
393   }
394   return Default;
395 }
396 
397 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
398   for (auto *arg : args.filtered_reverse(OPT_z)) {
399     StringRef v = arg->getValue();
400     if (v == "noseparate-code")
401       return SeparateSegmentKind::None;
402     if (v == "separate-code")
403       return SeparateSegmentKind::Code;
404     if (v == "separate-loadable-segments")
405       return SeparateSegmentKind::Loadable;
406   }
407   return SeparateSegmentKind::None;
408 }
409 
410 static GnuStackKind getZGnuStack(opt::InputArgList &args) {
411   for (auto *arg : args.filtered_reverse(OPT_z)) {
412     if (StringRef("execstack") == arg->getValue())
413       return GnuStackKind::Exec;
414     if (StringRef("noexecstack") == arg->getValue())
415       return GnuStackKind::NoExec;
416     if (StringRef("nognustack") == arg->getValue())
417       return GnuStackKind::None;
418   }
419 
420   return GnuStackKind::NoExec;
421 }
422 
423 static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
424   for (auto *arg : args.filtered_reverse(OPT_z)) {
425     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
426     if (kv.first == "start-stop-visibility") {
427       if (kv.second == "default")
428         return STV_DEFAULT;
429       else if (kv.second == "internal")
430         return STV_INTERNAL;
431       else if (kv.second == "hidden")
432         return STV_HIDDEN;
433       else if (kv.second == "protected")
434         return STV_PROTECTED;
435       error("unknown -z start-stop-visibility= value: " + StringRef(kv.second));
436     }
437   }
438   return STV_PROTECTED;
439 }
440 
441 constexpr const char *knownZFlags[] = {
442     "combreloc",
443     "copyreloc",
444     "defs",
445     "execstack",
446     "force-bti",
447     "force-ibt",
448     "global",
449     "hazardplt",
450     "ifunc-noplt",
451     "initfirst",
452     "interpose",
453     "keep-text-section-prefix",
454     "lazy",
455     "muldefs",
456     "nocombreloc",
457     "nocopyreloc",
458     "nodefaultlib",
459     "nodelete",
460     "nodlopen",
461     "noexecstack",
462     "nognustack",
463     "nokeep-text-section-prefix",
464     "nopack-relative-relocs",
465     "norelro",
466     "noseparate-code",
467     "nostart-stop-gc",
468     "notext",
469     "now",
470     "origin",
471     "pac-plt",
472     "pack-relative-relocs",
473     "rel",
474     "rela",
475     "relro",
476     "retpolineplt",
477     "rodynamic",
478     "separate-code",
479     "separate-loadable-segments",
480     "shstk",
481     "start-stop-gc",
482     "text",
483     "undefs",
484     "wxneeded",
485 };
486 
487 static bool isKnownZFlag(StringRef s) {
488   return llvm::is_contained(knownZFlags, s) ||
489          s.startswith("common-page-size=") || s.startswith("bti-report=") ||
490          s.startswith("cet-report=") ||
491          s.startswith("dead-reloc-in-nonalloc=") ||
492          s.startswith("max-page-size=") || s.startswith("stack-size=") ||
493          s.startswith("start-stop-visibility=");
494 }
495 
496 // Report a warning for an unknown -z option.
497 static void checkZOptions(opt::InputArgList &args) {
498   for (auto *arg : args.filtered(OPT_z))
499     if (!isKnownZFlag(arg->getValue()))
500       warn("unknown -z value: " + StringRef(arg->getValue()));
501 }
502 
503 constexpr const char *saveTempsValues[] = {
504     "resolution", "preopt",     "promote", "internalize",  "import",
505     "opt",        "precodegen", "prelink", "combinedindex"};
506 
507 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
508   ELFOptTable parser;
509   opt::InputArgList args = parser.parse(argsArr.slice(1));
510 
511   // Interpret these flags early because error()/warn() depend on them.
512   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
513   errorHandler().fatalWarnings =
514       args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
515   checkZOptions(args);
516 
517   // Handle -help
518   if (args.hasArg(OPT_help)) {
519     printHelp();
520     return;
521   }
522 
523   // Handle -v or -version.
524   //
525   // A note about "compatible with GNU linkers" message: this is a hack for
526   // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
527   // a GNU compatible linker. See
528   // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
529   //
530   // This is somewhat ugly hack, but in reality, we had no choice other
531   // than doing this. Considering the very long release cycle of Libtool,
532   // it is not easy to improve it to recognize LLD as a GNU compatible
533   // linker in a timely manner. Even if we can make it, there are still a
534   // lot of "configure" scripts out there that are generated by old version
535   // of Libtool. We cannot convince every software developer to migrate to
536   // the latest version and re-generate scripts. So we have this hack.
537   if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
538     message(getLLDVersion() + " (compatible with GNU linkers)");
539 
540   if (const char *path = getReproduceOption(args)) {
541     // Note that --reproduce is a debug option so you can ignore it
542     // if you are trying to understand the whole picture of the code.
543     Expected<std::unique_ptr<TarWriter>> errOrWriter =
544         TarWriter::create(path, path::stem(path));
545     if (errOrWriter) {
546       tar = std::move(*errOrWriter);
547       tar->append("response.txt", createResponseFile(args));
548       tar->append("version.txt", getLLDVersion() + "\n");
549       StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
550       if (!ltoSampleProfile.empty())
551         readFile(ltoSampleProfile);
552     } else {
553       error("--reproduce: " + toString(errOrWriter.takeError()));
554     }
555   }
556 
557   readConfigs(args);
558 
559   // The behavior of -v or --version is a bit strange, but this is
560   // needed for compatibility with GNU linkers.
561   if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
562     return;
563   if (args.hasArg(OPT_version))
564     return;
565 
566   // Initialize time trace profiler.
567   if (config->timeTraceEnabled)
568     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
569 
570   {
571     llvm::TimeTraceScope timeScope("ExecuteLinker");
572 
573     initLLVM();
574     createFiles(args);
575     if (errorCount())
576       return;
577 
578     inferMachineType();
579     setConfigs(args);
580     checkOptions();
581     if (errorCount())
582       return;
583 
584     // The Target instance handles target-specific stuff, such as applying
585     // relocations or writing a PLT section. It also contains target-dependent
586     // values such as a default image base address.
587     target = getTarget();
588 
589     link(args);
590   }
591 
592   if (config->timeTraceEnabled) {
593     checkError(timeTraceProfilerWrite(
594         args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
595     timeTraceProfilerCleanup();
596   }
597 }
598 
599 static std::string getRpath(opt::InputArgList &args) {
600   std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
601   return llvm::join(v.begin(), v.end(), ":");
602 }
603 
604 // Determines what we should do if there are remaining unresolved
605 // symbols after the name resolution.
606 static void setUnresolvedSymbolPolicy(opt::InputArgList &args) {
607   UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
608                                               OPT_warn_unresolved_symbols, true)
609                                      ? UnresolvedPolicy::ReportError
610                                      : UnresolvedPolicy::Warn;
611   // -shared implies --unresolved-symbols=ignore-all because missing
612   // symbols are likely to be resolved at runtime.
613   bool diagRegular = !config->shared, diagShlib = !config->shared;
614 
615   for (const opt::Arg *arg : args) {
616     switch (arg->getOption().getID()) {
617     case OPT_unresolved_symbols: {
618       StringRef s = arg->getValue();
619       if (s == "ignore-all") {
620         diagRegular = false;
621         diagShlib = false;
622       } else if (s == "ignore-in-object-files") {
623         diagRegular = false;
624         diagShlib = true;
625       } else if (s == "ignore-in-shared-libs") {
626         diagRegular = true;
627         diagShlib = false;
628       } else if (s == "report-all") {
629         diagRegular = true;
630         diagShlib = true;
631       } else {
632         error("unknown --unresolved-symbols value: " + s);
633       }
634       break;
635     }
636     case OPT_no_undefined:
637       diagRegular = true;
638       break;
639     case OPT_z:
640       if (StringRef(arg->getValue()) == "defs")
641         diagRegular = true;
642       else if (StringRef(arg->getValue()) == "undefs")
643         diagRegular = false;
644       break;
645     case OPT_allow_shlib_undefined:
646       diagShlib = false;
647       break;
648     case OPT_no_allow_shlib_undefined:
649       diagShlib = true;
650       break;
651     }
652   }
653 
654   config->unresolvedSymbols =
655       diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;
656   config->unresolvedSymbolsInShlib =
657       diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;
658 }
659 
660 static Target2Policy getTarget2(opt::InputArgList &args) {
661   StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
662   if (s == "rel")
663     return Target2Policy::Rel;
664   if (s == "abs")
665     return Target2Policy::Abs;
666   if (s == "got-rel")
667     return Target2Policy::GotRel;
668   error("unknown --target2 option: " + s);
669   return Target2Policy::GotRel;
670 }
671 
672 static bool isOutputFormatBinary(opt::InputArgList &args) {
673   StringRef s = args.getLastArgValue(OPT_oformat, "elf");
674   if (s == "binary")
675     return true;
676   if (!s.startswith("elf"))
677     error("unknown --oformat value: " + s);
678   return false;
679 }
680 
681 static DiscardPolicy getDiscard(opt::InputArgList &args) {
682   auto *arg =
683       args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
684   if (!arg)
685     return DiscardPolicy::Default;
686   if (arg->getOption().getID() == OPT_discard_all)
687     return DiscardPolicy::All;
688   if (arg->getOption().getID() == OPT_discard_locals)
689     return DiscardPolicy::Locals;
690   return DiscardPolicy::None;
691 }
692 
693 static StringRef getDynamicLinker(opt::InputArgList &args) {
694   auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
695   if (!arg)
696     return "";
697   if (arg->getOption().getID() == OPT_no_dynamic_linker) {
698     // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
699     config->noDynamicLinker = true;
700     return "";
701   }
702   return arg->getValue();
703 }
704 
705 static int getMemtagMode(opt::InputArgList &args) {
706   StringRef memtagModeArg = args.getLastArgValue(OPT_android_memtag_mode);
707   if (!config->androidMemtagHeap && !config->androidMemtagStack) {
708     if (!memtagModeArg.empty())
709       error("when using --android-memtag-mode, at least one of "
710             "--android-memtag-heap or "
711             "--android-memtag-stack is required");
712     return ELF::NT_MEMTAG_LEVEL_NONE;
713   }
714 
715   if (memtagModeArg == "sync" || memtagModeArg.empty())
716     return ELF::NT_MEMTAG_LEVEL_SYNC;
717   if (memtagModeArg == "async")
718     return ELF::NT_MEMTAG_LEVEL_ASYNC;
719   if (memtagModeArg == "none")
720     return ELF::NT_MEMTAG_LEVEL_NONE;
721 
722   error("unknown --android-memtag-mode value: \"" + memtagModeArg +
723         "\", should be one of {async, sync, none}");
724   return ELF::NT_MEMTAG_LEVEL_NONE;
725 }
726 
727 static ICFLevel getICF(opt::InputArgList &args) {
728   auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
729   if (!arg || arg->getOption().getID() == OPT_icf_none)
730     return ICFLevel::None;
731   if (arg->getOption().getID() == OPT_icf_safe)
732     return ICFLevel::Safe;
733   return ICFLevel::All;
734 }
735 
736 static StripPolicy getStrip(opt::InputArgList &args) {
737   if (args.hasArg(OPT_relocatable))
738     return StripPolicy::None;
739 
740   auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
741   if (!arg)
742     return StripPolicy::None;
743   if (arg->getOption().getID() == OPT_strip_all)
744     return StripPolicy::All;
745   return StripPolicy::Debug;
746 }
747 
748 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
749                                     const opt::Arg &arg) {
750   uint64_t va = 0;
751   if (s.startswith("0x"))
752     s = s.drop_front(2);
753   if (!to_integer(s, va, 16))
754     error("invalid argument: " + arg.getAsString(args));
755   return va;
756 }
757 
758 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
759   StringMap<uint64_t> ret;
760   for (auto *arg : args.filtered(OPT_section_start)) {
761     StringRef name;
762     StringRef addr;
763     std::tie(name, addr) = StringRef(arg->getValue()).split('=');
764     ret[name] = parseSectionAddress(addr, args, *arg);
765   }
766 
767   if (auto *arg = args.getLastArg(OPT_Ttext))
768     ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
769   if (auto *arg = args.getLastArg(OPT_Tdata))
770     ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
771   if (auto *arg = args.getLastArg(OPT_Tbss))
772     ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
773   return ret;
774 }
775 
776 static SortSectionPolicy getSortSection(opt::InputArgList &args) {
777   StringRef s = args.getLastArgValue(OPT_sort_section);
778   if (s == "alignment")
779     return SortSectionPolicy::Alignment;
780   if (s == "name")
781     return SortSectionPolicy::Name;
782   if (!s.empty())
783     error("unknown --sort-section rule: " + s);
784   return SortSectionPolicy::Default;
785 }
786 
787 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
788   StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
789   if (s == "warn")
790     return OrphanHandlingPolicy::Warn;
791   if (s == "error")
792     return OrphanHandlingPolicy::Error;
793   if (s != "place")
794     error("unknown --orphan-handling mode: " + s);
795   return OrphanHandlingPolicy::Place;
796 }
797 
798 // Parse --build-id or --build-id=<style>. We handle "tree" as a
799 // synonym for "sha1" because all our hash functions including
800 // --build-id=sha1 are actually tree hashes for performance reasons.
801 static std::pair<BuildIdKind, std::vector<uint8_t>>
802 getBuildId(opt::InputArgList &args) {
803   auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
804   if (!arg)
805     return {BuildIdKind::None, {}};
806 
807   if (arg->getOption().getID() == OPT_build_id)
808     return {BuildIdKind::Fast, {}};
809 
810   StringRef s = arg->getValue();
811   if (s == "fast")
812     return {BuildIdKind::Fast, {}};
813   if (s == "md5")
814     return {BuildIdKind::Md5, {}};
815   if (s == "sha1" || s == "tree")
816     return {BuildIdKind::Sha1, {}};
817   if (s == "uuid")
818     return {BuildIdKind::Uuid, {}};
819   if (s.startswith("0x"))
820     return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
821 
822   if (s != "none")
823     error("unknown --build-id style: " + s);
824   return {BuildIdKind::None, {}};
825 }
826 
827 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
828   StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
829   if (s == "android")
830     return {true, false};
831   if (s == "relr")
832     return {false, true};
833   if (s == "android+relr")
834     return {true, true};
835 
836   if (s != "none")
837     error("unknown --pack-dyn-relocs format: " + s);
838   return {false, false};
839 }
840 
841 static void readCallGraph(MemoryBufferRef mb) {
842   // Build a map from symbol name to section
843   DenseMap<StringRef, Symbol *> map;
844   for (ELFFileBase *file : ctx->objectFiles)
845     for (Symbol *sym : file->getSymbols())
846       map[sym->getName()] = sym;
847 
848   auto findSection = [&](StringRef name) -> InputSectionBase * {
849     Symbol *sym = map.lookup(name);
850     if (!sym) {
851       if (config->warnSymbolOrdering)
852         warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
853       return nullptr;
854     }
855     maybeWarnUnorderableSymbol(sym);
856 
857     if (Defined *dr = dyn_cast_or_null<Defined>(sym))
858       return dyn_cast_or_null<InputSectionBase>(dr->section);
859     return nullptr;
860   };
861 
862   for (StringRef line : args::getLines(mb)) {
863     SmallVector<StringRef, 3> fields;
864     line.split(fields, ' ');
865     uint64_t count;
866 
867     if (fields.size() != 3 || !to_integer(fields[2], count)) {
868       error(mb.getBufferIdentifier() + ": parse error");
869       return;
870     }
871 
872     if (InputSectionBase *from = findSection(fields[0]))
873       if (InputSectionBase *to = findSection(fields[1]))
874         config->callGraphProfile[std::make_pair(from, to)] += count;
875   }
876 }
877 
878 // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
879 // true and populates cgProfile and symbolIndices.
880 template <class ELFT>
881 static bool
882 processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices,
883                             ArrayRef<typename ELFT::CGProfile> &cgProfile,
884                             ObjFile<ELFT> *inputObj) {
885   if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
886     return false;
887 
888   ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
889       inputObj->template getELFShdrs<ELFT>();
890   symbolIndices.clear();
891   const ELFFile<ELFT> &obj = inputObj->getObj();
892   cgProfile =
893       check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(
894           objSections[inputObj->cgProfileSectionIndex]));
895 
896   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
897     const Elf_Shdr_Impl<ELFT> &sec = objSections[i];
898     if (sec.sh_info == inputObj->cgProfileSectionIndex) {
899       if (sec.sh_type == SHT_RELA) {
900         ArrayRef<typename ELFT::Rela> relas =
901             CHECK(obj.relas(sec), "could not retrieve cg profile rela section");
902         for (const typename ELFT::Rela &rel : relas)
903           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
904         break;
905       }
906       if (sec.sh_type == SHT_REL) {
907         ArrayRef<typename ELFT::Rel> rels =
908             CHECK(obj.rels(sec), "could not retrieve cg profile rel section");
909         for (const typename ELFT::Rel &rel : rels)
910           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
911         break;
912       }
913     }
914   }
915   if (symbolIndices.empty())
916     warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");
917   return !symbolIndices.empty();
918 }
919 
920 template <class ELFT> static void readCallGraphsFromObjectFiles() {
921   SmallVector<uint32_t, 32> symbolIndices;
922   ArrayRef<typename ELFT::CGProfile> cgProfile;
923   for (auto file : ctx->objectFiles) {
924     auto *obj = cast<ObjFile<ELFT>>(file);
925     if (!processCallGraphRelocations(symbolIndices, cgProfile, obj))
926       continue;
927 
928     if (symbolIndices.size() != cgProfile.size() * 2)
929       fatal("number of relocations doesn't match Weights");
930 
931     for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {
932       const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];
933       uint32_t fromIndex = symbolIndices[i * 2];
934       uint32_t toIndex = symbolIndices[i * 2 + 1];
935       auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
936       auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
937       if (!fromSym || !toSym)
938         continue;
939 
940       auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
941       auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
942       if (from && to)
943         config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
944     }
945   }
946 }
947 
948 static bool getCompressDebugSections(opt::InputArgList &args) {
949   StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
950   if (s == "none")
951     return false;
952   if (s != "zlib")
953     error("unknown --compress-debug-sections value: " + s);
954   if (!compression::zlib::isAvailable())
955     error("--compress-debug-sections: zlib is not available");
956   return true;
957 }
958 
959 static StringRef getAliasSpelling(opt::Arg *arg) {
960   if (const opt::Arg *alias = arg->getAlias())
961     return alias->getSpelling();
962   return arg->getSpelling();
963 }
964 
965 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
966                                                         unsigned id) {
967   auto *arg = args.getLastArg(id);
968   if (!arg)
969     return {"", ""};
970 
971   StringRef s = arg->getValue();
972   std::pair<StringRef, StringRef> ret = s.split(';');
973   if (ret.second.empty())
974     error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
975   return ret;
976 }
977 
978 // Parse the symbol ordering file and warn for any duplicate entries.
979 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
980   SetVector<StringRef> names;
981   for (StringRef s : args::getLines(mb))
982     if (!names.insert(s) && config->warnSymbolOrdering)
983       warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
984 
985   return names.takeVector();
986 }
987 
988 static bool getIsRela(opt::InputArgList &args) {
989   // If -z rel or -z rela is specified, use the last option.
990   for (auto *arg : args.filtered_reverse(OPT_z)) {
991     StringRef s(arg->getValue());
992     if (s == "rel")
993       return false;
994     if (s == "rela")
995       return true;
996   }
997 
998   // Otherwise use the psABI defined relocation entry format.
999   uint16_t m = config->emachine;
1000   return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC ||
1001          m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64;
1002 }
1003 
1004 static void parseClangOption(StringRef opt, const Twine &msg) {
1005   std::string err;
1006   raw_string_ostream os(err);
1007 
1008   const char *argv[] = {config->progName.data(), opt.data()};
1009   if (cl::ParseCommandLineOptions(2, argv, "", &os))
1010     return;
1011   os.flush();
1012   error(msg + ": " + StringRef(err).trim());
1013 }
1014 
1015 // Checks the parameter of the bti-report and cet-report options.
1016 static bool isValidReportString(StringRef arg) {
1017   return arg == "none" || arg == "warning" || arg == "error";
1018 }
1019 
1020 // Initializes Config members by the command line options.
1021 static void readConfigs(opt::InputArgList &args) {
1022   errorHandler().verbose = args.hasArg(OPT_verbose);
1023   errorHandler().vsDiagnostics =
1024       args.hasArg(OPT_visual_studio_diagnostics_format, false);
1025 
1026   config->allowMultipleDefinition =
1027       args.hasFlag(OPT_allow_multiple_definition,
1028                    OPT_no_allow_multiple_definition, false) ||
1029       hasZOption(args, "muldefs");
1030   config->androidMemtagHeap =
1031       args.hasFlag(OPT_android_memtag_heap, OPT_no_android_memtag_heap, false);
1032   config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack,
1033                                             OPT_no_android_memtag_stack, false);
1034   config->androidMemtagMode = getMemtagMode(args);
1035   config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
1036   if (opt::Arg *arg =
1037           args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,
1038                           OPT_Bsymbolic_functions, OPT_Bsymbolic)) {
1039     if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
1040       config->bsymbolic = BsymbolicKind::NonWeakFunctions;
1041     else if (arg->getOption().matches(OPT_Bsymbolic_functions))
1042       config->bsymbolic = BsymbolicKind::Functions;
1043     else if (arg->getOption().matches(OPT_Bsymbolic))
1044       config->bsymbolic = BsymbolicKind::All;
1045   }
1046   config->checkSections =
1047       args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
1048   config->chroot = args.getLastArgValue(OPT_chroot);
1049   config->compressDebugSections = getCompressDebugSections(args);
1050   config->cref = args.hasArg(OPT_cref);
1051   config->optimizeBBJumps =
1052       args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
1053   config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
1054   config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
1055   config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
1056   config->disableVerify = args.hasArg(OPT_disable_verify);
1057   config->discard = getDiscard(args);
1058   config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
1059   config->dynamicLinker = getDynamicLinker(args);
1060   config->ehFrameHdr =
1061       args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
1062   config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
1063   config->emitRelocs = args.hasArg(OPT_emit_relocs);
1064   config->callGraphProfileSort = args.hasFlag(
1065       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
1066   config->enableNewDtags =
1067       args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
1068   config->entry = args.getLastArgValue(OPT_entry);
1069 
1070   errorHandler().errorHandlingScript =
1071       args.getLastArgValue(OPT_error_handling_script);
1072 
1073   config->executeOnly =
1074       args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
1075   config->exportDynamic =
1076       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false) ||
1077       args.hasArg(OPT_shared);
1078   config->filterList = args::getStrings(args, OPT_filter);
1079   config->fini = args.getLastArgValue(OPT_fini, "_fini");
1080   config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
1081                                      !args.hasArg(OPT_relocatable);
1082   config->fixCortexA8 =
1083       args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
1084   config->fortranCommon =
1085       args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, false);
1086   config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
1087   config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
1088   config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
1089   config->icf = getICF(args);
1090   config->ignoreDataAddressEquality =
1091       args.hasArg(OPT_ignore_data_address_equality);
1092   config->ignoreFunctionAddressEquality =
1093       args.hasArg(OPT_ignore_function_address_equality);
1094   config->init = args.getLastArgValue(OPT_init, "_init");
1095   config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
1096   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1097   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1098   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1099                                             OPT_no_lto_pgo_warn_mismatch, true);
1100   config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
1101   config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
1102   config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
1103   config->ltoWholeProgramVisibility =
1104       args.hasFlag(OPT_lto_whole_program_visibility,
1105                    OPT_no_lto_whole_program_visibility, false);
1106   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
1107   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
1108   config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
1109   config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
1110   config->ltoBasicBlockSections =
1111       args.getLastArgValue(OPT_lto_basic_block_sections);
1112   config->ltoUniqueBasicBlockSectionNames =
1113       args.hasFlag(OPT_lto_unique_basic_block_section_names,
1114                    OPT_no_lto_unique_basic_block_section_names, false);
1115   config->mapFile = args.getLastArgValue(OPT_Map);
1116   config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
1117   config->mergeArmExidx =
1118       args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
1119   config->mmapOutputFile =
1120       args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
1121   config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
1122   config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
1123   config->nostdlib = args.hasArg(OPT_nostdlib);
1124   config->oFormatBinary = isOutputFormatBinary(args);
1125   config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
1126   config->opaquePointers = args.hasFlag(
1127       OPT_plugin_opt_opaque_pointers, OPT_plugin_opt_no_opaque_pointers, true);
1128   config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
1129   config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file);
1130 
1131   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1132   if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {
1133     auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());
1134     if (!resultOrErr)
1135       error(arg->getSpelling() + ": invalid argument '" + arg->getValue() +
1136             "', only integer or 'auto' is supported");
1137     else
1138       config->optRemarksHotnessThreshold = *resultOrErr;
1139   }
1140 
1141   config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
1142   config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
1143   config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
1144   config->optimize = args::getInteger(args, OPT_O, 1);
1145   config->orphanHandling = getOrphanHandling(args);
1146   config->outputFile = args.getLastArgValue(OPT_o);
1147   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
1148   config->printIcfSections =
1149       args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
1150   config->printGcSections =
1151       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
1152   config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
1153   config->printSymbolOrder =
1154       args.getLastArgValue(OPT_print_symbol_order);
1155   config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true);
1156   config->rpath = getRpath(args);
1157   config->relocatable = args.hasArg(OPT_relocatable);
1158 
1159   if (args.hasArg(OPT_save_temps)) {
1160     // --save-temps implies saving all temps.
1161     for (const char *s : saveTempsValues)
1162       config->saveTempsArgs.insert(s);
1163   } else {
1164     for (auto *arg : args.filtered(OPT_save_temps_eq)) {
1165       StringRef s = arg->getValue();
1166       if (llvm::is_contained(saveTempsValues, s))
1167         config->saveTempsArgs.insert(s);
1168       else
1169         error("unknown --save-temps value: " + s);
1170     }
1171   }
1172 
1173   config->searchPaths = args::getStrings(args, OPT_library_path);
1174   config->sectionStartMap = getSectionStartMap(args);
1175   config->shared = args.hasArg(OPT_shared);
1176   config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
1177   config->soName = args.getLastArgValue(OPT_soname);
1178   config->sortSection = getSortSection(args);
1179   config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
1180   config->strip = getStrip(args);
1181   config->sysroot = args.getLastArgValue(OPT_sysroot);
1182   config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
1183   config->target2 = getTarget2(args);
1184   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
1185   config->thinLTOCachePolicy = CHECK(
1186       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
1187       "--thinlto-cache-policy: invalid cache policy");
1188   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1189   config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||
1190                                   args.hasArg(OPT_thinlto_index_only) ||
1191                                   args.hasArg(OPT_thinlto_index_only_eq);
1192   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1193                              args.hasArg(OPT_thinlto_index_only_eq);
1194   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1195   config->thinLTOObjectSuffixReplace =
1196       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
1197   config->thinLTOPrefixReplace =
1198       getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
1199   if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {
1200     if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))
1201       error("--thinlto-object-suffix-replace is not supported with "
1202             "--thinlto-emit-index-files");
1203     else if (args.hasArg(OPT_thinlto_prefix_replace_eq))
1204       error("--thinlto-prefix-replace is not supported with "
1205             "--thinlto-emit-index-files");
1206   }
1207   config->thinLTOModulesToCompile =
1208       args::getStrings(args, OPT_thinlto_single_module_eq);
1209   config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
1210   config->timeTraceGranularity =
1211       args::getInteger(args, OPT_time_trace_granularity, 500);
1212   config->trace = args.hasArg(OPT_trace);
1213   config->undefined = args::getStrings(args, OPT_undefined);
1214   config->undefinedVersion =
1215       args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
1216   config->unique = args.hasArg(OPT_unique);
1217   config->useAndroidRelrTags = args.hasFlag(
1218       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
1219   config->warnBackrefs =
1220       args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
1221   config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
1222   config->warnSymbolOrdering =
1223       args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1224   config->whyExtract = args.getLastArgValue(OPT_why_extract);
1225   config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
1226   config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
1227   config->zForceBti = hasZOption(args, "force-bti");
1228   config->zForceIbt = hasZOption(args, "force-ibt");
1229   config->zGlobal = hasZOption(args, "global");
1230   config->zGnustack = getZGnuStack(args);
1231   config->zHazardplt = hasZOption(args, "hazardplt");
1232   config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
1233   config->zInitfirst = hasZOption(args, "initfirst");
1234   config->zInterpose = hasZOption(args, "interpose");
1235   config->zKeepTextSectionPrefix = getZFlag(
1236       args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
1237   config->zNodefaultlib = hasZOption(args, "nodefaultlib");
1238   config->zNodelete = hasZOption(args, "nodelete");
1239   config->zNodlopen = hasZOption(args, "nodlopen");
1240   config->zNow = getZFlag(args, "now", "lazy", false);
1241   config->zOrigin = hasZOption(args, "origin");
1242   config->zPacPlt = hasZOption(args, "pac-plt");
1243   config->zRelro = getZFlag(args, "relro", "norelro", true);
1244   config->zRetpolineplt = hasZOption(args, "retpolineplt");
1245   config->zRodynamic = hasZOption(args, "rodynamic");
1246   config->zSeparate = getZSeparate(args);
1247   config->zShstk = hasZOption(args, "shstk");
1248   config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1249   config->zStartStopGC =
1250       getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);
1251   config->zStartStopVisibility = getZStartStopVisibility(args);
1252   config->zText = getZFlag(args, "text", "notext", true);
1253   config->zWxneeded = hasZOption(args, "wxneeded");
1254   setUnresolvedSymbolPolicy(args);
1255   config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";
1256 
1257   if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {
1258     if (arg->getOption().matches(OPT_eb))
1259       config->optEB = true;
1260     else
1261       config->optEL = true;
1262   }
1263 
1264   for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {
1265     constexpr StringRef errPrefix = "--shuffle-sections=: ";
1266     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
1267     if (kv.first.empty() || kv.second.empty()) {
1268       error(errPrefix + "expected <section_glob>=<seed>, but got '" +
1269             arg->getValue() + "'");
1270       continue;
1271     }
1272     // Signed so that <section_glob>=-1 is allowed.
1273     int64_t v;
1274     if (!to_integer(kv.second, v))
1275       error(errPrefix + "expected an integer, but got '" + kv.second + "'");
1276     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1277       config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v));
1278     else
1279       error(errPrefix + toString(pat.takeError()));
1280   }
1281 
1282   auto reports = {std::make_pair("bti-report", &config->zBtiReport),
1283                   std::make_pair("cet-report", &config->zCetReport)};
1284   for (opt::Arg *arg : args.filtered(OPT_z)) {
1285     std::pair<StringRef, StringRef> option =
1286         StringRef(arg->getValue()).split('=');
1287     for (auto reportArg : reports) {
1288       if (option.first != reportArg.first)
1289         continue;
1290       if (!isValidReportString(option.second)) {
1291         error(Twine("-z ") + reportArg.first + "= parameter " + option.second +
1292               " is not recognized");
1293         continue;
1294       }
1295       *reportArg.second = option.second;
1296     }
1297   }
1298 
1299   for (opt::Arg *arg : args.filtered(OPT_z)) {
1300     std::pair<StringRef, StringRef> option =
1301         StringRef(arg->getValue()).split('=');
1302     if (option.first != "dead-reloc-in-nonalloc")
1303       continue;
1304     constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
1305     std::pair<StringRef, StringRef> kv = option.second.split('=');
1306     if (kv.first.empty() || kv.second.empty()) {
1307       error(errPrefix + "expected <section_glob>=<value>");
1308       continue;
1309     }
1310     uint64_t v;
1311     if (!to_integer(kv.second, v))
1312       error(errPrefix + "expected a non-negative integer, but got '" +
1313             kv.second + "'");
1314     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1315       config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
1316     else
1317       error(errPrefix + toString(pat.takeError()));
1318   }
1319 
1320   cl::ResetAllOptionOccurrences();
1321 
1322   // Parse LTO options.
1323   if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
1324     parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
1325                      arg->getSpelling());
1326 
1327   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
1328     parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
1329 
1330   // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1331   // relative path. Just ignore. If not ended with "lto-wrapper", consider it an
1332   // unsupported LLVMgold.so option and error.
1333   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq))
1334     if (!StringRef(arg->getValue()).endswith("lto-wrapper"))
1335       error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
1336             "'");
1337 
1338   config->passPlugins = args::getStrings(args, OPT_load_pass_plugins);
1339 
1340   // Parse -mllvm options.
1341   for (auto *arg : args.filtered(OPT_mllvm))
1342     parseClangOption(arg->getValue(), arg->getSpelling());
1343 
1344   // --threads= takes a positive integer and provides the default value for
1345   // --thinlto-jobs=.
1346   if (auto *arg = args.getLastArg(OPT_threads)) {
1347     StringRef v(arg->getValue());
1348     unsigned threads = 0;
1349     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1350       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1351             arg->getValue() + "'");
1352     parallel::strategy = hardware_concurrency(threads);
1353     config->thinLTOJobs = v;
1354   }
1355   if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
1356     config->thinLTOJobs = arg->getValue();
1357 
1358   if (config->ltoo > 3)
1359     error("invalid optimization level for LTO: " + Twine(config->ltoo));
1360   if (config->ltoPartitions == 0)
1361     error("--lto-partitions: number of threads must be > 0");
1362   if (!get_threadpool_strategy(config->thinLTOJobs))
1363     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1364 
1365   if (config->splitStackAdjustSize < 0)
1366     error("--split-stack-adjust-size: size must be >= 0");
1367 
1368   // The text segment is traditionally the first segment, whose address equals
1369   // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1370   // is an old-fashioned option that does not play well with lld's layout.
1371   // Suggest --image-base as a likely alternative.
1372   if (args.hasArg(OPT_Ttext_segment))
1373     error("-Ttext-segment is not supported. Use --image-base if you "
1374           "intend to set the base address");
1375 
1376   // Parse ELF{32,64}{LE,BE} and CPU type.
1377   if (auto *arg = args.getLastArg(OPT_m)) {
1378     StringRef s = arg->getValue();
1379     std::tie(config->ekind, config->emachine, config->osabi) =
1380         parseEmulation(s);
1381     config->mipsN32Abi =
1382         (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
1383     config->emulation = s;
1384   }
1385 
1386   // Parse --hash-style={sysv,gnu,both}.
1387   if (auto *arg = args.getLastArg(OPT_hash_style)) {
1388     StringRef s = arg->getValue();
1389     if (s == "sysv")
1390       config->sysvHash = true;
1391     else if (s == "gnu")
1392       config->gnuHash = true;
1393     else if (s == "both")
1394       config->sysvHash = config->gnuHash = true;
1395     else
1396       error("unknown --hash-style: " + s);
1397   }
1398 
1399   if (args.hasArg(OPT_print_map))
1400     config->mapFile = "-";
1401 
1402   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1403   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1404   // it.
1405   if (config->nmagic || config->omagic)
1406     config->zRelro = false;
1407 
1408   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1409 
1410   if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) {
1411     config->relrGlibc = true;
1412     config->relrPackDynRelocs = true;
1413   } else {
1414     std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1415         getPackDynRelocs(args);
1416   }
1417 
1418   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1419     if (args.hasArg(OPT_call_graph_ordering_file))
1420       error("--symbol-ordering-file and --call-graph-order-file "
1421             "may not be used together");
1422     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1423       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1424       // Also need to disable CallGraphProfileSort to prevent
1425       // LLD order symbols with CGProfile
1426       config->callGraphProfileSort = false;
1427     }
1428   }
1429 
1430   assert(config->versionDefinitions.empty());
1431   config->versionDefinitions.push_back(
1432       {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});
1433   config->versionDefinitions.push_back(
1434       {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});
1435 
1436   // If --retain-symbol-file is used, we'll keep only the symbols listed in
1437   // the file and discard all others.
1438   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1439     config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
1440         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1441     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1442       for (StringRef s : args::getLines(*buffer))
1443         config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
1444             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1445   }
1446 
1447   for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
1448     StringRef pattern(arg->getValue());
1449     if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
1450       config->warnBackrefsExclude.push_back(std::move(*pat));
1451     else
1452       error(arg->getSpelling() + ": " + toString(pat.takeError()));
1453   }
1454 
1455   // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1456   // which should be exported. For -shared, references to matched non-local
1457   // STV_DEFAULT symbols are not bound to definitions within the shared object,
1458   // even if other options express a symbolic intention: -Bsymbolic,
1459   // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1460   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1461     config->dynamicList.push_back(
1462         {arg->getValue(), /*isExternCpp=*/false,
1463          /*hasWildcard=*/hasWildcard(arg->getValue())});
1464 
1465   // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1466   // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1467   // like semantics.
1468   config->symbolic =
1469       config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1470   for (auto *arg :
1471        args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))
1472     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1473       readDynamicList(*buffer);
1474 
1475   for (auto *arg : args.filtered(OPT_version_script))
1476     if (Optional<std::string> path = searchScript(arg->getValue())) {
1477       if (Optional<MemoryBufferRef> buffer = readFile(*path))
1478         readVersionScript(*buffer);
1479     } else {
1480       error(Twine("cannot find version script ") + arg->getValue());
1481     }
1482 }
1483 
1484 // Some Config members do not directly correspond to any particular
1485 // command line options, but computed based on other Config values.
1486 // This function initialize such members. See Config.h for the details
1487 // of these values.
1488 static void setConfigs(opt::InputArgList &args) {
1489   ELFKind k = config->ekind;
1490   uint16_t m = config->emachine;
1491 
1492   config->copyRelocs = (config->relocatable || config->emitRelocs);
1493   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1494   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1495   config->endianness = config->isLE ? endianness::little : endianness::big;
1496   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1497   config->isPic = config->pie || config->shared;
1498   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1499   config->wordsize = config->is64 ? 8 : 4;
1500 
1501   // ELF defines two different ways to store relocation addends as shown below:
1502   //
1503   //  Rel: Addends are stored to the location where relocations are applied. It
1504   //  cannot pack the full range of addend values for all relocation types, but
1505   //  this only affects relocation types that we don't support emitting as
1506   //  dynamic relocations (see getDynRel).
1507   //  Rela: Addends are stored as part of relocation entry.
1508   //
1509   // In other words, Rela makes it easy to read addends at the price of extra
1510   // 4 or 8 byte for each relocation entry.
1511   //
1512   // We pick the format for dynamic relocations according to the psABI for each
1513   // processor, but a contrary choice can be made if the dynamic loader
1514   // supports.
1515   config->isRela = getIsRela(args);
1516 
1517   // If the output uses REL relocations we must store the dynamic relocation
1518   // addends to the output sections. We also store addends for RELA relocations
1519   // if --apply-dynamic-relocs is used.
1520   // We default to not writing the addends when using RELA relocations since
1521   // any standard conforming tool can find it in r_addend.
1522   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1523                                       OPT_no_apply_dynamic_relocs, false) ||
1524                          !config->isRela;
1525   // Validation of dynamic relocation addends is on by default for assertions
1526   // builds (for supported targets) and disabled otherwise. Ideally we would
1527   // enable the debug checks for all targets, but currently not all targets
1528   // have support for reading Elf_Rel addends, so we only enable for a subset.
1529 #ifndef NDEBUG
1530   bool checkDynamicRelocsDefault = m == EM_ARM || m == EM_386 || m == EM_MIPS ||
1531                                    m == EM_X86_64 || m == EM_RISCV;
1532 #else
1533   bool checkDynamicRelocsDefault = false;
1534 #endif
1535   config->checkDynamicRelocs =
1536       args.hasFlag(OPT_check_dynamic_relocations,
1537                    OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);
1538   config->tocOptimize =
1539       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1540   config->pcRelOptimize =
1541       args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
1542 }
1543 
1544 static bool isFormatBinary(StringRef s) {
1545   if (s == "binary")
1546     return true;
1547   if (s == "elf" || s == "default")
1548     return false;
1549   error("unknown --format value: " + s +
1550         " (supported formats: elf, default, binary)");
1551   return false;
1552 }
1553 
1554 void LinkerDriver::createFiles(opt::InputArgList &args) {
1555   llvm::TimeTraceScope timeScope("Load input files");
1556   // For --{push,pop}-state.
1557   std::vector<std::tuple<bool, bool, bool>> stack;
1558 
1559   // Iterate over argv to process input files and positional arguments.
1560   InputFile::isInGroup = false;
1561   bool hasInput = false;
1562   for (auto *arg : args) {
1563     switch (arg->getOption().getID()) {
1564     case OPT_library:
1565       addLibrary(arg->getValue());
1566       hasInput = true;
1567       break;
1568     case OPT_INPUT:
1569       addFile(arg->getValue(), /*withLOption=*/false);
1570       hasInput = true;
1571       break;
1572     case OPT_defsym: {
1573       StringRef from;
1574       StringRef to;
1575       std::tie(from, to) = StringRef(arg->getValue()).split('=');
1576       if (from.empty() || to.empty())
1577         error("--defsym: syntax error: " + StringRef(arg->getValue()));
1578       else
1579         readDefsym(from, MemoryBufferRef(to, "--defsym"));
1580       break;
1581     }
1582     case OPT_script:
1583       if (Optional<std::string> path = searchScript(arg->getValue())) {
1584         if (Optional<MemoryBufferRef> mb = readFile(*path))
1585           readLinkerScript(*mb);
1586         break;
1587       }
1588       error(Twine("cannot find linker script ") + arg->getValue());
1589       break;
1590     case OPT_as_needed:
1591       config->asNeeded = true;
1592       break;
1593     case OPT_format:
1594       config->formatBinary = isFormatBinary(arg->getValue());
1595       break;
1596     case OPT_no_as_needed:
1597       config->asNeeded = false;
1598       break;
1599     case OPT_Bstatic:
1600     case OPT_omagic:
1601     case OPT_nmagic:
1602       config->isStatic = true;
1603       break;
1604     case OPT_Bdynamic:
1605       config->isStatic = false;
1606       break;
1607     case OPT_whole_archive:
1608       inWholeArchive = true;
1609       break;
1610     case OPT_no_whole_archive:
1611       inWholeArchive = false;
1612       break;
1613     case OPT_just_symbols:
1614       if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1615         files.push_back(createObjectFile(*mb));
1616         files.back()->justSymbols = true;
1617       }
1618       break;
1619     case OPT_start_group:
1620       if (InputFile::isInGroup)
1621         error("nested --start-group");
1622       InputFile::isInGroup = true;
1623       break;
1624     case OPT_end_group:
1625       if (!InputFile::isInGroup)
1626         error("stray --end-group");
1627       InputFile::isInGroup = false;
1628       ++InputFile::nextGroupId;
1629       break;
1630     case OPT_start_lib:
1631       if (inLib)
1632         error("nested --start-lib");
1633       if (InputFile::isInGroup)
1634         error("may not nest --start-lib in --start-group");
1635       inLib = true;
1636       InputFile::isInGroup = true;
1637       break;
1638     case OPT_end_lib:
1639       if (!inLib)
1640         error("stray --end-lib");
1641       inLib = false;
1642       InputFile::isInGroup = false;
1643       ++InputFile::nextGroupId;
1644       break;
1645     case OPT_push_state:
1646       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1647       break;
1648     case OPT_pop_state:
1649       if (stack.empty()) {
1650         error("unbalanced --push-state/--pop-state");
1651         break;
1652       }
1653       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1654       stack.pop_back();
1655       break;
1656     }
1657   }
1658 
1659   if (files.empty() && !hasInput && errorCount() == 0)
1660     error("no input files");
1661 }
1662 
1663 // If -m <machine_type> was not given, infer it from object files.
1664 void LinkerDriver::inferMachineType() {
1665   if (config->ekind != ELFNoneKind)
1666     return;
1667 
1668   for (InputFile *f : files) {
1669     if (f->ekind == ELFNoneKind)
1670       continue;
1671     config->ekind = f->ekind;
1672     config->emachine = f->emachine;
1673     config->osabi = f->osabi;
1674     config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1675     return;
1676   }
1677   error("target emulation unknown: -m or at least one .o file required");
1678 }
1679 
1680 // Parse -z max-page-size=<value>. The default value is defined by
1681 // each target.
1682 static uint64_t getMaxPageSize(opt::InputArgList &args) {
1683   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1684                                        target->defaultMaxPageSize);
1685   if (!isPowerOf2_64(val))
1686     error("max-page-size: value isn't a power of 2");
1687   if (config->nmagic || config->omagic) {
1688     if (val != target->defaultMaxPageSize)
1689       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1690     return 1;
1691   }
1692   return val;
1693 }
1694 
1695 // Parse -z common-page-size=<value>. The default value is defined by
1696 // each target.
1697 static uint64_t getCommonPageSize(opt::InputArgList &args) {
1698   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1699                                        target->defaultCommonPageSize);
1700   if (!isPowerOf2_64(val))
1701     error("common-page-size: value isn't a power of 2");
1702   if (config->nmagic || config->omagic) {
1703     if (val != target->defaultCommonPageSize)
1704       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1705     return 1;
1706   }
1707   // commonPageSize can't be larger than maxPageSize.
1708   if (val > config->maxPageSize)
1709     val = config->maxPageSize;
1710   return val;
1711 }
1712 
1713 // Parses --image-base option.
1714 static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1715   // Because we are using "Config->maxPageSize" here, this function has to be
1716   // called after the variable is initialized.
1717   auto *arg = args.getLastArg(OPT_image_base);
1718   if (!arg)
1719     return None;
1720 
1721   StringRef s = arg->getValue();
1722   uint64_t v;
1723   if (!to_integer(s, v)) {
1724     error("--image-base: number expected, but got " + s);
1725     return 0;
1726   }
1727   if ((v % config->maxPageSize) != 0)
1728     warn("--image-base: address isn't multiple of page size: " + s);
1729   return v;
1730 }
1731 
1732 // Parses `--exclude-libs=lib,lib,...`.
1733 // The library names may be delimited by commas or colons.
1734 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1735   DenseSet<StringRef> ret;
1736   for (auto *arg : args.filtered(OPT_exclude_libs)) {
1737     StringRef s = arg->getValue();
1738     for (;;) {
1739       size_t pos = s.find_first_of(",:");
1740       if (pos == StringRef::npos)
1741         break;
1742       ret.insert(s.substr(0, pos));
1743       s = s.substr(pos + 1);
1744     }
1745     ret.insert(s);
1746   }
1747   return ret;
1748 }
1749 
1750 // Handles the --exclude-libs option. If a static library file is specified
1751 // by the --exclude-libs option, all public symbols from the archive become
1752 // private unless otherwise specified by version scripts or something.
1753 // A special library name "ALL" means all archive files.
1754 //
1755 // This is not a popular option, but some programs such as bionic libc use it.
1756 static void excludeLibs(opt::InputArgList &args) {
1757   DenseSet<StringRef> libs = getExcludeLibs(args);
1758   bool all = libs.count("ALL");
1759 
1760   auto visit = [&](InputFile *file) {
1761     if (file->archiveName.empty() ||
1762         !(all || libs.count(path::filename(file->archiveName))))
1763       return;
1764     ArrayRef<Symbol *> symbols = file->getSymbols();
1765     if (isa<ELFFileBase>(file))
1766       symbols = cast<ELFFileBase>(file)->getGlobalSymbols();
1767     for (Symbol *sym : symbols)
1768       if (!sym->isUndefined() && sym->file == file)
1769         sym->versionId = VER_NDX_LOCAL;
1770   };
1771 
1772   for (ELFFileBase *file : ctx->objectFiles)
1773     visit(file);
1774 
1775   for (BitcodeFile *file : ctx->bitcodeFiles)
1776     visit(file);
1777 }
1778 
1779 // Force Sym to be entered in the output.
1780 static void handleUndefined(Symbol *sym, const char *option) {
1781   // Since a symbol may not be used inside the program, LTO may
1782   // eliminate it. Mark the symbol as "used" to prevent it.
1783   sym->isUsedInRegularObj = true;
1784 
1785   if (!sym->isLazy())
1786     return;
1787   sym->extract();
1788   if (!config->whyExtract.empty())
1789     ctx->whyExtractRecords.emplace_back(option, sym->file, *sym);
1790 }
1791 
1792 // As an extension to GNU linkers, lld supports a variant of `-u`
1793 // which accepts wildcard patterns. All symbols that match a given
1794 // pattern are handled as if they were given by `-u`.
1795 static void handleUndefinedGlob(StringRef arg) {
1796   Expected<GlobPattern> pat = GlobPattern::create(arg);
1797   if (!pat) {
1798     error("--undefined-glob: " + toString(pat.takeError()));
1799     return;
1800   }
1801 
1802   // Calling sym->extract() in the loop is not safe because it may add new
1803   // symbols to the symbol table, invalidating the current iterator.
1804   SmallVector<Symbol *, 0> syms;
1805   for (Symbol *sym : symtab->symbols())
1806     if (!sym->isPlaceholder() && pat->match(sym->getName()))
1807       syms.push_back(sym);
1808 
1809   for (Symbol *sym : syms)
1810     handleUndefined(sym, "--undefined-glob");
1811 }
1812 
1813 static void handleLibcall(StringRef name) {
1814   Symbol *sym = symtab->find(name);
1815   if (!sym || !sym->isLazy())
1816     return;
1817 
1818   MemoryBufferRef mb;
1819   mb = cast<LazyObject>(sym)->file->mb;
1820 
1821   if (isBitcode(mb))
1822     sym->extract();
1823 }
1824 
1825 static void writeArchiveStats() {
1826   if (config->printArchiveStats.empty())
1827     return;
1828 
1829   std::error_code ec;
1830   raw_fd_ostream os(config->printArchiveStats, ec, sys::fs::OF_None);
1831   if (ec) {
1832     error("--print-archive-stats=: cannot open " + config->printArchiveStats +
1833           ": " + ec.message());
1834     return;
1835   }
1836 
1837   os << "members\textracted\tarchive\n";
1838 
1839   SmallVector<StringRef, 0> archives;
1840   DenseMap<CachedHashStringRef, unsigned> all, extracted;
1841   for (ELFFileBase *file : ctx->objectFiles)
1842     if (file->archiveName.size())
1843       ++extracted[CachedHashStringRef(file->archiveName)];
1844   for (BitcodeFile *file : ctx->bitcodeFiles)
1845     if (file->archiveName.size())
1846       ++extracted[CachedHashStringRef(file->archiveName)];
1847   for (std::pair<StringRef, unsigned> f : driver->archiveFiles) {
1848     unsigned &v = extracted[CachedHashString(f.first)];
1849     os << f.second << '\t' << v << '\t' << f.first << '\n';
1850     // If the archive occurs multiple times, other instances have a count of 0.
1851     v = 0;
1852   }
1853 }
1854 
1855 static void writeWhyExtract() {
1856   if (config->whyExtract.empty())
1857     return;
1858 
1859   std::error_code ec;
1860   raw_fd_ostream os(config->whyExtract, ec, sys::fs::OF_None);
1861   if (ec) {
1862     error("cannot open --why-extract= file " + config->whyExtract + ": " +
1863           ec.message());
1864     return;
1865   }
1866 
1867   os << "reference\textracted\tsymbol\n";
1868   for (auto &entry : ctx->whyExtractRecords) {
1869     os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t'
1870        << toString(std::get<2>(entry)) << '\n';
1871   }
1872 }
1873 
1874 static void reportBackrefs() {
1875   for (auto &ref : ctx->backwardReferences) {
1876     const Symbol &sym = *ref.first;
1877     std::string to = toString(ref.second.second);
1878     // Some libraries have known problems and can cause noise. Filter them out
1879     // with --warn-backrefs-exclude=. The value may look like (for --start-lib)
1880     // *.o or (archive member) *.a(*.o).
1881     bool exclude = false;
1882     for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
1883       if (pat.match(to)) {
1884         exclude = true;
1885         break;
1886       }
1887     if (!exclude)
1888       warn("backward reference detected: " + sym.getName() + " in " +
1889            toString(ref.second.first) + " refers to " + to);
1890   }
1891 }
1892 
1893 // Handle --dependency-file=<path>. If that option is given, lld creates a
1894 // file at a given path with the following contents:
1895 //
1896 //   <output-file>: <input-file> ...
1897 //
1898 //   <input-file>:
1899 //
1900 // where <output-file> is a pathname of an output file and <input-file>
1901 // ... is a list of pathnames of all input files. `make` command can read a
1902 // file in the above format and interpret it as a dependency info. We write
1903 // phony targets for every <input-file> to avoid an error when that file is
1904 // removed.
1905 //
1906 // This option is useful if you want to make your final executable to depend
1907 // on all input files including system libraries. Here is why.
1908 //
1909 // When you write a Makefile, you usually write it so that the final
1910 // executable depends on all user-generated object files. Normally, you
1911 // don't make your executable to depend on system libraries (such as libc)
1912 // because you don't know the exact paths of libraries, even though system
1913 // libraries that are linked to your executable statically are technically a
1914 // part of your program. By using --dependency-file option, you can make
1915 // lld to dump dependency info so that you can maintain exact dependencies
1916 // easily.
1917 static void writeDependencyFile() {
1918   std::error_code ec;
1919   raw_fd_ostream os(config->dependencyFile, ec, sys::fs::OF_None);
1920   if (ec) {
1921     error("cannot open " + config->dependencyFile + ": " + ec.message());
1922     return;
1923   }
1924 
1925   // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
1926   // * A space is escaped by a backslash which itself must be escaped.
1927   // * A hash sign is escaped by a single backslash.
1928   // * $ is escapes as $$.
1929   auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
1930     llvm::SmallString<256> nativePath;
1931     llvm::sys::path::native(filename.str(), nativePath);
1932     llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
1933     for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
1934       if (nativePath[i] == '#') {
1935         os << '\\';
1936       } else if (nativePath[i] == ' ') {
1937         os << '\\';
1938         unsigned j = i;
1939         while (j > 0 && nativePath[--j] == '\\')
1940           os << '\\';
1941       } else if (nativePath[i] == '$') {
1942         os << '$';
1943       }
1944       os << nativePath[i];
1945     }
1946   };
1947 
1948   os << config->outputFile << ":";
1949   for (StringRef path : config->dependencyFiles) {
1950     os << " \\\n ";
1951     printFilename(os, path);
1952   }
1953   os << "\n";
1954 
1955   for (StringRef path : config->dependencyFiles) {
1956     os << "\n";
1957     printFilename(os, path);
1958     os << ":\n";
1959   }
1960 }
1961 
1962 // Replaces common symbols with defined symbols reside in .bss sections.
1963 // This function is called after all symbol names are resolved. As a
1964 // result, the passes after the symbol resolution won't see any
1965 // symbols of type CommonSymbol.
1966 static void replaceCommonSymbols() {
1967   llvm::TimeTraceScope timeScope("Replace common symbols");
1968   for (ELFFileBase *file : ctx->objectFiles) {
1969     if (!file->hasCommonSyms)
1970       continue;
1971     for (Symbol *sym : file->getGlobalSymbols()) {
1972       auto *s = dyn_cast<CommonSymbol>(sym);
1973       if (!s)
1974         continue;
1975 
1976       auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1977       bss->file = s->file;
1978       inputSections.push_back(bss);
1979       s->replace(Defined{s->file, StringRef(), s->binding, s->stOther, s->type,
1980                          /*value=*/0, s->size, bss});
1981     }
1982   }
1983 }
1984 
1985 // If all references to a DSO happen to be weak, the DSO is not added to
1986 // DT_NEEDED. If that happens, replace ShardSymbol with Undefined to avoid
1987 // dangling references to an unneeded DSO. Use a weak binding to avoid
1988 // --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols.
1989 static void demoteSharedAndLazySymbols() {
1990   llvm::TimeTraceScope timeScope("Demote shared and lazy symbols");
1991   for (Symbol *sym : symtab->symbols()) {
1992     auto *s = dyn_cast<SharedSymbol>(sym);
1993     if (!(s && !cast<SharedFile>(s->file)->isNeeded) && !sym->isLazy())
1994       continue;
1995 
1996     bool used = sym->used;
1997     uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK);
1998     sym->replace(
1999         Undefined{nullptr, sym->getName(), binding, sym->stOther, sym->type});
2000     sym->used = used;
2001     sym->versionId = VER_NDX_GLOBAL;
2002   }
2003 }
2004 
2005 // The section referred to by `s` is considered address-significant. Set the
2006 // keepUnique flag on the section if appropriate.
2007 static void markAddrsig(Symbol *s) {
2008   if (auto *d = dyn_cast_or_null<Defined>(s))
2009     if (d->section)
2010       // We don't need to keep text sections unique under --icf=all even if they
2011       // are address-significant.
2012       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
2013         d->section->keepUnique = true;
2014 }
2015 
2016 // Record sections that define symbols mentioned in --keep-unique <symbol>
2017 // and symbols referred to by address-significance tables. These sections are
2018 // ineligible for ICF.
2019 template <class ELFT>
2020 static void findKeepUniqueSections(opt::InputArgList &args) {
2021   for (auto *arg : args.filtered(OPT_keep_unique)) {
2022     StringRef name = arg->getValue();
2023     auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
2024     if (!d || !d->section) {
2025       warn("could not find symbol " + name + " to keep unique");
2026       continue;
2027     }
2028     d->section->keepUnique = true;
2029   }
2030 
2031   // --icf=all --ignore-data-address-equality means that we can ignore
2032   // the dynsym and address-significance tables entirely.
2033   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
2034     return;
2035 
2036   // Symbols in the dynsym could be address-significant in other executables
2037   // or DSOs, so we conservatively mark them as address-significant.
2038   for (Symbol *sym : symtab->symbols())
2039     if (sym->includeInDynsym())
2040       markAddrsig(sym);
2041 
2042   // Visit the address-significance table in each object file and mark each
2043   // referenced symbol as address-significant.
2044   for (InputFile *f : ctx->objectFiles) {
2045     auto *obj = cast<ObjFile<ELFT>>(f);
2046     ArrayRef<Symbol *> syms = obj->getSymbols();
2047     if (obj->addrsigSec) {
2048       ArrayRef<uint8_t> contents =
2049           check(obj->getObj().getSectionContents(*obj->addrsigSec));
2050       const uint8_t *cur = contents.begin();
2051       while (cur != contents.end()) {
2052         unsigned size;
2053         const char *err;
2054         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
2055         if (err)
2056           fatal(toString(f) + ": could not decode addrsig section: " + err);
2057         markAddrsig(syms[symIndex]);
2058         cur += size;
2059       }
2060     } else {
2061       // If an object file does not have an address-significance table,
2062       // conservatively mark all of its symbols as address-significant.
2063       for (Symbol *s : syms)
2064         markAddrsig(s);
2065     }
2066   }
2067 }
2068 
2069 // This function reads a symbol partition specification section. These sections
2070 // are used to control which partition a symbol is allocated to. See
2071 // https://lld.llvm.org/Partitions.html for more details on partitions.
2072 template <typename ELFT>
2073 static void readSymbolPartitionSection(InputSectionBase *s) {
2074   // Read the relocation that refers to the partition's entry point symbol.
2075   Symbol *sym;
2076   const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
2077   if (rels.areRelocsRel())
2078     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]);
2079   else
2080     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]);
2081   if (!isa<Defined>(sym) || !sym->includeInDynsym())
2082     return;
2083 
2084   StringRef partName = reinterpret_cast<const char *>(s->rawData.data());
2085   for (Partition &part : partitions) {
2086     if (part.name == partName) {
2087       sym->partition = part.getNumber();
2088       return;
2089     }
2090   }
2091 
2092   // Forbid partitions from being used on incompatible targets, and forbid them
2093   // from being used together with various linker features that assume a single
2094   // set of output sections.
2095   if (script->hasSectionsCommand)
2096     error(toString(s->file) +
2097           ": partitions cannot be used with the SECTIONS command");
2098   if (script->hasPhdrsCommands())
2099     error(toString(s->file) +
2100           ": partitions cannot be used with the PHDRS command");
2101   if (!config->sectionStartMap.empty())
2102     error(toString(s->file) + ": partitions cannot be used with "
2103                               "--section-start, -Ttext, -Tdata or -Tbss");
2104   if (config->emachine == EM_MIPS)
2105     error(toString(s->file) + ": partitions cannot be used on this target");
2106 
2107   // Impose a limit of no more than 254 partitions. This limit comes from the
2108   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
2109   // the amount of space devoted to the partition number in RankFlags.
2110   if (partitions.size() == 254)
2111     fatal("may not have more than 254 partitions");
2112 
2113   partitions.emplace_back();
2114   Partition &newPart = partitions.back();
2115   newPart.name = partName;
2116   sym->partition = newPart.getNumber();
2117 }
2118 
2119 static Symbol *addUnusedUndefined(StringRef name,
2120                                   uint8_t binding = STB_GLOBAL) {
2121   return symtab->addSymbol(Undefined{nullptr, name, binding, STV_DEFAULT, 0});
2122 }
2123 
2124 static void markBuffersAsDontNeed(bool skipLinkedOutput) {
2125   // With --thinlto-index-only, all buffers are nearly unused from now on
2126   // (except symbol/section names used by infrequent passes). Mark input file
2127   // buffers as MADV_DONTNEED so that these pages can be reused by the expensive
2128   // thin link, saving memory.
2129   if (skipLinkedOutput) {
2130     for (MemoryBuffer &mb : llvm::make_pointee_range(ctx->memoryBuffers))
2131       mb.dontNeedIfMmap();
2132     return;
2133   }
2134 
2135   // Otherwise, just mark MemoryBuffers backing BitcodeFiles.
2136   DenseSet<const char *> bufs;
2137   for (BitcodeFile *file : ctx->bitcodeFiles)
2138     bufs.insert(file->mb.getBufferStart());
2139   for (BitcodeFile *file : ctx->lazyBitcodeFiles)
2140     bufs.insert(file->mb.getBufferStart());
2141   for (MemoryBuffer &mb : llvm::make_pointee_range(ctx->memoryBuffers))
2142     if (bufs.count(mb.getBufferStart()))
2143       mb.dontNeedIfMmap();
2144 }
2145 
2146 // This function is where all the optimizations of link-time
2147 // optimization takes place. When LTO is in use, some input files are
2148 // not in native object file format but in the LLVM bitcode format.
2149 // This function compiles bitcode files into a few big native files
2150 // using LLVM functions and replaces bitcode symbols with the results.
2151 // Because all bitcode files that the program consists of are passed to
2152 // the compiler at once, it can do a whole-program optimization.
2153 template <class ELFT>
2154 void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) {
2155   llvm::TimeTraceScope timeScope("LTO");
2156   // Compile bitcode files and replace bitcode symbols.
2157   lto.reset(new BitcodeCompiler);
2158   for (BitcodeFile *file : ctx->bitcodeFiles)
2159     lto->add(*file);
2160 
2161   if (!ctx->bitcodeFiles.empty())
2162     markBuffersAsDontNeed(skipLinkedOutput);
2163 
2164   for (InputFile *file : lto->compile()) {
2165     auto *obj = cast<ObjFile<ELFT>>(file);
2166     obj->parse(/*ignoreComdats=*/true);
2167 
2168     // Parse '@' in symbol names for non-relocatable output.
2169     if (!config->relocatable)
2170       for (Symbol *sym : obj->getGlobalSymbols())
2171         if (sym->hasVersionSuffix)
2172           sym->parseSymbolVersion();
2173     ctx->objectFiles.push_back(obj);
2174   }
2175 }
2176 
2177 // The --wrap option is a feature to rename symbols so that you can write
2178 // wrappers for existing functions. If you pass `--wrap=foo`, all
2179 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
2180 // expected to write `__wrap_foo` function as a wrapper). The original
2181 // symbol becomes accessible as `__real_foo`, so you can call that from your
2182 // wrapper.
2183 //
2184 // This data structure is instantiated for each --wrap option.
2185 struct WrappedSymbol {
2186   Symbol *sym;
2187   Symbol *real;
2188   Symbol *wrap;
2189 };
2190 
2191 // Handles --wrap option.
2192 //
2193 // This function instantiates wrapper symbols. At this point, they seem
2194 // like they are not being used at all, so we explicitly set some flags so
2195 // that LTO won't eliminate them.
2196 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
2197   std::vector<WrappedSymbol> v;
2198   DenseSet<StringRef> seen;
2199 
2200   for (auto *arg : args.filtered(OPT_wrap)) {
2201     StringRef name = arg->getValue();
2202     if (!seen.insert(name).second)
2203       continue;
2204 
2205     Symbol *sym = symtab->find(name);
2206     if (!sym)
2207       continue;
2208 
2209     Symbol *real = addUnusedUndefined(saver().save("__real_" + name));
2210     Symbol *wrap =
2211         addUnusedUndefined(saver().save("__wrap_" + name), sym->binding);
2212     v.push_back({sym, real, wrap});
2213 
2214     // We want to tell LTO not to inline symbols to be overwritten
2215     // because LTO doesn't know the final symbol contents after renaming.
2216     real->scriptDefined = true;
2217     sym->scriptDefined = true;
2218 
2219     // If a symbol is referenced in any object file, bitcode file or shared
2220     // object, mark its redirection target (foo for __real_foo and __wrap_foo
2221     // for foo) as referenced after redirection, which will be used to tell LTO
2222     // to not eliminate the redirection target. If the object file defining the
2223     // symbol also references it, we cannot easily distinguish the case from
2224     // cases where the symbol is not referenced. Retain the redirection target
2225     // in this case because we choose to wrap symbol references regardless of
2226     // whether the symbol is defined
2227     // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
2228     if (real->referenced || real->isDefined())
2229       sym->referencedAfterWrap = true;
2230     if (sym->referenced || sym->isDefined())
2231       wrap->referencedAfterWrap = true;
2232   }
2233   return v;
2234 }
2235 
2236 // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
2237 //
2238 // When this function is executed, only InputFiles and symbol table
2239 // contain pointers to symbol objects. We visit them to replace pointers,
2240 // so that wrapped symbols are swapped as instructed by the command line.
2241 static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) {
2242   llvm::TimeTraceScope timeScope("Redirect symbols");
2243   DenseMap<Symbol *, Symbol *> map;
2244   for (const WrappedSymbol &w : wrapped) {
2245     map[w.sym] = w.wrap;
2246     map[w.real] = w.sym;
2247   }
2248   for (Symbol *sym : symtab->symbols()) {
2249     // Enumerate symbols with a non-default version (foo@v1). hasVersionSuffix
2250     // filters out most symbols but is not sufficient.
2251     if (!sym->hasVersionSuffix)
2252       continue;
2253     const char *suffix1 = sym->getVersionSuffix();
2254     if (suffix1[0] != '@' || suffix1[1] == '@')
2255       continue;
2256 
2257     // Check the existing symbol foo. We have two special cases to handle:
2258     //
2259     // * There is a definition of foo@v1 and foo@@v1.
2260     // * There is a definition of foo@v1 and foo.
2261     Defined *sym2 = dyn_cast_or_null<Defined>(symtab->find(sym->getName()));
2262     if (!sym2)
2263       continue;
2264     const char *suffix2 = sym2->getVersionSuffix();
2265     if (suffix2[0] == '@' && suffix2[1] == '@' &&
2266         strcmp(suffix1 + 1, suffix2 + 2) == 0) {
2267       // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
2268       map.try_emplace(sym, sym2);
2269       // If both foo@v1 and foo@@v1 are defined and non-weak, report a duplicate
2270       // definition error.
2271       if (sym->isDefined())
2272         sym2->checkDuplicate(cast<Defined>(*sym));
2273       sym2->resolve(*sym);
2274       // Eliminate foo@v1 from the symbol table.
2275       sym->symbolKind = Symbol::PlaceholderKind;
2276       sym->isUsedInRegularObj = false;
2277     } else if (auto *sym1 = dyn_cast<Defined>(sym)) {
2278       if (sym2->versionId > VER_NDX_GLOBAL
2279               ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1
2280               : sym1->section == sym2->section && sym1->value == sym2->value) {
2281         // Due to an assembler design flaw, if foo is defined, .symver foo,
2282         // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2283         // different version, GNU ld makes foo@v1 canonical and eliminates foo.
2284         // Emulate its behavior, otherwise we would have foo or foo@@v1 beside
2285         // foo@v1. foo@v1 and foo combining does not apply if they are not
2286         // defined in the same place.
2287         map.try_emplace(sym2, sym);
2288         sym2->symbolKind = Symbol::PlaceholderKind;
2289         sym2->isUsedInRegularObj = false;
2290       }
2291     }
2292   }
2293 
2294   if (map.empty())
2295     return;
2296 
2297   // Update pointers in input files.
2298   parallelForEach(ctx->objectFiles, [&](ELFFileBase *file) {
2299     for (Symbol *&sym : file->getMutableGlobalSymbols())
2300       if (Symbol *s = map.lookup(sym))
2301         sym = s;
2302   });
2303 
2304   // Update pointers in the symbol table.
2305   for (const WrappedSymbol &w : wrapped)
2306     symtab->wrap(w.sym, w.real, w.wrap);
2307 }
2308 
2309 static void checkAndReportMissingFeature(StringRef config, uint32_t features,
2310                                          uint32_t mask, const Twine &report) {
2311   if (!(features & mask)) {
2312     if (config == "error")
2313       error(report);
2314     else if (config == "warning")
2315       warn(report);
2316   }
2317 }
2318 
2319 // To enable CET (x86's hardware-assited control flow enforcement), each
2320 // source file must be compiled with -fcf-protection. Object files compiled
2321 // with the flag contain feature flags indicating that they are compatible
2322 // with CET. We enable the feature only when all object files are compatible
2323 // with CET.
2324 //
2325 // This is also the case with AARCH64's BTI and PAC which use the similar
2326 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
2327 static uint32_t getAndFeatures() {
2328   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
2329       config->emachine != EM_AARCH64)
2330     return 0;
2331 
2332   uint32_t ret = -1;
2333   for (ELFFileBase *f : ctx->objectFiles) {
2334     uint32_t features = f->andFeatures;
2335 
2336     checkAndReportMissingFeature(
2337         config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI,
2338         toString(f) + ": -z bti-report: file does not have "
2339                       "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2340 
2341     checkAndReportMissingFeature(
2342         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT,
2343         toString(f) + ": -z cet-report: file does not have "
2344                       "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2345 
2346     checkAndReportMissingFeature(
2347         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK,
2348         toString(f) + ": -z cet-report: file does not have "
2349                       "GNU_PROPERTY_X86_FEATURE_1_SHSTK property");
2350 
2351     if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
2352       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
2353       if (config->zBtiReport == "none")
2354         warn(toString(f) + ": -z force-bti: file does not have "
2355                            "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2356     } else if (config->zForceIbt &&
2357                !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
2358       if (config->zCetReport == "none")
2359         warn(toString(f) + ": -z force-ibt: file does not have "
2360                            "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2361       features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
2362     }
2363     if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
2364       warn(toString(f) + ": -z pac-plt: file does not have "
2365                          "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
2366       features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
2367     }
2368     ret &= features;
2369   }
2370 
2371   // Force enable Shadow Stack.
2372   if (config->zShstk)
2373     ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
2374 
2375   return ret;
2376 }
2377 
2378 static void initializeLocalSymbols(ELFFileBase *file) {
2379   switch (config->ekind) {
2380   case ELF32LEKind:
2381     cast<ObjFile<ELF32LE>>(file)->initializeLocalSymbols();
2382     break;
2383   case ELF32BEKind:
2384     cast<ObjFile<ELF32BE>>(file)->initializeLocalSymbols();
2385     break;
2386   case ELF64LEKind:
2387     cast<ObjFile<ELF64LE>>(file)->initializeLocalSymbols();
2388     break;
2389   case ELF64BEKind:
2390     cast<ObjFile<ELF64BE>>(file)->initializeLocalSymbols();
2391     break;
2392   default:
2393     llvm_unreachable("");
2394   }
2395 }
2396 
2397 static void postParseObjectFile(ELFFileBase *file) {
2398   switch (config->ekind) {
2399   case ELF32LEKind:
2400     cast<ObjFile<ELF32LE>>(file)->postParse();
2401     break;
2402   case ELF32BEKind:
2403     cast<ObjFile<ELF32BE>>(file)->postParse();
2404     break;
2405   case ELF64LEKind:
2406     cast<ObjFile<ELF64LE>>(file)->postParse();
2407     break;
2408   case ELF64BEKind:
2409     cast<ObjFile<ELF64BE>>(file)->postParse();
2410     break;
2411   default:
2412     llvm_unreachable("");
2413   }
2414 }
2415 
2416 // Do actual linking. Note that when this function is called,
2417 // all linker scripts have already been parsed.
2418 void LinkerDriver::link(opt::InputArgList &args) {
2419   llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
2420   // If a --hash-style option was not given, set to a default value,
2421   // which varies depending on the target.
2422   if (!args.hasArg(OPT_hash_style)) {
2423     if (config->emachine == EM_MIPS)
2424       config->sysvHash = true;
2425     else
2426       config->sysvHash = config->gnuHash = true;
2427   }
2428 
2429   // Default output filename is "a.out" by the Unix tradition.
2430   if (config->outputFile.empty())
2431     config->outputFile = "a.out";
2432 
2433   // Fail early if the output file or map file is not writable. If a user has a
2434   // long link, e.g. due to a large LTO link, they do not wish to run it and
2435   // find that it failed because there was a mistake in their command-line.
2436   {
2437     llvm::TimeTraceScope timeScope("Create output files");
2438     if (auto e = tryCreateFile(config->outputFile))
2439       error("cannot open output file " + config->outputFile + ": " +
2440             e.message());
2441     if (auto e = tryCreateFile(config->mapFile))
2442       error("cannot open map file " + config->mapFile + ": " + e.message());
2443     if (auto e = tryCreateFile(config->whyExtract))
2444       error("cannot open --why-extract= file " + config->whyExtract + ": " +
2445             e.message());
2446   }
2447   if (errorCount())
2448     return;
2449 
2450   // Use default entry point name if no name was given via the command
2451   // line nor linker scripts. For some reason, MIPS entry point name is
2452   // different from others.
2453   config->warnMissingEntry =
2454       (!config->entry.empty() || (!config->shared && !config->relocatable));
2455   if (config->entry.empty() && !config->relocatable)
2456     config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
2457 
2458   // Handle --trace-symbol.
2459   for (auto *arg : args.filtered(OPT_trace_symbol))
2460     symtab->insert(arg->getValue())->traced = true;
2461 
2462   // Handle -u/--undefined before input files. If both a.a and b.so define foo,
2463   // -u foo a.a b.so will extract a.a.
2464   for (StringRef name : config->undefined)
2465     addUnusedUndefined(name)->referenced = true;
2466 
2467   // Add all files to the symbol table. This will add almost all
2468   // symbols that we need to the symbol table. This process might
2469   // add files to the link, via autolinking, these files are always
2470   // appended to the Files vector.
2471   {
2472     llvm::TimeTraceScope timeScope("Parse input files");
2473     for (size_t i = 0; i < files.size(); ++i) {
2474       llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
2475       parseFile(files[i]);
2476     }
2477   }
2478 
2479   // Now that we have every file, we can decide if we will need a
2480   // dynamic symbol table.
2481   // We need one if we were asked to export dynamic symbols or if we are
2482   // producing a shared library.
2483   // We also need one if any shared libraries are used and for pie executables
2484   // (probably because the dynamic linker needs it).
2485   config->hasDynSymTab =
2486       !ctx->sharedFiles.empty() || config->isPic || config->exportDynamic;
2487 
2488   // Some symbols (such as __ehdr_start) are defined lazily only when there
2489   // are undefined symbols for them, so we add these to trigger that logic.
2490   for (StringRef name : script->referencedSymbols) {
2491     Symbol *sym = addUnusedUndefined(name);
2492     sym->isUsedInRegularObj = true;
2493     sym->referenced = true;
2494   }
2495 
2496   // Prevent LTO from removing any definition referenced by -u.
2497   for (StringRef name : config->undefined)
2498     if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name)))
2499       sym->isUsedInRegularObj = true;
2500 
2501   // If an entry symbol is in a static archive, pull out that file now.
2502   if (Symbol *sym = symtab->find(config->entry))
2503     handleUndefined(sym, "--entry");
2504 
2505   // Handle the `--undefined-glob <pattern>` options.
2506   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
2507     handleUndefinedGlob(pat);
2508 
2509   // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2510   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init)))
2511     sym->isUsedInRegularObj = true;
2512   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini)))
2513     sym->isUsedInRegularObj = true;
2514 
2515   // If any of our inputs are bitcode files, the LTO code generator may create
2516   // references to certain library functions that might not be explicit in the
2517   // bitcode file's symbol table. If any of those library functions are defined
2518   // in a bitcode file in an archive member, we need to arrange to use LTO to
2519   // compile those archive members by adding them to the link beforehand.
2520   //
2521   // However, adding all libcall symbols to the link can have undesired
2522   // consequences. For example, the libgcc implementation of
2523   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
2524   // that aborts the program if the Linux kernel does not support 64-bit
2525   // atomics, which would prevent the program from running even if it does not
2526   // use 64-bit atomics.
2527   //
2528   // Therefore, we only add libcall symbols to the link before LTO if we have
2529   // to, i.e. if the symbol's definition is in bitcode. Any other required
2530   // libcall symbols will be added to the link after LTO when we add the LTO
2531   // object file to the link.
2532   if (!ctx->bitcodeFiles.empty())
2533     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2534       handleLibcall(s);
2535 
2536   // Archive members defining __wrap symbols may be extracted.
2537   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
2538 
2539   // No more lazy bitcode can be extracted at this point. Do post parse work
2540   // like checking duplicate symbols.
2541   parallelForEach(ctx->objectFiles, initializeLocalSymbols);
2542   parallelForEach(ctx->objectFiles, postParseObjectFile);
2543   parallelForEach(ctx->bitcodeFiles,
2544                   [](BitcodeFile *file) { file->postParse(); });
2545   for (auto &it : ctx->nonPrevailingSyms) {
2546     Symbol &sym = *it.first;
2547     sym.replace(Undefined{sym.file, sym.getName(), sym.binding, sym.stOther,
2548                           sym.type, it.second});
2549     cast<Undefined>(sym).nonPrevailing = true;
2550   }
2551   ctx->nonPrevailingSyms.clear();
2552   for (const DuplicateSymbol &d : ctx->duplicates)
2553     reportDuplicate(*d.sym, d.file, d.section, d.value);
2554   ctx->duplicates.clear();
2555 
2556   // Return if there were name resolution errors.
2557   if (errorCount())
2558     return;
2559 
2560   // We want to declare linker script's symbols early,
2561   // so that we can version them.
2562   // They also might be exported if referenced by DSOs.
2563   script->declareSymbols();
2564 
2565   // Handle --exclude-libs. This is before scanVersionScript() due to a
2566   // workaround for Android ndk: for a defined versioned symbol in an archive
2567   // without a version node in the version script, Android does not expect a
2568   // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2569   // GNU ld errors in this case.
2570   if (args.hasArg(OPT_exclude_libs))
2571     excludeLibs(args);
2572 
2573   // Create elfHeader early. We need a dummy section in
2574   // addReservedSymbols to mark the created symbols as not absolute.
2575   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
2576 
2577   // We need to create some reserved symbols such as _end. Create them.
2578   if (!config->relocatable)
2579     addReservedSymbols();
2580 
2581   // Apply version scripts.
2582   //
2583   // For a relocatable output, version scripts don't make sense, and
2584   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
2585   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2586   if (!config->relocatable) {
2587     llvm::TimeTraceScope timeScope("Process symbol versions");
2588     symtab->scanVersionScript();
2589   }
2590 
2591   // Skip the normal linked output if some LTO options are specified.
2592   //
2593   // For --thinlto-index-only, index file creation is performed in
2594   // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and
2595   // --plugin-opt=emit-asm create output files in bitcode or assembly code,
2596   // respectively. When only certain thinLTO modules are specified for
2597   // compilation, the intermediate object file are the expected output.
2598   const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM ||
2599                                 config->ltoEmitAsm ||
2600                                 !config->thinLTOModulesToCompile.empty();
2601 
2602   // Do link-time optimization if given files are LLVM bitcode files.
2603   // This compiles bitcode files into real object files.
2604   //
2605   // With this the symbol table should be complete. After this, no new names
2606   // except a few linker-synthesized ones will be added to the symbol table.
2607   const size_t numObjsBeforeLTO = ctx->objectFiles.size();
2608   invokeELFT(compileBitcodeFiles, skipLinkedOutput);
2609 
2610   // Symbol resolution finished. Report backward reference problems,
2611   // --print-archive-stats=, and --why-extract=.
2612   reportBackrefs();
2613   writeArchiveStats();
2614   writeWhyExtract();
2615   if (errorCount())
2616     return;
2617 
2618   // Bail out if normal linked output is skipped due to LTO.
2619   if (skipLinkedOutput)
2620     return;
2621 
2622   // compileBitcodeFiles may have produced lto.tmp object files. After this, no
2623   // more file will be added.
2624   auto newObjectFiles = makeArrayRef(ctx->objectFiles).slice(numObjsBeforeLTO);
2625   parallelForEach(newObjectFiles, initializeLocalSymbols);
2626   parallelForEach(newObjectFiles, postParseObjectFile);
2627   for (const DuplicateSymbol &d : ctx->duplicates)
2628     reportDuplicate(*d.sym, d.file, d.section, d.value);
2629 
2630   // Handle --exclude-libs again because lto.tmp may reference additional
2631   // libcalls symbols defined in an excluded archive. This may override
2632   // versionId set by scanVersionScript().
2633   if (args.hasArg(OPT_exclude_libs))
2634     excludeLibs(args);
2635 
2636   // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
2637   redirectSymbols(wrapped);
2638 
2639   // Replace common symbols with regular symbols.
2640   replaceCommonSymbols();
2641 
2642   {
2643     llvm::TimeTraceScope timeScope("Aggregate sections");
2644     // Now that we have a complete list of input files.
2645     // Beyond this point, no new files are added.
2646     // Aggregate all input sections into one place.
2647     for (InputFile *f : ctx->objectFiles)
2648       for (InputSectionBase *s : f->getSections())
2649         if (s && s != &InputSection::discarded)
2650           inputSections.push_back(s);
2651     for (BinaryFile *f : ctx->binaryFiles)
2652       for (InputSectionBase *s : f->getSections())
2653         inputSections.push_back(cast<InputSection>(s));
2654   }
2655 
2656   {
2657     llvm::TimeTraceScope timeScope("Strip sections");
2658     if (ctx->hasSympart.load(std::memory_order_relaxed)) {
2659       llvm::erase_if(inputSections, [](InputSectionBase *s) {
2660         if (s->type != SHT_LLVM_SYMPART)
2661           return false;
2662         invokeELFT(readSymbolPartitionSection, s);
2663         return true;
2664       });
2665     }
2666     // We do not want to emit debug sections if --strip-all
2667     // or --strip-debug are given.
2668     if (config->strip != StripPolicy::None) {
2669       llvm::erase_if(inputSections, [](InputSectionBase *s) {
2670         if (isDebugSection(*s))
2671           return true;
2672         if (auto *isec = dyn_cast<InputSection>(s))
2673           if (InputSectionBase *rel = isec->getRelocatedSection())
2674             if (isDebugSection(*rel))
2675               return true;
2676 
2677         return false;
2678       });
2679     }
2680   }
2681 
2682   // Since we now have a complete set of input files, we can create
2683   // a .d file to record build dependencies.
2684   if (!config->dependencyFile.empty())
2685     writeDependencyFile();
2686 
2687   // Now that the number of partitions is fixed, save a pointer to the main
2688   // partition.
2689   mainPart = &partitions[0];
2690 
2691   // Read .note.gnu.property sections from input object files which
2692   // contain a hint to tweak linker's and loader's behaviors.
2693   config->andFeatures = getAndFeatures();
2694 
2695   // The Target instance handles target-specific stuff, such as applying
2696   // relocations or writing a PLT section. It also contains target-dependent
2697   // values such as a default image base address.
2698   target = getTarget();
2699 
2700   config->eflags = target->calcEFlags();
2701   // maxPageSize (sometimes called abi page size) is the maximum page size that
2702   // the output can be run on. For example if the OS can use 4k or 64k page
2703   // sizes then maxPageSize must be 64k for the output to be useable on both.
2704   // All important alignment decisions must use this value.
2705   config->maxPageSize = getMaxPageSize(args);
2706   // commonPageSize is the most common page size that the output will be run on.
2707   // For example if an OS can use 4k or 64k page sizes and 4k is more common
2708   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
2709   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
2710   // is limited to writing trap instructions on the last executable segment.
2711   config->commonPageSize = getCommonPageSize(args);
2712 
2713   config->imageBase = getImageBase(args);
2714 
2715   if (config->emachine == EM_ARM) {
2716     // FIXME: These warnings can be removed when lld only uses these features
2717     // when the input objects have been compiled with an architecture that
2718     // supports them.
2719     if (config->armHasBlx == false)
2720       warn("lld uses blx instruction, no object with architecture supporting "
2721            "feature detected");
2722   }
2723 
2724   // This adds a .comment section containing a version string.
2725   if (!config->relocatable)
2726     inputSections.push_back(createCommentSection());
2727 
2728   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
2729   invokeELFT(splitSections);
2730 
2731   // Garbage collection and removal of shared symbols from unused shared objects.
2732   invokeELFT(markLive);
2733   demoteSharedAndLazySymbols();
2734 
2735   // Make copies of any input sections that need to be copied into each
2736   // partition.
2737   copySectionsIntoPartitions();
2738 
2739   // Create synthesized sections such as .got and .plt. This is called before
2740   // processSectionCommands() so that they can be placed by SECTIONS commands.
2741   invokeELFT(createSyntheticSections);
2742 
2743   // Some input sections that are used for exception handling need to be moved
2744   // into synthetic sections. Do that now so that they aren't assigned to
2745   // output sections in the usual way.
2746   if (!config->relocatable)
2747     combineEhSections();
2748 
2749   {
2750     llvm::TimeTraceScope timeScope("Assign sections");
2751 
2752     // Create output sections described by SECTIONS commands.
2753     script->processSectionCommands();
2754 
2755     // Linker scripts control how input sections are assigned to output
2756     // sections. Input sections that were not handled by scripts are called
2757     // "orphans", and they are assigned to output sections by the default rule.
2758     // Process that.
2759     script->addOrphanSections();
2760   }
2761 
2762   {
2763     llvm::TimeTraceScope timeScope("Merge/finalize input sections");
2764 
2765     // Migrate InputSectionDescription::sectionBases to sections. This includes
2766     // merging MergeInputSections into a single MergeSyntheticSection. From this
2767     // point onwards InputSectionDescription::sections should be used instead of
2768     // sectionBases.
2769     for (SectionCommand *cmd : script->sectionCommands)
2770       if (auto *osd = dyn_cast<OutputDesc>(cmd))
2771         osd->osec.finalizeInputSections();
2772     llvm::erase_if(inputSections, [](InputSectionBase *s) {
2773       return isa<MergeInputSection>(s);
2774     });
2775   }
2776 
2777   // Two input sections with different output sections should not be folded.
2778   // ICF runs after processSectionCommands() so that we know the output sections.
2779   if (config->icf != ICFLevel::None) {
2780     invokeELFT(findKeepUniqueSections, args);
2781     invokeELFT(doIcf);
2782   }
2783 
2784   // Read the callgraph now that we know what was gced or icfed
2785   if (config->callGraphProfileSort) {
2786     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
2787       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
2788         readCallGraph(*buffer);
2789     invokeELFT(readCallGraphsFromObjectFiles);
2790   }
2791 
2792   // Write the result to the file.
2793   invokeELFT(writeResult);
2794 }
2795