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