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