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