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" (or
1334   // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
1335   // unsupported LLVMgold.so option and error.
1336   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) {
1337     StringRef v(arg->getValue());
1338     if (!v.endswith("lto-wrapper") && !v.endswith("lto-wrapper.exe"))
1339       error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
1340             "'");
1341   }
1342 
1343   config->passPlugins = args::getStrings(args, OPT_load_pass_plugins);
1344 
1345   // Parse -mllvm options.
1346   for (auto *arg : args.filtered(OPT_mllvm))
1347     parseClangOption(arg->getValue(), arg->getSpelling());
1348 
1349   // --threads= takes a positive integer and provides the default value for
1350   // --thinlto-jobs=.
1351   if (auto *arg = args.getLastArg(OPT_threads)) {
1352     StringRef v(arg->getValue());
1353     unsigned threads = 0;
1354     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1355       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1356             arg->getValue() + "'");
1357     parallel::strategy = hardware_concurrency(threads);
1358     config->thinLTOJobs = v;
1359   }
1360   if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
1361     config->thinLTOJobs = arg->getValue();
1362 
1363   if (config->ltoo > 3)
1364     error("invalid optimization level for LTO: " + Twine(config->ltoo));
1365   if (config->ltoPartitions == 0)
1366     error("--lto-partitions: number of threads must be > 0");
1367   if (!get_threadpool_strategy(config->thinLTOJobs))
1368     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1369 
1370   if (config->splitStackAdjustSize < 0)
1371     error("--split-stack-adjust-size: size must be >= 0");
1372 
1373   // The text segment is traditionally the first segment, whose address equals
1374   // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1375   // is an old-fashioned option that does not play well with lld's layout.
1376   // Suggest --image-base as a likely alternative.
1377   if (args.hasArg(OPT_Ttext_segment))
1378     error("-Ttext-segment is not supported. Use --image-base if you "
1379           "intend to set the base address");
1380 
1381   // Parse ELF{32,64}{LE,BE} and CPU type.
1382   if (auto *arg = args.getLastArg(OPT_m)) {
1383     StringRef s = arg->getValue();
1384     std::tie(config->ekind, config->emachine, config->osabi) =
1385         parseEmulation(s);
1386     config->mipsN32Abi =
1387         (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
1388     config->emulation = s;
1389   }
1390 
1391   // Parse --hash-style={sysv,gnu,both}.
1392   if (auto *arg = args.getLastArg(OPT_hash_style)) {
1393     StringRef s = arg->getValue();
1394     if (s == "sysv")
1395       config->sysvHash = true;
1396     else if (s == "gnu")
1397       config->gnuHash = true;
1398     else if (s == "both")
1399       config->sysvHash = config->gnuHash = true;
1400     else
1401       error("unknown --hash-style: " + s);
1402   }
1403 
1404   if (args.hasArg(OPT_print_map))
1405     config->mapFile = "-";
1406 
1407   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1408   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1409   // it.
1410   if (config->nmagic || config->omagic)
1411     config->zRelro = false;
1412 
1413   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1414 
1415   if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) {
1416     config->relrGlibc = true;
1417     config->relrPackDynRelocs = true;
1418   } else {
1419     std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1420         getPackDynRelocs(args);
1421   }
1422 
1423   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1424     if (args.hasArg(OPT_call_graph_ordering_file))
1425       error("--symbol-ordering-file and --call-graph-order-file "
1426             "may not be used together");
1427     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1428       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1429       // Also need to disable CallGraphProfileSort to prevent
1430       // LLD order symbols with CGProfile
1431       config->callGraphProfileSort = false;
1432     }
1433   }
1434 
1435   assert(config->versionDefinitions.empty());
1436   config->versionDefinitions.push_back(
1437       {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});
1438   config->versionDefinitions.push_back(
1439       {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});
1440 
1441   // If --retain-symbol-file is used, we'll keep only the symbols listed in
1442   // the file and discard all others.
1443   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1444     config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
1445         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1446     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1447       for (StringRef s : args::getLines(*buffer))
1448         config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
1449             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1450   }
1451 
1452   for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
1453     StringRef pattern(arg->getValue());
1454     if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
1455       config->warnBackrefsExclude.push_back(std::move(*pat));
1456     else
1457       error(arg->getSpelling() + ": " + toString(pat.takeError()));
1458   }
1459 
1460   // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1461   // which should be exported. For -shared, references to matched non-local
1462   // STV_DEFAULT symbols are not bound to definitions within the shared object,
1463   // even if other options express a symbolic intention: -Bsymbolic,
1464   // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1465   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1466     config->dynamicList.push_back(
1467         {arg->getValue(), /*isExternCpp=*/false,
1468          /*hasWildcard=*/hasWildcard(arg->getValue())});
1469 
1470   // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1471   // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1472   // like semantics.
1473   config->symbolic =
1474       config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1475   for (auto *arg :
1476        args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))
1477     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1478       readDynamicList(*buffer);
1479 
1480   for (auto *arg : args.filtered(OPT_version_script))
1481     if (Optional<std::string> path = searchScript(arg->getValue())) {
1482       if (Optional<MemoryBufferRef> buffer = readFile(*path))
1483         readVersionScript(*buffer);
1484     } else {
1485       error(Twine("cannot find version script ") + arg->getValue());
1486     }
1487 }
1488 
1489 // Some Config members do not directly correspond to any particular
1490 // command line options, but computed based on other Config values.
1491 // This function initialize such members. See Config.h for the details
1492 // of these values.
1493 static void setConfigs(opt::InputArgList &args) {
1494   ELFKind k = config->ekind;
1495   uint16_t m = config->emachine;
1496 
1497   config->copyRelocs = (config->relocatable || config->emitRelocs);
1498   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1499   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1500   config->endianness = config->isLE ? endianness::little : endianness::big;
1501   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1502   config->isPic = config->pie || config->shared;
1503   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1504   config->wordsize = config->is64 ? 8 : 4;
1505 
1506   // ELF defines two different ways to store relocation addends as shown below:
1507   //
1508   //  Rel: Addends are stored to the location where relocations are applied. It
1509   //  cannot pack the full range of addend values for all relocation types, but
1510   //  this only affects relocation types that we don't support emitting as
1511   //  dynamic relocations (see getDynRel).
1512   //  Rela: Addends are stored as part of relocation entry.
1513   //
1514   // In other words, Rela makes it easy to read addends at the price of extra
1515   // 4 or 8 byte for each relocation entry.
1516   //
1517   // We pick the format for dynamic relocations according to the psABI for each
1518   // processor, but a contrary choice can be made if the dynamic loader
1519   // supports.
1520   config->isRela = getIsRela(args);
1521 
1522   // If the output uses REL relocations we must store the dynamic relocation
1523   // addends to the output sections. We also store addends for RELA relocations
1524   // if --apply-dynamic-relocs is used.
1525   // We default to not writing the addends when using RELA relocations since
1526   // any standard conforming tool can find it in r_addend.
1527   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1528                                       OPT_no_apply_dynamic_relocs, false) ||
1529                          !config->isRela;
1530   // Validation of dynamic relocation addends is on by default for assertions
1531   // builds (for supported targets) and disabled otherwise. Ideally we would
1532   // enable the debug checks for all targets, but currently not all targets
1533   // have support for reading Elf_Rel addends, so we only enable for a subset.
1534 #ifndef NDEBUG
1535   bool checkDynamicRelocsDefault = m == EM_ARM || m == EM_386 || m == EM_MIPS ||
1536                                    m == EM_X86_64 || m == EM_RISCV;
1537 #else
1538   bool checkDynamicRelocsDefault = false;
1539 #endif
1540   config->checkDynamicRelocs =
1541       args.hasFlag(OPT_check_dynamic_relocations,
1542                    OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);
1543   config->tocOptimize =
1544       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1545   config->pcRelOptimize =
1546       args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
1547 }
1548 
1549 static bool isFormatBinary(StringRef s) {
1550   if (s == "binary")
1551     return true;
1552   if (s == "elf" || s == "default")
1553     return false;
1554   error("unknown --format value: " + s +
1555         " (supported formats: elf, default, binary)");
1556   return false;
1557 }
1558 
1559 void LinkerDriver::createFiles(opt::InputArgList &args) {
1560   llvm::TimeTraceScope timeScope("Load input files");
1561   // For --{push,pop}-state.
1562   std::vector<std::tuple<bool, bool, bool>> stack;
1563 
1564   // Iterate over argv to process input files and positional arguments.
1565   InputFile::isInGroup = false;
1566   bool hasInput = false;
1567   for (auto *arg : args) {
1568     switch (arg->getOption().getID()) {
1569     case OPT_library:
1570       addLibrary(arg->getValue());
1571       hasInput = true;
1572       break;
1573     case OPT_INPUT:
1574       addFile(arg->getValue(), /*withLOption=*/false);
1575       hasInput = true;
1576       break;
1577     case OPT_defsym: {
1578       StringRef from;
1579       StringRef to;
1580       std::tie(from, to) = StringRef(arg->getValue()).split('=');
1581       if (from.empty() || to.empty())
1582         error("--defsym: syntax error: " + StringRef(arg->getValue()));
1583       else
1584         readDefsym(from, MemoryBufferRef(to, "--defsym"));
1585       break;
1586     }
1587     case OPT_script:
1588       if (Optional<std::string> path = searchScript(arg->getValue())) {
1589         if (Optional<MemoryBufferRef> mb = readFile(*path))
1590           readLinkerScript(*mb);
1591         break;
1592       }
1593       error(Twine("cannot find linker script ") + arg->getValue());
1594       break;
1595     case OPT_as_needed:
1596       config->asNeeded = true;
1597       break;
1598     case OPT_format:
1599       config->formatBinary = isFormatBinary(arg->getValue());
1600       break;
1601     case OPT_no_as_needed:
1602       config->asNeeded = false;
1603       break;
1604     case OPT_Bstatic:
1605     case OPT_omagic:
1606     case OPT_nmagic:
1607       config->isStatic = true;
1608       break;
1609     case OPT_Bdynamic:
1610       config->isStatic = false;
1611       break;
1612     case OPT_whole_archive:
1613       inWholeArchive = true;
1614       break;
1615     case OPT_no_whole_archive:
1616       inWholeArchive = false;
1617       break;
1618     case OPT_just_symbols:
1619       if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1620         files.push_back(createObjFile(*mb));
1621         files.back()->justSymbols = true;
1622       }
1623       break;
1624     case OPT_start_group:
1625       if (InputFile::isInGroup)
1626         error("nested --start-group");
1627       InputFile::isInGroup = true;
1628       break;
1629     case OPT_end_group:
1630       if (!InputFile::isInGroup)
1631         error("stray --end-group");
1632       InputFile::isInGroup = false;
1633       ++InputFile::nextGroupId;
1634       break;
1635     case OPT_start_lib:
1636       if (inLib)
1637         error("nested --start-lib");
1638       if (InputFile::isInGroup)
1639         error("may not nest --start-lib in --start-group");
1640       inLib = true;
1641       InputFile::isInGroup = true;
1642       break;
1643     case OPT_end_lib:
1644       if (!inLib)
1645         error("stray --end-lib");
1646       inLib = false;
1647       InputFile::isInGroup = false;
1648       ++InputFile::nextGroupId;
1649       break;
1650     case OPT_push_state:
1651       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1652       break;
1653     case OPT_pop_state:
1654       if (stack.empty()) {
1655         error("unbalanced --push-state/--pop-state");
1656         break;
1657       }
1658       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1659       stack.pop_back();
1660       break;
1661     }
1662   }
1663 
1664   if (files.empty() && !hasInput && errorCount() == 0)
1665     error("no input files");
1666 }
1667 
1668 // If -m <machine_type> was not given, infer it from object files.
1669 void LinkerDriver::inferMachineType() {
1670   if (config->ekind != ELFNoneKind)
1671     return;
1672 
1673   for (InputFile *f : files) {
1674     if (f->ekind == ELFNoneKind)
1675       continue;
1676     config->ekind = f->ekind;
1677     config->emachine = f->emachine;
1678     config->osabi = f->osabi;
1679     config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1680     return;
1681   }
1682   error("target emulation unknown: -m or at least one .o file required");
1683 }
1684 
1685 // Parse -z max-page-size=<value>. The default value is defined by
1686 // each target.
1687 static uint64_t getMaxPageSize(opt::InputArgList &args) {
1688   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1689                                        target->defaultMaxPageSize);
1690   if (!isPowerOf2_64(val)) {
1691     error("max-page-size: value isn't a power of 2");
1692     return target->defaultMaxPageSize;
1693   }
1694   if (config->nmagic || config->omagic) {
1695     if (val != target->defaultMaxPageSize)
1696       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1697     return 1;
1698   }
1699   return val;
1700 }
1701 
1702 // Parse -z common-page-size=<value>. The default value is defined by
1703 // each target.
1704 static uint64_t getCommonPageSize(opt::InputArgList &args) {
1705   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1706                                        target->defaultCommonPageSize);
1707   if (!isPowerOf2_64(val)) {
1708     error("common-page-size: value isn't a power of 2");
1709     return target->defaultCommonPageSize;
1710   }
1711   if (config->nmagic || config->omagic) {
1712     if (val != target->defaultCommonPageSize)
1713       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1714     return 1;
1715   }
1716   // commonPageSize can't be larger than maxPageSize.
1717   if (val > config->maxPageSize)
1718     val = config->maxPageSize;
1719   return val;
1720 }
1721 
1722 // Parses --image-base option.
1723 static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1724   // Because we are using "Config->maxPageSize" here, this function has to be
1725   // called after the variable is initialized.
1726   auto *arg = args.getLastArg(OPT_image_base);
1727   if (!arg)
1728     return None;
1729 
1730   StringRef s = arg->getValue();
1731   uint64_t v;
1732   if (!to_integer(s, v)) {
1733     error("--image-base: number expected, but got " + s);
1734     return 0;
1735   }
1736   if ((v % config->maxPageSize) != 0)
1737     warn("--image-base: address isn't multiple of page size: " + s);
1738   return v;
1739 }
1740 
1741 // Parses `--exclude-libs=lib,lib,...`.
1742 // The library names may be delimited by commas or colons.
1743 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1744   DenseSet<StringRef> ret;
1745   for (auto *arg : args.filtered(OPT_exclude_libs)) {
1746     StringRef s = arg->getValue();
1747     for (;;) {
1748       size_t pos = s.find_first_of(",:");
1749       if (pos == StringRef::npos)
1750         break;
1751       ret.insert(s.substr(0, pos));
1752       s = s.substr(pos + 1);
1753     }
1754     ret.insert(s);
1755   }
1756   return ret;
1757 }
1758 
1759 // Handles the --exclude-libs option. If a static library file is specified
1760 // by the --exclude-libs option, all public symbols from the archive become
1761 // private unless otherwise specified by version scripts or something.
1762 // A special library name "ALL" means all archive files.
1763 //
1764 // This is not a popular option, but some programs such as bionic libc use it.
1765 static void excludeLibs(opt::InputArgList &args) {
1766   DenseSet<StringRef> libs = getExcludeLibs(args);
1767   bool all = libs.count("ALL");
1768 
1769   auto visit = [&](InputFile *file) {
1770     if (file->archiveName.empty() ||
1771         !(all || libs.count(path::filename(file->archiveName))))
1772       return;
1773     ArrayRef<Symbol *> symbols = file->getSymbols();
1774     if (isa<ELFFileBase>(file))
1775       symbols = cast<ELFFileBase>(file)->getGlobalSymbols();
1776     for (Symbol *sym : symbols)
1777       if (!sym->isUndefined() && sym->file == file)
1778         sym->versionId = VER_NDX_LOCAL;
1779   };
1780 
1781   for (ELFFileBase *file : ctx->objectFiles)
1782     visit(file);
1783 
1784   for (BitcodeFile *file : ctx->bitcodeFiles)
1785     visit(file);
1786 }
1787 
1788 // Force Sym to be entered in the output.
1789 static void handleUndefined(Symbol *sym, const char *option) {
1790   // Since a symbol may not be used inside the program, LTO may
1791   // eliminate it. Mark the symbol as "used" to prevent it.
1792   sym->isUsedInRegularObj = true;
1793 
1794   if (!sym->isLazy())
1795     return;
1796   sym->extract();
1797   if (!config->whyExtract.empty())
1798     ctx->whyExtractRecords.emplace_back(option, sym->file, *sym);
1799 }
1800 
1801 // As an extension to GNU linkers, lld supports a variant of `-u`
1802 // which accepts wildcard patterns. All symbols that match a given
1803 // pattern are handled as if they were given by `-u`.
1804 static void handleUndefinedGlob(StringRef arg) {
1805   Expected<GlobPattern> pat = GlobPattern::create(arg);
1806   if (!pat) {
1807     error("--undefined-glob: " + toString(pat.takeError()));
1808     return;
1809   }
1810 
1811   // Calling sym->extract() in the loop is not safe because it may add new
1812   // symbols to the symbol table, invalidating the current iterator.
1813   SmallVector<Symbol *, 0> syms;
1814   for (Symbol *sym : symtab->symbols())
1815     if (!sym->isPlaceholder() && pat->match(sym->getName()))
1816       syms.push_back(sym);
1817 
1818   for (Symbol *sym : syms)
1819     handleUndefined(sym, "--undefined-glob");
1820 }
1821 
1822 static void handleLibcall(StringRef name) {
1823   Symbol *sym = symtab->find(name);
1824   if (!sym || !sym->isLazy())
1825     return;
1826 
1827   MemoryBufferRef mb;
1828   mb = cast<LazyObject>(sym)->file->mb;
1829 
1830   if (isBitcode(mb))
1831     sym->extract();
1832 }
1833 
1834 static void writeArchiveStats() {
1835   if (config->printArchiveStats.empty())
1836     return;
1837 
1838   std::error_code ec;
1839   raw_fd_ostream os(config->printArchiveStats, ec, sys::fs::OF_None);
1840   if (ec) {
1841     error("--print-archive-stats=: cannot open " + config->printArchiveStats +
1842           ": " + ec.message());
1843     return;
1844   }
1845 
1846   os << "members\textracted\tarchive\n";
1847 
1848   SmallVector<StringRef, 0> archives;
1849   DenseMap<CachedHashStringRef, unsigned> all, extracted;
1850   for (ELFFileBase *file : ctx->objectFiles)
1851     if (file->archiveName.size())
1852       ++extracted[CachedHashStringRef(file->archiveName)];
1853   for (BitcodeFile *file : ctx->bitcodeFiles)
1854     if (file->archiveName.size())
1855       ++extracted[CachedHashStringRef(file->archiveName)];
1856   for (std::pair<StringRef, unsigned> f : driver->archiveFiles) {
1857     unsigned &v = extracted[CachedHashString(f.first)];
1858     os << f.second << '\t' << v << '\t' << f.first << '\n';
1859     // If the archive occurs multiple times, other instances have a count of 0.
1860     v = 0;
1861   }
1862 }
1863 
1864 static void writeWhyExtract() {
1865   if (config->whyExtract.empty())
1866     return;
1867 
1868   std::error_code ec;
1869   raw_fd_ostream os(config->whyExtract, ec, sys::fs::OF_None);
1870   if (ec) {
1871     error("cannot open --why-extract= file " + config->whyExtract + ": " +
1872           ec.message());
1873     return;
1874   }
1875 
1876   os << "reference\textracted\tsymbol\n";
1877   for (auto &entry : ctx->whyExtractRecords) {
1878     os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t'
1879        << toString(std::get<2>(entry)) << '\n';
1880   }
1881 }
1882 
1883 static void reportBackrefs() {
1884   for (auto &ref : ctx->backwardReferences) {
1885     const Symbol &sym = *ref.first;
1886     std::string to = toString(ref.second.second);
1887     // Some libraries have known problems and can cause noise. Filter them out
1888     // with --warn-backrefs-exclude=. The value may look like (for --start-lib)
1889     // *.o or (archive member) *.a(*.o).
1890     bool exclude = false;
1891     for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
1892       if (pat.match(to)) {
1893         exclude = true;
1894         break;
1895       }
1896     if (!exclude)
1897       warn("backward reference detected: " + sym.getName() + " in " +
1898            toString(ref.second.first) + " refers to " + to);
1899   }
1900 }
1901 
1902 // Handle --dependency-file=<path>. If that option is given, lld creates a
1903 // file at a given path with the following contents:
1904 //
1905 //   <output-file>: <input-file> ...
1906 //
1907 //   <input-file>:
1908 //
1909 // where <output-file> is a pathname of an output file and <input-file>
1910 // ... is a list of pathnames of all input files. `make` command can read a
1911 // file in the above format and interpret it as a dependency info. We write
1912 // phony targets for every <input-file> to avoid an error when that file is
1913 // removed.
1914 //
1915 // This option is useful if you want to make your final executable to depend
1916 // on all input files including system libraries. Here is why.
1917 //
1918 // When you write a Makefile, you usually write it so that the final
1919 // executable depends on all user-generated object files. Normally, you
1920 // don't make your executable to depend on system libraries (such as libc)
1921 // because you don't know the exact paths of libraries, even though system
1922 // libraries that are linked to your executable statically are technically a
1923 // part of your program. By using --dependency-file option, you can make
1924 // lld to dump dependency info so that you can maintain exact dependencies
1925 // easily.
1926 static void writeDependencyFile() {
1927   std::error_code ec;
1928   raw_fd_ostream os(config->dependencyFile, ec, sys::fs::OF_None);
1929   if (ec) {
1930     error("cannot open " + config->dependencyFile + ": " + ec.message());
1931     return;
1932   }
1933 
1934   // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
1935   // * A space is escaped by a backslash which itself must be escaped.
1936   // * A hash sign is escaped by a single backslash.
1937   // * $ is escapes as $$.
1938   auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
1939     llvm::SmallString<256> nativePath;
1940     llvm::sys::path::native(filename.str(), nativePath);
1941     llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
1942     for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
1943       if (nativePath[i] == '#') {
1944         os << '\\';
1945       } else if (nativePath[i] == ' ') {
1946         os << '\\';
1947         unsigned j = i;
1948         while (j > 0 && nativePath[--j] == '\\')
1949           os << '\\';
1950       } else if (nativePath[i] == '$') {
1951         os << '$';
1952       }
1953       os << nativePath[i];
1954     }
1955   };
1956 
1957   os << config->outputFile << ":";
1958   for (StringRef path : config->dependencyFiles) {
1959     os << " \\\n ";
1960     printFilename(os, path);
1961   }
1962   os << "\n";
1963 
1964   for (StringRef path : config->dependencyFiles) {
1965     os << "\n";
1966     printFilename(os, path);
1967     os << ":\n";
1968   }
1969 }
1970 
1971 // Replaces common symbols with defined symbols reside in .bss sections.
1972 // This function is called after all symbol names are resolved. As a
1973 // result, the passes after the symbol resolution won't see any
1974 // symbols of type CommonSymbol.
1975 static void replaceCommonSymbols() {
1976   llvm::TimeTraceScope timeScope("Replace common symbols");
1977   for (ELFFileBase *file : ctx->objectFiles) {
1978     if (!file->hasCommonSyms)
1979       continue;
1980     for (Symbol *sym : file->getGlobalSymbols()) {
1981       auto *s = dyn_cast<CommonSymbol>(sym);
1982       if (!s)
1983         continue;
1984 
1985       auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1986       bss->file = s->file;
1987       inputSections.push_back(bss);
1988       s->replace(Defined{s->file, StringRef(), s->binding, s->stOther, s->type,
1989                          /*value=*/0, s->size, bss});
1990     }
1991   }
1992 }
1993 
1994 // If all references to a DSO happen to be weak, the DSO is not added to
1995 // DT_NEEDED. If that happens, replace ShardSymbol with Undefined to avoid
1996 // dangling references to an unneeded DSO. Use a weak binding to avoid
1997 // --no-allow-shlib-undefined diagnostics. Similarly, demote lazy symbols.
1998 static void demoteSharedAndLazySymbols() {
1999   llvm::TimeTraceScope timeScope("Demote shared and lazy symbols");
2000   for (Symbol *sym : symtab->symbols()) {
2001     auto *s = dyn_cast<SharedSymbol>(sym);
2002     if (!(s && !cast<SharedFile>(s->file)->isNeeded) && !sym->isLazy())
2003       continue;
2004 
2005     bool used = sym->used;
2006     uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK);
2007     sym->replace(
2008         Undefined{nullptr, sym->getName(), binding, sym->stOther, sym->type});
2009     sym->used = used;
2010     sym->versionId = VER_NDX_GLOBAL;
2011   }
2012 }
2013 
2014 // The section referred to by `s` is considered address-significant. Set the
2015 // keepUnique flag on the section if appropriate.
2016 static void markAddrsig(Symbol *s) {
2017   if (auto *d = dyn_cast_or_null<Defined>(s))
2018     if (d->section)
2019       // We don't need to keep text sections unique under --icf=all even if they
2020       // are address-significant.
2021       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
2022         d->section->keepUnique = true;
2023 }
2024 
2025 // Record sections that define symbols mentioned in --keep-unique <symbol>
2026 // and symbols referred to by address-significance tables. These sections are
2027 // ineligible for ICF.
2028 template <class ELFT>
2029 static void findKeepUniqueSections(opt::InputArgList &args) {
2030   for (auto *arg : args.filtered(OPT_keep_unique)) {
2031     StringRef name = arg->getValue();
2032     auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
2033     if (!d || !d->section) {
2034       warn("could not find symbol " + name + " to keep unique");
2035       continue;
2036     }
2037     d->section->keepUnique = true;
2038   }
2039 
2040   // --icf=all --ignore-data-address-equality means that we can ignore
2041   // the dynsym and address-significance tables entirely.
2042   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
2043     return;
2044 
2045   // Symbols in the dynsym could be address-significant in other executables
2046   // or DSOs, so we conservatively mark them as address-significant.
2047   for (Symbol *sym : symtab->symbols())
2048     if (sym->includeInDynsym())
2049       markAddrsig(sym);
2050 
2051   // Visit the address-significance table in each object file and mark each
2052   // referenced symbol as address-significant.
2053   for (InputFile *f : ctx->objectFiles) {
2054     auto *obj = cast<ObjFile<ELFT>>(f);
2055     ArrayRef<Symbol *> syms = obj->getSymbols();
2056     if (obj->addrsigSec) {
2057       ArrayRef<uint8_t> contents =
2058           check(obj->getObj().getSectionContents(*obj->addrsigSec));
2059       const uint8_t *cur = contents.begin();
2060       while (cur != contents.end()) {
2061         unsigned size;
2062         const char *err;
2063         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
2064         if (err)
2065           fatal(toString(f) + ": could not decode addrsig section: " + err);
2066         markAddrsig(syms[symIndex]);
2067         cur += size;
2068       }
2069     } else {
2070       // If an object file does not have an address-significance table,
2071       // conservatively mark all of its symbols as address-significant.
2072       for (Symbol *s : syms)
2073         markAddrsig(s);
2074     }
2075   }
2076 }
2077 
2078 // This function reads a symbol partition specification section. These sections
2079 // are used to control which partition a symbol is allocated to. See
2080 // https://lld.llvm.org/Partitions.html for more details on partitions.
2081 template <typename ELFT>
2082 static void readSymbolPartitionSection(InputSectionBase *s) {
2083   // Read the relocation that refers to the partition's entry point symbol.
2084   Symbol *sym;
2085   const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
2086   if (rels.areRelocsRel())
2087     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]);
2088   else
2089     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]);
2090   if (!isa<Defined>(sym) || !sym->includeInDynsym())
2091     return;
2092 
2093   StringRef partName = reinterpret_cast<const char *>(s->rawData.data());
2094   for (Partition &part : partitions) {
2095     if (part.name == partName) {
2096       sym->partition = part.getNumber();
2097       return;
2098     }
2099   }
2100 
2101   // Forbid partitions from being used on incompatible targets, and forbid them
2102   // from being used together with various linker features that assume a single
2103   // set of output sections.
2104   if (script->hasSectionsCommand)
2105     error(toString(s->file) +
2106           ": partitions cannot be used with the SECTIONS command");
2107   if (script->hasPhdrsCommands())
2108     error(toString(s->file) +
2109           ": partitions cannot be used with the PHDRS command");
2110   if (!config->sectionStartMap.empty())
2111     error(toString(s->file) + ": partitions cannot be used with "
2112                               "--section-start, -Ttext, -Tdata or -Tbss");
2113   if (config->emachine == EM_MIPS)
2114     error(toString(s->file) + ": partitions cannot be used on this target");
2115 
2116   // Impose a limit of no more than 254 partitions. This limit comes from the
2117   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
2118   // the amount of space devoted to the partition number in RankFlags.
2119   if (partitions.size() == 254)
2120     fatal("may not have more than 254 partitions");
2121 
2122   partitions.emplace_back();
2123   Partition &newPart = partitions.back();
2124   newPart.name = partName;
2125   sym->partition = newPart.getNumber();
2126 }
2127 
2128 static Symbol *addUnusedUndefined(StringRef name,
2129                                   uint8_t binding = STB_GLOBAL) {
2130   return symtab->addSymbol(Undefined{nullptr, name, binding, STV_DEFAULT, 0});
2131 }
2132 
2133 static void markBuffersAsDontNeed(bool skipLinkedOutput) {
2134   // With --thinlto-index-only, all buffers are nearly unused from now on
2135   // (except symbol/section names used by infrequent passes). Mark input file
2136   // buffers as MADV_DONTNEED so that these pages can be reused by the expensive
2137   // thin link, saving memory.
2138   if (skipLinkedOutput) {
2139     for (MemoryBuffer &mb : llvm::make_pointee_range(ctx->memoryBuffers))
2140       mb.dontNeedIfMmap();
2141     return;
2142   }
2143 
2144   // Otherwise, just mark MemoryBuffers backing BitcodeFiles.
2145   DenseSet<const char *> bufs;
2146   for (BitcodeFile *file : ctx->bitcodeFiles)
2147     bufs.insert(file->mb.getBufferStart());
2148   for (BitcodeFile *file : ctx->lazyBitcodeFiles)
2149     bufs.insert(file->mb.getBufferStart());
2150   for (MemoryBuffer &mb : llvm::make_pointee_range(ctx->memoryBuffers))
2151     if (bufs.count(mb.getBufferStart()))
2152       mb.dontNeedIfMmap();
2153 }
2154 
2155 // This function is where all the optimizations of link-time
2156 // optimization takes place. When LTO is in use, some input files are
2157 // not in native object file format but in the LLVM bitcode format.
2158 // This function compiles bitcode files into a few big native files
2159 // using LLVM functions and replaces bitcode symbols with the results.
2160 // Because all bitcode files that the program consists of are passed to
2161 // the compiler at once, it can do a whole-program optimization.
2162 template <class ELFT>
2163 void LinkerDriver::compileBitcodeFiles(bool skipLinkedOutput) {
2164   llvm::TimeTraceScope timeScope("LTO");
2165   // Compile bitcode files and replace bitcode symbols.
2166   lto.reset(new BitcodeCompiler);
2167   for (BitcodeFile *file : ctx->bitcodeFiles)
2168     lto->add(*file);
2169 
2170   if (!ctx->bitcodeFiles.empty())
2171     markBuffersAsDontNeed(skipLinkedOutput);
2172 
2173   for (InputFile *file : lto->compile()) {
2174     auto *obj = cast<ObjFile<ELFT>>(file);
2175     obj->parse(/*ignoreComdats=*/true);
2176 
2177     // Parse '@' in symbol names for non-relocatable output.
2178     if (!config->relocatable)
2179       for (Symbol *sym : obj->getGlobalSymbols())
2180         if (sym->hasVersionSuffix)
2181           sym->parseSymbolVersion();
2182     ctx->objectFiles.push_back(obj);
2183   }
2184 }
2185 
2186 // The --wrap option is a feature to rename symbols so that you can write
2187 // wrappers for existing functions. If you pass `--wrap=foo`, all
2188 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
2189 // expected to write `__wrap_foo` function as a wrapper). The original
2190 // symbol becomes accessible as `__real_foo`, so you can call that from your
2191 // wrapper.
2192 //
2193 // This data structure is instantiated for each --wrap option.
2194 struct WrappedSymbol {
2195   Symbol *sym;
2196   Symbol *real;
2197   Symbol *wrap;
2198 };
2199 
2200 // Handles --wrap option.
2201 //
2202 // This function instantiates wrapper symbols. At this point, they seem
2203 // like they are not being used at all, so we explicitly set some flags so
2204 // that LTO won't eliminate them.
2205 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
2206   std::vector<WrappedSymbol> v;
2207   DenseSet<StringRef> seen;
2208 
2209   for (auto *arg : args.filtered(OPT_wrap)) {
2210     StringRef name = arg->getValue();
2211     if (!seen.insert(name).second)
2212       continue;
2213 
2214     Symbol *sym = symtab->find(name);
2215     if (!sym)
2216       continue;
2217 
2218     Symbol *real = addUnusedUndefined(saver().save("__real_" + name));
2219     Symbol *wrap =
2220         addUnusedUndefined(saver().save("__wrap_" + name), sym->binding);
2221     v.push_back({sym, real, wrap});
2222 
2223     // We want to tell LTO not to inline symbols to be overwritten
2224     // because LTO doesn't know the final symbol contents after renaming.
2225     real->scriptDefined = true;
2226     sym->scriptDefined = true;
2227 
2228     // If a symbol is referenced in any object file, bitcode file or shared
2229     // object, mark its redirection target (foo for __real_foo and __wrap_foo
2230     // for foo) as referenced after redirection, which will be used to tell LTO
2231     // to not eliminate the redirection target. If the object file defining the
2232     // symbol also references it, we cannot easily distinguish the case from
2233     // cases where the symbol is not referenced. Retain the redirection target
2234     // in this case because we choose to wrap symbol references regardless of
2235     // whether the symbol is defined
2236     // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
2237     if (real->referenced || real->isDefined())
2238       sym->referencedAfterWrap = true;
2239     if (sym->referenced || sym->isDefined())
2240       wrap->referencedAfterWrap = true;
2241   }
2242   return v;
2243 }
2244 
2245 // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
2246 //
2247 // When this function is executed, only InputFiles and symbol table
2248 // contain pointers to symbol objects. We visit them to replace pointers,
2249 // so that wrapped symbols are swapped as instructed by the command line.
2250 static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) {
2251   llvm::TimeTraceScope timeScope("Redirect symbols");
2252   DenseMap<Symbol *, Symbol *> map;
2253   for (const WrappedSymbol &w : wrapped) {
2254     map[w.sym] = w.wrap;
2255     map[w.real] = w.sym;
2256   }
2257   for (Symbol *sym : symtab->symbols()) {
2258     // Enumerate symbols with a non-default version (foo@v1). hasVersionSuffix
2259     // filters out most symbols but is not sufficient.
2260     if (!sym->hasVersionSuffix)
2261       continue;
2262     const char *suffix1 = sym->getVersionSuffix();
2263     if (suffix1[0] != '@' || suffix1[1] == '@')
2264       continue;
2265 
2266     // Check the existing symbol foo. We have two special cases to handle:
2267     //
2268     // * There is a definition of foo@v1 and foo@@v1.
2269     // * There is a definition of foo@v1 and foo.
2270     Defined *sym2 = dyn_cast_or_null<Defined>(symtab->find(sym->getName()));
2271     if (!sym2)
2272       continue;
2273     const char *suffix2 = sym2->getVersionSuffix();
2274     if (suffix2[0] == '@' && suffix2[1] == '@' &&
2275         strcmp(suffix1 + 1, suffix2 + 2) == 0) {
2276       // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
2277       map.try_emplace(sym, sym2);
2278       // If both foo@v1 and foo@@v1 are defined and non-weak, report a duplicate
2279       // definition error.
2280       if (sym->isDefined())
2281         sym2->checkDuplicate(cast<Defined>(*sym));
2282       sym2->resolve(*sym);
2283       // Eliminate foo@v1 from the symbol table.
2284       sym->symbolKind = Symbol::PlaceholderKind;
2285       sym->isUsedInRegularObj = false;
2286     } else if (auto *sym1 = dyn_cast<Defined>(sym)) {
2287       if (sym2->versionId > VER_NDX_GLOBAL
2288               ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1
2289               : sym1->section == sym2->section && sym1->value == sym2->value) {
2290         // Due to an assembler design flaw, if foo is defined, .symver foo,
2291         // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2292         // different version, GNU ld makes foo@v1 canonical and eliminates foo.
2293         // Emulate its behavior, otherwise we would have foo or foo@@v1 beside
2294         // foo@v1. foo@v1 and foo combining does not apply if they are not
2295         // defined in the same place.
2296         map.try_emplace(sym2, sym);
2297         sym2->symbolKind = Symbol::PlaceholderKind;
2298         sym2->isUsedInRegularObj = false;
2299       }
2300     }
2301   }
2302 
2303   if (map.empty())
2304     return;
2305 
2306   // Update pointers in input files.
2307   parallelForEach(ctx->objectFiles, [&](ELFFileBase *file) {
2308     for (Symbol *&sym : file->getMutableGlobalSymbols())
2309       if (Symbol *s = map.lookup(sym))
2310         sym = s;
2311   });
2312 
2313   // Update pointers in the symbol table.
2314   for (const WrappedSymbol &w : wrapped)
2315     symtab->wrap(w.sym, w.real, w.wrap);
2316 }
2317 
2318 static void checkAndReportMissingFeature(StringRef config, uint32_t features,
2319                                          uint32_t mask, const Twine &report) {
2320   if (!(features & mask)) {
2321     if (config == "error")
2322       error(report);
2323     else if (config == "warning")
2324       warn(report);
2325   }
2326 }
2327 
2328 // To enable CET (x86's hardware-assited control flow enforcement), each
2329 // source file must be compiled with -fcf-protection. Object files compiled
2330 // with the flag contain feature flags indicating that they are compatible
2331 // with CET. We enable the feature only when all object files are compatible
2332 // with CET.
2333 //
2334 // This is also the case with AARCH64's BTI and PAC which use the similar
2335 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
2336 static uint32_t getAndFeatures() {
2337   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
2338       config->emachine != EM_AARCH64)
2339     return 0;
2340 
2341   uint32_t ret = -1;
2342   for (ELFFileBase *f : ctx->objectFiles) {
2343     uint32_t features = f->andFeatures;
2344 
2345     checkAndReportMissingFeature(
2346         config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI,
2347         toString(f) + ": -z bti-report: file does not have "
2348                       "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2349 
2350     checkAndReportMissingFeature(
2351         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT,
2352         toString(f) + ": -z cet-report: file does not have "
2353                       "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2354 
2355     checkAndReportMissingFeature(
2356         config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK,
2357         toString(f) + ": -z cet-report: file does not have "
2358                       "GNU_PROPERTY_X86_FEATURE_1_SHSTK property");
2359 
2360     if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
2361       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
2362       if (config->zBtiReport == "none")
2363         warn(toString(f) + ": -z force-bti: file does not have "
2364                            "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2365     } else if (config->zForceIbt &&
2366                !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
2367       if (config->zCetReport == "none")
2368         warn(toString(f) + ": -z force-ibt: file does not have "
2369                            "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2370       features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
2371     }
2372     if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
2373       warn(toString(f) + ": -z pac-plt: file does not have "
2374                          "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
2375       features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
2376     }
2377     ret &= features;
2378   }
2379 
2380   // Force enable Shadow Stack.
2381   if (config->zShstk)
2382     ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
2383 
2384   return ret;
2385 }
2386 
2387 static void initializeLocalSymbols(ELFFileBase *file) {
2388   switch (config->ekind) {
2389   case ELF32LEKind:
2390     cast<ObjFile<ELF32LE>>(file)->initializeLocalSymbols();
2391     break;
2392   case ELF32BEKind:
2393     cast<ObjFile<ELF32BE>>(file)->initializeLocalSymbols();
2394     break;
2395   case ELF64LEKind:
2396     cast<ObjFile<ELF64LE>>(file)->initializeLocalSymbols();
2397     break;
2398   case ELF64BEKind:
2399     cast<ObjFile<ELF64BE>>(file)->initializeLocalSymbols();
2400     break;
2401   default:
2402     llvm_unreachable("");
2403   }
2404 }
2405 
2406 static void postParseObjectFile(ELFFileBase *file) {
2407   switch (config->ekind) {
2408   case ELF32LEKind:
2409     cast<ObjFile<ELF32LE>>(file)->postParse();
2410     break;
2411   case ELF32BEKind:
2412     cast<ObjFile<ELF32BE>>(file)->postParse();
2413     break;
2414   case ELF64LEKind:
2415     cast<ObjFile<ELF64LE>>(file)->postParse();
2416     break;
2417   case ELF64BEKind:
2418     cast<ObjFile<ELF64BE>>(file)->postParse();
2419     break;
2420   default:
2421     llvm_unreachable("");
2422   }
2423 }
2424 
2425 // Do actual linking. Note that when this function is called,
2426 // all linker scripts have already been parsed.
2427 void LinkerDriver::link(opt::InputArgList &args) {
2428   llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
2429   // If a --hash-style option was not given, set to a default value,
2430   // which varies depending on the target.
2431   if (!args.hasArg(OPT_hash_style)) {
2432     if (config->emachine == EM_MIPS)
2433       config->sysvHash = true;
2434     else
2435       config->sysvHash = config->gnuHash = true;
2436   }
2437 
2438   // Default output filename is "a.out" by the Unix tradition.
2439   if (config->outputFile.empty())
2440     config->outputFile = "a.out";
2441 
2442   // Fail early if the output file or map file is not writable. If a user has a
2443   // long link, e.g. due to a large LTO link, they do not wish to run it and
2444   // find that it failed because there was a mistake in their command-line.
2445   {
2446     llvm::TimeTraceScope timeScope("Create output files");
2447     if (auto e = tryCreateFile(config->outputFile))
2448       error("cannot open output file " + config->outputFile + ": " +
2449             e.message());
2450     if (auto e = tryCreateFile(config->mapFile))
2451       error("cannot open map file " + config->mapFile + ": " + e.message());
2452     if (auto e = tryCreateFile(config->whyExtract))
2453       error("cannot open --why-extract= file " + config->whyExtract + ": " +
2454             e.message());
2455   }
2456   if (errorCount())
2457     return;
2458 
2459   // Use default entry point name if no name was given via the command
2460   // line nor linker scripts. For some reason, MIPS entry point name is
2461   // different from others.
2462   config->warnMissingEntry =
2463       (!config->entry.empty() || (!config->shared && !config->relocatable));
2464   if (config->entry.empty() && !config->relocatable)
2465     config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
2466 
2467   // Handle --trace-symbol.
2468   for (auto *arg : args.filtered(OPT_trace_symbol))
2469     symtab->insert(arg->getValue())->traced = true;
2470 
2471   // Handle -u/--undefined before input files. If both a.a and b.so define foo,
2472   // -u foo a.a b.so will extract a.a.
2473   for (StringRef name : config->undefined)
2474     addUnusedUndefined(name)->referenced = true;
2475 
2476   // Add all files to the symbol table. This will add almost all
2477   // symbols that we need to the symbol table. This process might
2478   // add files to the link, via autolinking, these files are always
2479   // appended to the Files vector.
2480   {
2481     llvm::TimeTraceScope timeScope("Parse input files");
2482     for (size_t i = 0; i < files.size(); ++i) {
2483       llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
2484       parseFile(files[i]);
2485     }
2486   }
2487 
2488   // Now that we have every file, we can decide if we will need a
2489   // dynamic symbol table.
2490   // We need one if we were asked to export dynamic symbols or if we are
2491   // producing a shared library.
2492   // We also need one if any shared libraries are used and for pie executables
2493   // (probably because the dynamic linker needs it).
2494   config->hasDynSymTab =
2495       !ctx->sharedFiles.empty() || config->isPic || config->exportDynamic;
2496 
2497   // Some symbols (such as __ehdr_start) are defined lazily only when there
2498   // are undefined symbols for them, so we add these to trigger that logic.
2499   for (StringRef name : script->referencedSymbols) {
2500     Symbol *sym = addUnusedUndefined(name);
2501     sym->isUsedInRegularObj = true;
2502     sym->referenced = true;
2503   }
2504 
2505   // Prevent LTO from removing any definition referenced by -u.
2506   for (StringRef name : config->undefined)
2507     if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name)))
2508       sym->isUsedInRegularObj = true;
2509 
2510   // If an entry symbol is in a static archive, pull out that file now.
2511   if (Symbol *sym = symtab->find(config->entry))
2512     handleUndefined(sym, "--entry");
2513 
2514   // Handle the `--undefined-glob <pattern>` options.
2515   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
2516     handleUndefinedGlob(pat);
2517 
2518   // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2519   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init)))
2520     sym->isUsedInRegularObj = true;
2521   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini)))
2522     sym->isUsedInRegularObj = true;
2523 
2524   // If any of our inputs are bitcode files, the LTO code generator may create
2525   // references to certain library functions that might not be explicit in the
2526   // bitcode file's symbol table. If any of those library functions are defined
2527   // in a bitcode file in an archive member, we need to arrange to use LTO to
2528   // compile those archive members by adding them to the link beforehand.
2529   //
2530   // However, adding all libcall symbols to the link can have undesired
2531   // consequences. For example, the libgcc implementation of
2532   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
2533   // that aborts the program if the Linux kernel does not support 64-bit
2534   // atomics, which would prevent the program from running even if it does not
2535   // use 64-bit atomics.
2536   //
2537   // Therefore, we only add libcall symbols to the link before LTO if we have
2538   // to, i.e. if the symbol's definition is in bitcode. Any other required
2539   // libcall symbols will be added to the link after LTO when we add the LTO
2540   // object file to the link.
2541   if (!ctx->bitcodeFiles.empty())
2542     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2543       handleLibcall(s);
2544 
2545   // Archive members defining __wrap symbols may be extracted.
2546   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
2547 
2548   // No more lazy bitcode can be extracted at this point. Do post parse work
2549   // like checking duplicate symbols.
2550   parallelForEach(ctx->objectFiles, initializeLocalSymbols);
2551   parallelForEach(ctx->objectFiles, postParseObjectFile);
2552   parallelForEach(ctx->bitcodeFiles,
2553                   [](BitcodeFile *file) { file->postParse(); });
2554   for (auto &it : ctx->nonPrevailingSyms) {
2555     Symbol &sym = *it.first;
2556     sym.replace(Undefined{sym.file, sym.getName(), sym.binding, sym.stOther,
2557                           sym.type, it.second});
2558     cast<Undefined>(sym).nonPrevailing = true;
2559   }
2560   ctx->nonPrevailingSyms.clear();
2561   for (const DuplicateSymbol &d : ctx->duplicates)
2562     reportDuplicate(*d.sym, d.file, d.section, d.value);
2563   ctx->duplicates.clear();
2564 
2565   // Return if there were name resolution errors.
2566   if (errorCount())
2567     return;
2568 
2569   // We want to declare linker script's symbols early,
2570   // so that we can version them.
2571   // They also might be exported if referenced by DSOs.
2572   script->declareSymbols();
2573 
2574   // Handle --exclude-libs. This is before scanVersionScript() due to a
2575   // workaround for Android ndk: for a defined versioned symbol in an archive
2576   // without a version node in the version script, Android does not expect a
2577   // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2578   // GNU ld errors in this case.
2579   if (args.hasArg(OPT_exclude_libs))
2580     excludeLibs(args);
2581 
2582   // Create elfHeader early. We need a dummy section in
2583   // addReservedSymbols to mark the created symbols as not absolute.
2584   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
2585 
2586   // We need to create some reserved symbols such as _end. Create them.
2587   if (!config->relocatable)
2588     addReservedSymbols();
2589 
2590   // Apply version scripts.
2591   //
2592   // For a relocatable output, version scripts don't make sense, and
2593   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
2594   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2595   if (!config->relocatable) {
2596     llvm::TimeTraceScope timeScope("Process symbol versions");
2597     symtab->scanVersionScript();
2598   }
2599 
2600   // Skip the normal linked output if some LTO options are specified.
2601   //
2602   // For --thinlto-index-only, index file creation is performed in
2603   // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and
2604   // --plugin-opt=emit-asm create output files in bitcode or assembly code,
2605   // respectively. When only certain thinLTO modules are specified for
2606   // compilation, the intermediate object file are the expected output.
2607   const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM ||
2608                                 config->ltoEmitAsm ||
2609                                 !config->thinLTOModulesToCompile.empty();
2610 
2611   // Do link-time optimization if given files are LLVM bitcode files.
2612   // This compiles bitcode files into real object files.
2613   //
2614   // With this the symbol table should be complete. After this, no new names
2615   // except a few linker-synthesized ones will be added to the symbol table.
2616   const size_t numObjsBeforeLTO = ctx->objectFiles.size();
2617   invokeELFT(compileBitcodeFiles, skipLinkedOutput);
2618 
2619   // Symbol resolution finished. Report backward reference problems,
2620   // --print-archive-stats=, and --why-extract=.
2621   reportBackrefs();
2622   writeArchiveStats();
2623   writeWhyExtract();
2624   if (errorCount())
2625     return;
2626 
2627   // Bail out if normal linked output is skipped due to LTO.
2628   if (skipLinkedOutput)
2629     return;
2630 
2631   // compileBitcodeFiles may have produced lto.tmp object files. After this, no
2632   // more file will be added.
2633   auto newObjectFiles = makeArrayRef(ctx->objectFiles).slice(numObjsBeforeLTO);
2634   parallelForEach(newObjectFiles, initializeLocalSymbols);
2635   parallelForEach(newObjectFiles, postParseObjectFile);
2636   for (const DuplicateSymbol &d : ctx->duplicates)
2637     reportDuplicate(*d.sym, d.file, d.section, d.value);
2638 
2639   // Handle --exclude-libs again because lto.tmp may reference additional
2640   // libcalls symbols defined in an excluded archive. This may override
2641   // versionId set by scanVersionScript().
2642   if (args.hasArg(OPT_exclude_libs))
2643     excludeLibs(args);
2644 
2645   // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
2646   redirectSymbols(wrapped);
2647 
2648   // Replace common symbols with regular symbols.
2649   replaceCommonSymbols();
2650 
2651   {
2652     llvm::TimeTraceScope timeScope("Aggregate sections");
2653     // Now that we have a complete list of input files.
2654     // Beyond this point, no new files are added.
2655     // Aggregate all input sections into one place.
2656     for (InputFile *f : ctx->objectFiles)
2657       for (InputSectionBase *s : f->getSections())
2658         if (s && s != &InputSection::discarded)
2659           inputSections.push_back(s);
2660     for (BinaryFile *f : ctx->binaryFiles)
2661       for (InputSectionBase *s : f->getSections())
2662         inputSections.push_back(cast<InputSection>(s));
2663   }
2664 
2665   {
2666     llvm::TimeTraceScope timeScope("Strip sections");
2667     if (ctx->hasSympart.load(std::memory_order_relaxed)) {
2668       llvm::erase_if(inputSections, [](InputSectionBase *s) {
2669         if (s->type != SHT_LLVM_SYMPART)
2670           return false;
2671         invokeELFT(readSymbolPartitionSection, s);
2672         return true;
2673       });
2674     }
2675     // We do not want to emit debug sections if --strip-all
2676     // or --strip-debug are given.
2677     if (config->strip != StripPolicy::None) {
2678       llvm::erase_if(inputSections, [](InputSectionBase *s) {
2679         if (isDebugSection(*s))
2680           return true;
2681         if (auto *isec = dyn_cast<InputSection>(s))
2682           if (InputSectionBase *rel = isec->getRelocatedSection())
2683             if (isDebugSection(*rel))
2684               return true;
2685 
2686         return false;
2687       });
2688     }
2689   }
2690 
2691   // Since we now have a complete set of input files, we can create
2692   // a .d file to record build dependencies.
2693   if (!config->dependencyFile.empty())
2694     writeDependencyFile();
2695 
2696   // Now that the number of partitions is fixed, save a pointer to the main
2697   // partition.
2698   mainPart = &partitions[0];
2699 
2700   // Read .note.gnu.property sections from input object files which
2701   // contain a hint to tweak linker's and loader's behaviors.
2702   config->andFeatures = getAndFeatures();
2703 
2704   // The Target instance handles target-specific stuff, such as applying
2705   // relocations or writing a PLT section. It also contains target-dependent
2706   // values such as a default image base address.
2707   target = getTarget();
2708 
2709   config->eflags = target->calcEFlags();
2710   // maxPageSize (sometimes called abi page size) is the maximum page size that
2711   // the output can be run on. For example if the OS can use 4k or 64k page
2712   // sizes then maxPageSize must be 64k for the output to be useable on both.
2713   // All important alignment decisions must use this value.
2714   config->maxPageSize = getMaxPageSize(args);
2715   // commonPageSize is the most common page size that the output will be run on.
2716   // For example if an OS can use 4k or 64k page sizes and 4k is more common
2717   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
2718   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
2719   // is limited to writing trap instructions on the last executable segment.
2720   config->commonPageSize = getCommonPageSize(args);
2721 
2722   config->imageBase = getImageBase(args);
2723 
2724   if (config->emachine == EM_ARM) {
2725     // FIXME: These warnings can be removed when lld only uses these features
2726     // when the input objects have been compiled with an architecture that
2727     // supports them.
2728     if (config->armHasBlx == false)
2729       warn("lld uses blx instruction, no object with architecture supporting "
2730            "feature detected");
2731   }
2732 
2733   // This adds a .comment section containing a version string.
2734   if (!config->relocatable)
2735     inputSections.push_back(createCommentSection());
2736 
2737   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
2738   invokeELFT(splitSections);
2739 
2740   // Garbage collection and removal of shared symbols from unused shared objects.
2741   invokeELFT(markLive);
2742   demoteSharedAndLazySymbols();
2743 
2744   // Make copies of any input sections that need to be copied into each
2745   // partition.
2746   copySectionsIntoPartitions();
2747 
2748   // Create synthesized sections such as .got and .plt. This is called before
2749   // processSectionCommands() so that they can be placed by SECTIONS commands.
2750   invokeELFT(createSyntheticSections);
2751 
2752   // Some input sections that are used for exception handling need to be moved
2753   // into synthetic sections. Do that now so that they aren't assigned to
2754   // output sections in the usual way.
2755   if (!config->relocatable)
2756     combineEhSections();
2757 
2758   {
2759     llvm::TimeTraceScope timeScope("Assign sections");
2760 
2761     // Create output sections described by SECTIONS commands.
2762     script->processSectionCommands();
2763 
2764     // Linker scripts control how input sections are assigned to output
2765     // sections. Input sections that were not handled by scripts are called
2766     // "orphans", and they are assigned to output sections by the default rule.
2767     // Process that.
2768     script->addOrphanSections();
2769   }
2770 
2771   {
2772     llvm::TimeTraceScope timeScope("Merge/finalize input sections");
2773 
2774     // Migrate InputSectionDescription::sectionBases to sections. This includes
2775     // merging MergeInputSections into a single MergeSyntheticSection. From this
2776     // point onwards InputSectionDescription::sections should be used instead of
2777     // sectionBases.
2778     for (SectionCommand *cmd : script->sectionCommands)
2779       if (auto *osd = dyn_cast<OutputDesc>(cmd))
2780         osd->osec.finalizeInputSections();
2781     llvm::erase_if(inputSections, [](InputSectionBase *s) {
2782       return isa<MergeInputSection>(s);
2783     });
2784   }
2785 
2786   // Two input sections with different output sections should not be folded.
2787   // ICF runs after processSectionCommands() so that we know the output sections.
2788   if (config->icf != ICFLevel::None) {
2789     invokeELFT(findKeepUniqueSections, args);
2790     invokeELFT(doIcf);
2791   }
2792 
2793   // Read the callgraph now that we know what was gced or icfed
2794   if (config->callGraphProfileSort) {
2795     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
2796       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
2797         readCallGraph(*buffer);
2798     invokeELFT(readCallGraphsFromObjectFiles);
2799   }
2800 
2801   // Write the result to the file.
2802   invokeELFT(writeResult);
2803 }
2804