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