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