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