xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision bb09ef95)
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/LTO/LTO.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compression.h"
53 #include "llvm/Support/GlobPattern.h"
54 #include "llvm/Support/LEB128.h"
55 #include "llvm/Support/Parallel.h"
56 #include "llvm/Support/Path.h"
57 #include "llvm/Support/TarWriter.h"
58 #include "llvm/Support/TargetSelect.h"
59 #include "llvm/Support/TimeProfiler.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include <cstdlib>
62 #include <utility>
63 
64 using namespace llvm;
65 using namespace llvm::ELF;
66 using namespace llvm::object;
67 using namespace llvm::sys;
68 using namespace llvm::support;
69 using namespace lld;
70 using namespace lld::elf;
71 
72 Configuration *elf::config;
73 LinkerDriver *elf::driver;
74 
75 static void setConfigs(opt::InputArgList &args);
76 static void readConfigs(opt::InputArgList &args);
77 
78 bool elf::link(ArrayRef<const char *> args, bool canExitEarly,
79                raw_ostream &stdoutOS, raw_ostream &stderrOS) {
80   lld::stdoutOS = &stdoutOS;
81   lld::stderrOS = &stderrOS;
82 
83   errorHandler().logName = args::getFilenameWithoutExe(args[0]);
84   errorHandler().errorLimitExceededMsg =
85       "too many errors emitted, stopping now (use "
86       "-error-limit=0 to see all errors)";
87   errorHandler().exitEarly = canExitEarly;
88   stderrOS.enable_colors(stderrOS.has_colors());
89 
90   inputSections.clear();
91   outputSections.clear();
92   archiveFiles.clear();
93   binaryFiles.clear();
94   bitcodeFiles.clear();
95   lazyObjFiles.clear();
96   objectFiles.clear();
97   sharedFiles.clear();
98   backwardReferences.clear();
99 
100   config = make<Configuration>();
101   driver = make<LinkerDriver>();
102   script = make<LinkerScript>();
103   symtab = make<SymbolTable>();
104 
105   tar = nullptr;
106   memset(&in, 0, sizeof(in));
107 
108   partitions = {Partition()};
109 
110   SharedFile::vernauxNum = 0;
111 
112   config->progName = args[0];
113 
114   driver->main(args);
115 
116   // Exit immediately if we don't need to return to the caller.
117   // This saves time because the overhead of calling destructors
118   // for all globally-allocated objects is not negligible.
119   if (canExitEarly)
120     exitLld(errorCount() ? 1 : 0);
121 
122   freeArena();
123   return !errorCount();
124 }
125 
126 // Parses a linker -m option.
127 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
128   uint8_t osabi = 0;
129   StringRef s = emul;
130   if (s.endswith("_fbsd")) {
131     s = s.drop_back(5);
132     osabi = ELFOSABI_FREEBSD;
133   }
134 
135   std::pair<ELFKind, uint16_t> ret =
136       StringSwitch<std::pair<ELFKind, uint16_t>>(s)
137           .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
138                  {ELF64LEKind, EM_AARCH64})
139           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
140           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
141           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
142           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
143           .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
144           .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
145           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
146           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
147           .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
148           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
149           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
150           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
151           .Case("elf_i386", {ELF32LEKind, EM_386})
152           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
153           .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
154           .Default({ELFNoneKind, EM_NONE});
155 
156   if (ret.first == ELFNoneKind)
157     error("unknown emulation: " + emul);
158   return std::make_tuple(ret.first, ret.second, osabi);
159 }
160 
161 // Returns slices of MB by parsing MB as an archive file.
162 // Each slice consists of a member file in the archive.
163 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
164     MemoryBufferRef mb) {
165   std::unique_ptr<Archive> file =
166       CHECK(Archive::create(mb),
167             mb.getBufferIdentifier() + ": failed to parse archive");
168 
169   std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
170   Error err = Error::success();
171   bool addToTar = file->isThin() && tar;
172   for (const Archive::Child &c : file->children(err)) {
173     MemoryBufferRef mbref =
174         CHECK(c.getMemoryBufferRef(),
175               mb.getBufferIdentifier() +
176                   ": could not get the buffer for a child of the archive");
177     if (addToTar)
178       tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
179     v.push_back(std::make_pair(mbref, c.getChildOffset()));
180   }
181   if (err)
182     fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
183           toString(std::move(err)));
184 
185   // Take ownership of memory buffers created for members of thin archives.
186   for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
187     make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
188 
189   return v;
190 }
191 
192 // Opens a file and create a file object. Path has to be resolved already.
193 void LinkerDriver::addFile(StringRef path, bool withLOption) {
194   using namespace sys::fs;
195 
196   Optional<MemoryBufferRef> buffer = readFile(path);
197   if (!buffer.hasValue())
198     return;
199   MemoryBufferRef mbref = *buffer;
200 
201   if (config->formatBinary) {
202     files.push_back(make<BinaryFile>(mbref));
203     return;
204   }
205 
206   switch (identify_magic(mbref.getBuffer())) {
207   case file_magic::unknown:
208     readLinkerScript(mbref);
209     return;
210   case file_magic::archive: {
211     // Handle -whole-archive.
212     if (inWholeArchive) {
213       for (const auto &p : getArchiveMembers(mbref))
214         files.push_back(createObjectFile(p.first, path, p.second));
215       return;
216     }
217 
218     std::unique_ptr<Archive> file =
219         CHECK(Archive::create(mbref), path + ": failed to parse archive");
220 
221     // If an archive file has no symbol table, it is likely that a user
222     // is attempting LTO and using a default ar command that doesn't
223     // understand the LLVM bitcode file. It is a pretty common error, so
224     // we'll handle it as if it had a symbol table.
225     if (!file->isEmpty() && !file->hasSymbolTable()) {
226       // Check if all members are bitcode files. If not, ignore, which is the
227       // default action without the LTO hack described above.
228       for (const std::pair<MemoryBufferRef, uint64_t> &p :
229            getArchiveMembers(mbref))
230         if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) {
231           error(path + ": archive has no index; run ranlib to add one");
232           return;
233         }
234 
235       for (const std::pair<MemoryBufferRef, uint64_t> &p :
236            getArchiveMembers(mbref))
237         files.push_back(make<LazyObjFile>(p.first, path, p.second));
238       return;
239     }
240 
241     // Handle the regular case.
242     files.push_back(make<ArchiveFile>(std::move(file)));
243     return;
244   }
245   case file_magic::elf_shared_object:
246     if (config->isStatic || config->relocatable) {
247       error("attempted static link of dynamic object " + path);
248       return;
249     }
250 
251     // DSOs usually have DT_SONAME tags in their ELF headers, and the
252     // sonames are used to identify DSOs. But if they are missing,
253     // they are identified by filenames. We don't know whether the new
254     // file has a DT_SONAME or not because we haven't parsed it yet.
255     // Here, we set the default soname for the file because we might
256     // need it later.
257     //
258     // If a file was specified by -lfoo, the directory part is not
259     // significant, as a user did not specify it. This behavior is
260     // compatible with GNU.
261     files.push_back(
262         make<SharedFile>(mbref, withLOption ? path::filename(path) : path));
263     return;
264   case file_magic::bitcode:
265   case file_magic::elf_relocatable:
266     if (inLib)
267       files.push_back(make<LazyObjFile>(mbref, "", 0));
268     else
269       files.push_back(createObjectFile(mbref));
270     break;
271   default:
272     error(path + ": unknown file type");
273   }
274 }
275 
276 // Add a given library by searching it from input search paths.
277 void LinkerDriver::addLibrary(StringRef name) {
278   if (Optional<std::string> path = searchLibrary(name))
279     addFile(*path, /*withLOption=*/true);
280   else
281     error("unable to find library -l" + name);
282 }
283 
284 // This function is called on startup. We need this for LTO since
285 // LTO calls LLVM functions to compile bitcode files to native code.
286 // Technically this can be delayed until we read bitcode files, but
287 // we don't bother to do lazily because the initialization is fast.
288 static void initLLVM() {
289   InitializeAllTargets();
290   InitializeAllTargetMCs();
291   InitializeAllAsmPrinters();
292   InitializeAllAsmParsers();
293 }
294 
295 // Some command line options or some combinations of them are not allowed.
296 // This function checks for such errors.
297 static void checkOptions() {
298   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
299   // table which is a relatively new feature.
300   if (config->emachine == EM_MIPS && config->gnuHash)
301     error("the .gnu.hash section is not compatible with the MIPS target");
302 
303   if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
304     error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
305 
306   if (config->fixCortexA8 && config->emachine != EM_ARM)
307     error("--fix-cortex-a8 is only supported on ARM targets");
308 
309   if (config->tocOptimize && config->emachine != EM_PPC64)
310     error("--toc-optimize is only supported on the PowerPC64 target");
311 
312   if (config->pcRelOptimize && config->emachine != EM_PPC64)
313     error("--pcrel--optimize is only supported on the PowerPC64 target");
314 
315   if (config->pie && config->shared)
316     error("-shared and -pie may not be used together");
317 
318   if (!config->shared && !config->filterList.empty())
319     error("-F may not be used without -shared");
320 
321   if (!config->shared && !config->auxiliaryList.empty())
322     error("-f may not be used without -shared");
323 
324   if (!config->relocatable && !config->defineCommon)
325     error("-no-define-common not supported in non relocatable output");
326 
327   if (config->strip == StripPolicy::All && config->emitRelocs)
328     error("--strip-all and --emit-relocs may not be used together");
329 
330   if (config->zText && config->zIfuncNoplt)
331     error("-z text and -z ifunc-noplt may not be used together");
332 
333   if (config->relocatable) {
334     if (config->shared)
335       error("-r and -shared may not be used together");
336     if (config->gdbIndex)
337       error("-r and --gdb-index may not be used together");
338     if (config->icf != ICFLevel::None)
339       error("-r and --icf may not be used together");
340     if (config->pie)
341       error("-r and -pie may not be used together");
342     if (config->exportDynamic)
343       error("-r and --export-dynamic may not be used together");
344   }
345 
346   if (config->executeOnly) {
347     if (config->emachine != EM_AARCH64)
348       error("-execute-only is only supported on AArch64 targets");
349 
350     if (config->singleRoRx && !script->hasSectionsCommand)
351       error("-execute-only and -no-rosegment cannot be used together");
352   }
353 
354   if (config->zRetpolineplt && config->zForceIbt)
355     error("-z force-ibt may not be used with -z retpolineplt");
356 
357   if (config->emachine != EM_AARCH64) {
358     if (config->zPacPlt)
359       error("-z pac-plt only supported on AArch64");
360     if (config->zForceBti)
361       error("-z force-bti only supported on AArch64");
362   }
363 }
364 
365 static const char *getReproduceOption(opt::InputArgList &args) {
366   if (auto *arg = args.getLastArg(OPT_reproduce))
367     return arg->getValue();
368   return getenv("LLD_REPRODUCE");
369 }
370 
371 static bool hasZOption(opt::InputArgList &args, StringRef key) {
372   for (auto *arg : args.filtered(OPT_z))
373     if (key == arg->getValue())
374       return true;
375   return false;
376 }
377 
378 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
379                      bool Default) {
380   for (auto *arg : args.filtered_reverse(OPT_z)) {
381     if (k1 == arg->getValue())
382       return true;
383     if (k2 == arg->getValue())
384       return false;
385   }
386   return Default;
387 }
388 
389 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
390   for (auto *arg : args.filtered_reverse(OPT_z)) {
391     StringRef v = arg->getValue();
392     if (v == "noseparate-code")
393       return SeparateSegmentKind::None;
394     if (v == "separate-code")
395       return SeparateSegmentKind::Code;
396     if (v == "separate-loadable-segments")
397       return SeparateSegmentKind::Loadable;
398   }
399   return SeparateSegmentKind::None;
400 }
401 
402 static GnuStackKind getZGnuStack(opt::InputArgList &args) {
403   for (auto *arg : args.filtered_reverse(OPT_z)) {
404     if (StringRef("execstack") == arg->getValue())
405       return GnuStackKind::Exec;
406     if (StringRef("noexecstack") == arg->getValue())
407       return GnuStackKind::NoExec;
408     if (StringRef("nognustack") == arg->getValue())
409       return GnuStackKind::None;
410   }
411 
412   return GnuStackKind::NoExec;
413 }
414 
415 static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
416   for (auto *arg : args.filtered_reverse(OPT_z)) {
417     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
418     if (kv.first == "start-stop-visibility") {
419       if (kv.second == "default")
420         return STV_DEFAULT;
421       else if (kv.second == "internal")
422         return STV_INTERNAL;
423       else if (kv.second == "hidden")
424         return STV_HIDDEN;
425       else if (kv.second == "protected")
426         return STV_PROTECTED;
427       error("unknown -z start-stop-visibility= value: " + StringRef(kv.second));
428     }
429   }
430   return STV_PROTECTED;
431 }
432 
433 static bool isKnownZFlag(StringRef s) {
434   return s == "combreloc" || s == "copyreloc" || s == "defs" ||
435          s == "execstack" || s == "force-bti" || s == "force-ibt" ||
436          s == "global" || s == "hazardplt" || s == "ifunc-noplt" ||
437          s == "initfirst" || s == "interpose" ||
438          s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
439          s == "separate-code" || s == "separate-loadable-segments" ||
440          s == "nocombreloc" || s == "nocopyreloc" || s == "nodefaultlib" ||
441          s == "nodelete" || s == "nodlopen" || s == "noexecstack" ||
442          s == "nognustack" || s == "nokeep-text-section-prefix" ||
443          s == "norelro" || s == "noseparate-code" || s == "notext" ||
444          s == "now" || s == "origin" || s == "pac-plt" || s == "rel" ||
445          s == "rela" || s == "relro" || s == "retpolineplt" ||
446          s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" ||
447          s == "wxneeded" || s.startswith("common-page-size=") ||
448          s.startswith("dead-reloc-in-nonalloc=") ||
449          s.startswith("max-page-size=") || s.startswith("stack-size=") ||
450          s.startswith("start-stop-visibility=");
451 }
452 
453 // Report an error for an unknown -z option.
454 static void checkZOptions(opt::InputArgList &args) {
455   for (auto *arg : args.filtered(OPT_z))
456     if (!isKnownZFlag(arg->getValue()))
457       error("unknown -z value: " + StringRef(arg->getValue()));
458 }
459 
460 void LinkerDriver::main(ArrayRef<const char *> argsArr) {
461   ELFOptTable parser;
462   opt::InputArgList args = parser.parse(argsArr.slice(1));
463 
464   // Interpret this flag early because error() depends on them.
465   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
466   checkZOptions(args);
467 
468   // Handle -help
469   if (args.hasArg(OPT_help)) {
470     printHelp();
471     return;
472   }
473 
474   // Handle -v or -version.
475   //
476   // A note about "compatible with GNU linkers" message: this is a hack for
477   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
478   // still the newest version in March 2017) or earlier to recognize LLD as
479   // a GNU compatible linker. As long as an output for the -v option
480   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
481   //
482   // This is somewhat ugly hack, but in reality, we had no choice other
483   // than doing this. Considering the very long release cycle of Libtool,
484   // it is not easy to improve it to recognize LLD as a GNU compatible
485   // linker in a timely manner. Even if we can make it, there are still a
486   // lot of "configure" scripts out there that are generated by old version
487   // of Libtool. We cannot convince every software developer to migrate to
488   // the latest version and re-generate scripts. So we have this hack.
489   if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
490     message(getLLDVersion() + " (compatible with GNU linkers)");
491 
492   if (const char *path = getReproduceOption(args)) {
493     // Note that --reproduce is a debug option so you can ignore it
494     // if you are trying to understand the whole picture of the code.
495     Expected<std::unique_ptr<TarWriter>> errOrWriter =
496         TarWriter::create(path, path::stem(path));
497     if (errOrWriter) {
498       tar = std::move(*errOrWriter);
499       tar->append("response.txt", createResponseFile(args));
500       tar->append("version.txt", getLLDVersion() + "\n");
501       StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
502       if (!ltoSampleProfile.empty())
503         readFile(ltoSampleProfile);
504     } else {
505       error("--reproduce: " + toString(errOrWriter.takeError()));
506     }
507   }
508 
509   readConfigs(args);
510 
511   // The behavior of -v or --version is a bit strange, but this is
512   // needed for compatibility with GNU linkers.
513   if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
514     return;
515   if (args.hasArg(OPT_version))
516     return;
517 
518   // Initialize time trace profiler.
519   if (config->timeTraceEnabled)
520     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
521 
522   {
523     llvm::TimeTraceScope timeScope("ExecuteLinker");
524 
525     initLLVM();
526     createFiles(args);
527     if (errorCount())
528       return;
529 
530     inferMachineType();
531     setConfigs(args);
532     checkOptions();
533     if (errorCount())
534       return;
535 
536     // The Target instance handles target-specific stuff, such as applying
537     // relocations or writing a PLT section. It also contains target-dependent
538     // values such as a default image base address.
539     target = getTarget();
540 
541     switch (config->ekind) {
542     case ELF32LEKind:
543       link<ELF32LE>(args);
544       break;
545     case ELF32BEKind:
546       link<ELF32BE>(args);
547       break;
548     case ELF64LEKind:
549       link<ELF64LE>(args);
550       break;
551     case ELF64BEKind:
552       link<ELF64BE>(args);
553       break;
554     default:
555       llvm_unreachable("unknown Config->EKind");
556     }
557   }
558 
559   if (config->timeTraceEnabled) {
560     if (auto E = timeTraceProfilerWrite(args.getLastArgValue(OPT_time_trace_file_eq).str(),
561                                         config->outputFile)) {
562       handleAllErrors(std::move(E), [&](const StringError &SE) {
563         error(SE.getMessage());
564       });
565       return;
566     }
567 
568     timeTraceProfilerCleanup();
569   }
570 }
571 
572 static std::string getRpath(opt::InputArgList &args) {
573   std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
574   return llvm::join(v.begin(), v.end(), ":");
575 }
576 
577 // Determines what we should do if there are remaining unresolved
578 // symbols after the name resolution.
579 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &args) {
580   UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
581                                               OPT_warn_unresolved_symbols, true)
582                                      ? UnresolvedPolicy::ReportError
583                                      : UnresolvedPolicy::Warn;
584 
585   // Process the last of -unresolved-symbols, -no-undefined or -z defs.
586   for (auto *arg : llvm::reverse(args)) {
587     switch (arg->getOption().getID()) {
588     case OPT_unresolved_symbols: {
589       StringRef s = arg->getValue();
590       if (s == "ignore-all" || s == "ignore-in-object-files")
591         return UnresolvedPolicy::Ignore;
592       if (s == "ignore-in-shared-libs" || s == "report-all")
593         return errorOrWarn;
594       error("unknown --unresolved-symbols value: " + s);
595       continue;
596     }
597     case OPT_no_undefined:
598       return errorOrWarn;
599     case OPT_z:
600       if (StringRef(arg->getValue()) == "defs")
601         return errorOrWarn;
602       if (StringRef(arg->getValue()) == "undefs")
603         return UnresolvedPolicy::Ignore;
604       continue;
605     }
606   }
607 
608   // -shared implies -unresolved-symbols=ignore-all because missing
609   // symbols are likely to be resolved at runtime using other DSOs.
610   if (config->shared)
611     return UnresolvedPolicy::Ignore;
612   return errorOrWarn;
613 }
614 
615 static Target2Policy getTarget2(opt::InputArgList &args) {
616   StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
617   if (s == "rel")
618     return Target2Policy::Rel;
619   if (s == "abs")
620     return Target2Policy::Abs;
621   if (s == "got-rel")
622     return Target2Policy::GotRel;
623   error("unknown --target2 option: " + s);
624   return Target2Policy::GotRel;
625 }
626 
627 static bool isOutputFormatBinary(opt::InputArgList &args) {
628   StringRef s = args.getLastArgValue(OPT_oformat, "elf");
629   if (s == "binary")
630     return true;
631   if (!s.startswith("elf"))
632     error("unknown --oformat value: " + s);
633   return false;
634 }
635 
636 static DiscardPolicy getDiscard(opt::InputArgList &args) {
637   auto *arg =
638       args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
639   if (!arg)
640     return DiscardPolicy::Default;
641   if (arg->getOption().getID() == OPT_discard_all)
642     return DiscardPolicy::All;
643   if (arg->getOption().getID() == OPT_discard_locals)
644     return DiscardPolicy::Locals;
645   return DiscardPolicy::None;
646 }
647 
648 static StringRef getDynamicLinker(opt::InputArgList &args) {
649   auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
650   if (!arg)
651     return "";
652   if (arg->getOption().getID() == OPT_no_dynamic_linker) {
653     // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
654     config->noDynamicLinker = true;
655     return "";
656   }
657   return arg->getValue();
658 }
659 
660 static ICFLevel getICF(opt::InputArgList &args) {
661   auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
662   if (!arg || arg->getOption().getID() == OPT_icf_none)
663     return ICFLevel::None;
664   if (arg->getOption().getID() == OPT_icf_safe)
665     return ICFLevel::Safe;
666   return ICFLevel::All;
667 }
668 
669 static StripPolicy getStrip(opt::InputArgList &args) {
670   if (args.hasArg(OPT_relocatable))
671     return StripPolicy::None;
672 
673   auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
674   if (!arg)
675     return StripPolicy::None;
676   if (arg->getOption().getID() == OPT_strip_all)
677     return StripPolicy::All;
678   return StripPolicy::Debug;
679 }
680 
681 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
682                                     const opt::Arg &arg) {
683   uint64_t va = 0;
684   if (s.startswith("0x"))
685     s = s.drop_front(2);
686   if (!to_integer(s, va, 16))
687     error("invalid argument: " + arg.getAsString(args));
688   return va;
689 }
690 
691 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
692   StringMap<uint64_t> ret;
693   for (auto *arg : args.filtered(OPT_section_start)) {
694     StringRef name;
695     StringRef addr;
696     std::tie(name, addr) = StringRef(arg->getValue()).split('=');
697     ret[name] = parseSectionAddress(addr, args, *arg);
698   }
699 
700   if (auto *arg = args.getLastArg(OPT_Ttext))
701     ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
702   if (auto *arg = args.getLastArg(OPT_Tdata))
703     ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
704   if (auto *arg = args.getLastArg(OPT_Tbss))
705     ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
706   return ret;
707 }
708 
709 static SortSectionPolicy getSortSection(opt::InputArgList &args) {
710   StringRef s = args.getLastArgValue(OPT_sort_section);
711   if (s == "alignment")
712     return SortSectionPolicy::Alignment;
713   if (s == "name")
714     return SortSectionPolicy::Name;
715   if (!s.empty())
716     error("unknown --sort-section rule: " + s);
717   return SortSectionPolicy::Default;
718 }
719 
720 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
721   StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
722   if (s == "warn")
723     return OrphanHandlingPolicy::Warn;
724   if (s == "error")
725     return OrphanHandlingPolicy::Error;
726   if (s != "place")
727     error("unknown --orphan-handling mode: " + s);
728   return OrphanHandlingPolicy::Place;
729 }
730 
731 // Parse --build-id or --build-id=<style>. We handle "tree" as a
732 // synonym for "sha1" because all our hash functions including
733 // -build-id=sha1 are actually tree hashes for performance reasons.
734 static std::pair<BuildIdKind, std::vector<uint8_t>>
735 getBuildId(opt::InputArgList &args) {
736   auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
737   if (!arg)
738     return {BuildIdKind::None, {}};
739 
740   if (arg->getOption().getID() == OPT_build_id)
741     return {BuildIdKind::Fast, {}};
742 
743   StringRef s = arg->getValue();
744   if (s == "fast")
745     return {BuildIdKind::Fast, {}};
746   if (s == "md5")
747     return {BuildIdKind::Md5, {}};
748   if (s == "sha1" || s == "tree")
749     return {BuildIdKind::Sha1, {}};
750   if (s == "uuid")
751     return {BuildIdKind::Uuid, {}};
752   if (s.startswith("0x"))
753     return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
754 
755   if (s != "none")
756     error("unknown --build-id style: " + s);
757   return {BuildIdKind::None, {}};
758 }
759 
760 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
761   StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
762   if (s == "android")
763     return {true, false};
764   if (s == "relr")
765     return {false, true};
766   if (s == "android+relr")
767     return {true, true};
768 
769   if (s != "none")
770     error("unknown -pack-dyn-relocs format: " + s);
771   return {false, false};
772 }
773 
774 static void readCallGraph(MemoryBufferRef mb) {
775   // Build a map from symbol name to section
776   DenseMap<StringRef, Symbol *> map;
777   for (InputFile *file : objectFiles)
778     for (Symbol *sym : file->getSymbols())
779       map[sym->getName()] = sym;
780 
781   auto findSection = [&](StringRef name) -> InputSectionBase * {
782     Symbol *sym = map.lookup(name);
783     if (!sym) {
784       if (config->warnSymbolOrdering)
785         warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
786       return nullptr;
787     }
788     maybeWarnUnorderableSymbol(sym);
789 
790     if (Defined *dr = dyn_cast_or_null<Defined>(sym))
791       return dyn_cast_or_null<InputSectionBase>(dr->section);
792     return nullptr;
793   };
794 
795   for (StringRef line : args::getLines(mb)) {
796     SmallVector<StringRef, 3> fields;
797     line.split(fields, ' ');
798     uint64_t count;
799 
800     if (fields.size() != 3 || !to_integer(fields[2], count)) {
801       error(mb.getBufferIdentifier() + ": parse error");
802       return;
803     }
804 
805     if (InputSectionBase *from = findSection(fields[0]))
806       if (InputSectionBase *to = findSection(fields[1]))
807         config->callGraphProfile[std::make_pair(from, to)] += count;
808   }
809 }
810 
811 template <class ELFT> static void readCallGraphsFromObjectFiles() {
812   for (auto file : objectFiles) {
813     auto *obj = cast<ObjFile<ELFT>>(file);
814 
815     for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
816       auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
817       auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
818       if (!fromSym || !toSym)
819         continue;
820 
821       auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
822       auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
823       if (from && to)
824         config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
825     }
826   }
827 }
828 
829 static bool getCompressDebugSections(opt::InputArgList &args) {
830   StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
831   if (s == "none")
832     return false;
833   if (s != "zlib")
834     error("unknown --compress-debug-sections value: " + s);
835   if (!zlib::isAvailable())
836     error("--compress-debug-sections: zlib is not available");
837   return true;
838 }
839 
840 static StringRef getAliasSpelling(opt::Arg *arg) {
841   if (const opt::Arg *alias = arg->getAlias())
842     return alias->getSpelling();
843   return arg->getSpelling();
844 }
845 
846 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
847                                                         unsigned id) {
848   auto *arg = args.getLastArg(id);
849   if (!arg)
850     return {"", ""};
851 
852   StringRef s = arg->getValue();
853   std::pair<StringRef, StringRef> ret = s.split(';');
854   if (ret.second.empty())
855     error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
856   return ret;
857 }
858 
859 // Parse the symbol ordering file and warn for any duplicate entries.
860 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
861   SetVector<StringRef> names;
862   for (StringRef s : args::getLines(mb))
863     if (!names.insert(s) && config->warnSymbolOrdering)
864       warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
865 
866   return names.takeVector();
867 }
868 
869 static bool getIsRela(opt::InputArgList &args) {
870   // If -z rel or -z rela is specified, use the last option.
871   for (auto *arg : args.filtered_reverse(OPT_z)) {
872     StringRef s(arg->getValue());
873     if (s == "rel")
874       return false;
875     if (s == "rela")
876       return true;
877   }
878 
879   // Otherwise use the psABI defined relocation entry format.
880   uint16_t m = config->emachine;
881   return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC ||
882          m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64;
883 }
884 
885 static void parseClangOption(StringRef opt, const Twine &msg) {
886   std::string err;
887   raw_string_ostream os(err);
888 
889   const char *argv[] = {config->progName.data(), opt.data()};
890   if (cl::ParseCommandLineOptions(2, argv, "", &os))
891     return;
892   os.flush();
893   error(msg + ": " + StringRef(err).trim());
894 }
895 
896 // Initializes Config members by the command line options.
897 static void readConfigs(opt::InputArgList &args) {
898   errorHandler().verbose = args.hasArg(OPT_verbose);
899   errorHandler().fatalWarnings =
900       args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
901   errorHandler().vsDiagnostics =
902       args.hasArg(OPT_visual_studio_diagnostics_format, false);
903 
904   config->allowMultipleDefinition =
905       args.hasFlag(OPT_allow_multiple_definition,
906                    OPT_no_allow_multiple_definition, false) ||
907       hasZOption(args, "muldefs");
908   config->allowShlibUndefined =
909       args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined,
910                    args.hasArg(OPT_shared));
911   config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
912   config->bsymbolic = args.hasArg(OPT_Bsymbolic);
913   config->bsymbolicFunctions = args.hasArg(OPT_Bsymbolic_functions);
914   config->checkSections =
915       args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
916   config->chroot = args.getLastArgValue(OPT_chroot);
917   config->compressDebugSections = getCompressDebugSections(args);
918   config->cref = args.hasFlag(OPT_cref, OPT_no_cref, false);
919   config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
920                                       !args.hasArg(OPT_relocatable));
921   config->optimizeBBJumps =
922       args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
923   config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
924   config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
925   config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
926   config->disableVerify = args.hasArg(OPT_disable_verify);
927   config->discard = getDiscard(args);
928   config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
929   config->dynamicLinker = getDynamicLinker(args);
930   config->ehFrameHdr =
931       args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
932   config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
933   config->emitRelocs = args.hasArg(OPT_emit_relocs);
934   config->callGraphProfileSort = args.hasFlag(
935       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
936   config->enableNewDtags =
937       args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
938   config->entry = args.getLastArgValue(OPT_entry);
939   config->executeOnly =
940       args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
941   config->exportDynamic =
942       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
943   config->filterList = args::getStrings(args, OPT_filter);
944   config->fini = args.getLastArgValue(OPT_fini, "_fini");
945   config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
946                                      !args.hasArg(OPT_relocatable);
947   config->fixCortexA8 =
948       args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
949   config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
950   config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
951   config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
952   config->icf = getICF(args);
953   config->ignoreDataAddressEquality =
954       args.hasArg(OPT_ignore_data_address_equality);
955   config->ignoreFunctionAddressEquality =
956       args.hasArg(OPT_ignore_function_address_equality);
957   config->init = args.getLastArgValue(OPT_init, "_init");
958   config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
959   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
960   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
961   config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
962   config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
963   config->ltoNewPassManager = args.hasArg(OPT_lto_new_pass_manager);
964   config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
965   config->ltoWholeProgramVisibility =
966       args.hasArg(OPT_lto_whole_program_visibility);
967   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
968   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
969   config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
970   config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
971   config->ltoBasicBlockSections =
972       args.getLastArgValue(OPT_lto_basic_block_sections);
973   config->ltoUniqueBasicBlockSectionNames =
974       args.hasFlag(OPT_lto_unique_basic_block_section_names,
975                    OPT_no_lto_unique_basic_block_section_names, false);
976   config->mapFile = args.getLastArgValue(OPT_Map);
977   config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
978   config->mergeArmExidx =
979       args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
980   config->mmapOutputFile =
981       args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
982   config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
983   config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
984   config->nostdlib = args.hasArg(OPT_nostdlib);
985   config->oFormatBinary = isOutputFormatBinary(args);
986   config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
987   config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
988   config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
989   config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
990   config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
991   config->optimize = args::getInteger(args, OPT_O, 1);
992   config->orphanHandling = getOrphanHandling(args);
993   config->outputFile = args.getLastArgValue(OPT_o);
994   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
995   config->printIcfSections =
996       args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
997   config->printGcSections =
998       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
999   config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
1000   config->printSymbolOrder =
1001       args.getLastArgValue(OPT_print_symbol_order);
1002   config->rpath = getRpath(args);
1003   config->relocatable = args.hasArg(OPT_relocatable);
1004   config->saveTemps = args.hasArg(OPT_save_temps);
1005   if (args.hasArg(OPT_shuffle_sections))
1006     config->shuffleSectionSeed = args::getInteger(args, OPT_shuffle_sections, 0);
1007   config->searchPaths = args::getStrings(args, OPT_library_path);
1008   config->sectionStartMap = getSectionStartMap(args);
1009   config->shared = args.hasArg(OPT_shared);
1010   config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
1011   config->soName = args.getLastArgValue(OPT_soname);
1012   config->sortSection = getSortSection(args);
1013   config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
1014   config->strip = getStrip(args);
1015   config->sysroot = args.getLastArgValue(OPT_sysroot);
1016   config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
1017   config->target2 = getTarget2(args);
1018   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
1019   config->thinLTOCachePolicy = CHECK(
1020       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
1021       "--thinlto-cache-policy: invalid cache policy");
1022   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1023   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1024                              args.hasArg(OPT_thinlto_index_only_eq);
1025   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1026   config->thinLTOObjectSuffixReplace =
1027       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
1028   config->thinLTOPrefixReplace =
1029       getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
1030   config->thinLTOModulesToCompile =
1031       args::getStrings(args, OPT_thinlto_single_module_eq);
1032   config->timeTraceEnabled = args.hasArg(OPT_time_trace);
1033   config->timeTraceGranularity =
1034       args::getInteger(args, OPT_time_trace_granularity, 500);
1035   config->trace = args.hasArg(OPT_trace);
1036   config->undefined = args::getStrings(args, OPT_undefined);
1037   config->undefinedVersion =
1038       args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
1039   config->unique = args.hasArg(OPT_unique);
1040   config->useAndroidRelrTags = args.hasFlag(
1041       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
1042   config->unresolvedSymbols = getUnresolvedSymbolPolicy(args);
1043   config->warnBackrefs =
1044       args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
1045   config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
1046   config->warnIfuncTextrel =
1047       args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
1048   config->warnSymbolOrdering =
1049       args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1050   config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
1051   config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
1052   config->zForceBti = hasZOption(args, "force-bti");
1053   config->zForceIbt = hasZOption(args, "force-ibt");
1054   config->zGlobal = hasZOption(args, "global");
1055   config->zGnustack = getZGnuStack(args);
1056   config->zHazardplt = hasZOption(args, "hazardplt");
1057   config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
1058   config->zInitfirst = hasZOption(args, "initfirst");
1059   config->zInterpose = hasZOption(args, "interpose");
1060   config->zKeepTextSectionPrefix = getZFlag(
1061       args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
1062   config->zNodefaultlib = hasZOption(args, "nodefaultlib");
1063   config->zNodelete = hasZOption(args, "nodelete");
1064   config->zNodlopen = hasZOption(args, "nodlopen");
1065   config->zNow = getZFlag(args, "now", "lazy", false);
1066   config->zOrigin = hasZOption(args, "origin");
1067   config->zPacPlt = hasZOption(args, "pac-plt");
1068   config->zRelro = getZFlag(args, "relro", "norelro", true);
1069   config->zRetpolineplt = hasZOption(args, "retpolineplt");
1070   config->zRodynamic = hasZOption(args, "rodynamic");
1071   config->zSeparate = getZSeparate(args);
1072   config->zShstk = hasZOption(args, "shstk");
1073   config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1074   config->zStartStopVisibility = getZStartStopVisibility(args);
1075   config->zText = getZFlag(args, "text", "notext", true);
1076   config->zWxneeded = hasZOption(args, "wxneeded");
1077 
1078   for (opt::Arg *arg : args.filtered(OPT_z)) {
1079     std::pair<StringRef, StringRef> option =
1080         StringRef(arg->getValue()).split('=');
1081     if (option.first != "dead-reloc-in-nonalloc")
1082       continue;
1083     constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
1084     std::pair<StringRef, StringRef> kv = option.second.split('=');
1085     if (kv.first.empty() || kv.second.empty()) {
1086       error(errPrefix + "expected <section_glob>=<value>");
1087       continue;
1088     }
1089     uint64_t v;
1090     if (!to_integer(kv.second, v))
1091       error(errPrefix + "expected a non-negative integer, but got '" +
1092             kv.second + "'");
1093     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1094       config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
1095     else
1096       error(errPrefix + toString(pat.takeError()));
1097   }
1098 
1099   // Parse LTO options.
1100   if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
1101     parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
1102                      arg->getSpelling());
1103 
1104   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
1105     parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
1106 
1107   // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1108   // relative path. Just ignore. If not ended with "lto-wrapper", consider it an
1109   // unsupported LLVMgold.so option and error.
1110   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq))
1111     if (!StringRef(arg->getValue()).endswith("lto-wrapper"))
1112       error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
1113             "'");
1114 
1115   // Parse -mllvm options.
1116   for (auto *arg : args.filtered(OPT_mllvm))
1117     parseClangOption(arg->getValue(), arg->getSpelling());
1118 
1119   // --threads= takes a positive integer and provides the default value for
1120   // --thinlto-jobs=.
1121   if (auto *arg = args.getLastArg(OPT_threads)) {
1122     StringRef v(arg->getValue());
1123     unsigned threads = 0;
1124     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1125       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1126             arg->getValue() + "'");
1127     parallel::strategy = hardware_concurrency(threads);
1128     config->thinLTOJobs = v;
1129   }
1130   if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
1131     config->thinLTOJobs = arg->getValue();
1132 
1133   if (config->ltoo > 3)
1134     error("invalid optimization level for LTO: " + Twine(config->ltoo));
1135   if (config->ltoPartitions == 0)
1136     error("--lto-partitions: number of threads must be > 0");
1137   if (!get_threadpool_strategy(config->thinLTOJobs))
1138     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1139 
1140   if (config->splitStackAdjustSize < 0)
1141     error("--split-stack-adjust-size: size must be >= 0");
1142 
1143   // The text segment is traditionally the first segment, whose address equals
1144   // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1145   // is an old-fashioned option that does not play well with lld's layout.
1146   // Suggest --image-base as a likely alternative.
1147   if (args.hasArg(OPT_Ttext_segment))
1148     error("-Ttext-segment is not supported. Use --image-base if you "
1149           "intend to set the base address");
1150 
1151   // Parse ELF{32,64}{LE,BE} and CPU type.
1152   if (auto *arg = args.getLastArg(OPT_m)) {
1153     StringRef s = arg->getValue();
1154     std::tie(config->ekind, config->emachine, config->osabi) =
1155         parseEmulation(s);
1156     config->mipsN32Abi =
1157         (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
1158     config->emulation = s;
1159   }
1160 
1161   // Parse -hash-style={sysv,gnu,both}.
1162   if (auto *arg = args.getLastArg(OPT_hash_style)) {
1163     StringRef s = arg->getValue();
1164     if (s == "sysv")
1165       config->sysvHash = true;
1166     else if (s == "gnu")
1167       config->gnuHash = true;
1168     else if (s == "both")
1169       config->sysvHash = config->gnuHash = true;
1170     else
1171       error("unknown -hash-style: " + s);
1172   }
1173 
1174   if (args.hasArg(OPT_print_map))
1175     config->mapFile = "-";
1176 
1177   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1178   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1179   // it.
1180   if (config->nmagic || config->omagic)
1181     config->zRelro = false;
1182 
1183   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1184 
1185   std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1186       getPackDynRelocs(args);
1187 
1188   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1189     if (args.hasArg(OPT_call_graph_ordering_file))
1190       error("--symbol-ordering-file and --call-graph-order-file "
1191             "may not be used together");
1192     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1193       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1194       // Also need to disable CallGraphProfileSort to prevent
1195       // LLD order symbols with CGProfile
1196       config->callGraphProfileSort = false;
1197     }
1198   }
1199 
1200   assert(config->versionDefinitions.empty());
1201   config->versionDefinitions.push_back({"local", (uint16_t)VER_NDX_LOCAL, {}});
1202   config->versionDefinitions.push_back(
1203       {"global", (uint16_t)VER_NDX_GLOBAL, {}});
1204 
1205   // If --retain-symbol-file is used, we'll keep only the symbols listed in
1206   // the file and discard all others.
1207   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1208     config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(
1209         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1210     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1211       for (StringRef s : args::getLines(*buffer))
1212         config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back(
1213             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1214   }
1215 
1216   for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
1217     StringRef pattern(arg->getValue());
1218     if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
1219       config->warnBackrefsExclude.push_back(std::move(*pat));
1220     else
1221       error(arg->getSpelling() + ": " + toString(pat.takeError()));
1222   }
1223 
1224   // When producing an executable, --dynamic-list specifies non-local defined
1225   // symbols whith are required to be exported. When producing a shared object,
1226   // symbols not specified by --dynamic-list are non-preemptible.
1227   config->symbolic =
1228       args.hasArg(OPT_Bsymbolic) || args.hasArg(OPT_dynamic_list);
1229   for (auto *arg : args.filtered(OPT_dynamic_list))
1230     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1231       readDynamicList(*buffer);
1232 
1233   // --export-dynamic-symbol specifies additional --dynamic-list symbols if any
1234   // other option expresses a symbolic intention: -no-pie, -pie, -Bsymbolic,
1235   // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1236   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1237     config->dynamicList.push_back(
1238         {arg->getValue(), /*isExternCpp=*/false,
1239          /*hasWildcard=*/hasWildcard(arg->getValue())});
1240 
1241   for (auto *arg : args.filtered(OPT_version_script))
1242     if (Optional<std::string> path = searchScript(arg->getValue())) {
1243       if (Optional<MemoryBufferRef> buffer = readFile(*path))
1244         readVersionScript(*buffer);
1245     } else {
1246       error(Twine("cannot find version script ") + arg->getValue());
1247     }
1248 }
1249 
1250 // Some Config members do not directly correspond to any particular
1251 // command line options, but computed based on other Config values.
1252 // This function initialize such members. See Config.h for the details
1253 // of these values.
1254 static void setConfigs(opt::InputArgList &args) {
1255   ELFKind k = config->ekind;
1256   uint16_t m = config->emachine;
1257 
1258   config->copyRelocs = (config->relocatable || config->emitRelocs);
1259   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1260   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1261   config->endianness = config->isLE ? endianness::little : endianness::big;
1262   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1263   config->isPic = config->pie || config->shared;
1264   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1265   config->wordsize = config->is64 ? 8 : 4;
1266 
1267   // ELF defines two different ways to store relocation addends as shown below:
1268   //
1269   //  Rel: Addends are stored to the location where relocations are applied. It
1270   //  cannot pack the full range of addend values for all relocation types, but
1271   //  this only affects relocation types that we don't support emitting as
1272   //  dynamic relocations (see getDynRel).
1273   //  Rela: Addends are stored as part of relocation entry.
1274   //
1275   // In other words, Rela makes it easy to read addends at the price of extra
1276   // 4 or 8 byte for each relocation entry.
1277   //
1278   // We pick the format for dynamic relocations according to the psABI for each
1279   // processor, but a contrary choice can be made if the dynamic loader
1280   // supports.
1281   config->isRela = getIsRela(args);
1282 
1283   // If the output uses REL relocations we must store the dynamic relocation
1284   // addends to the output sections. We also store addends for RELA relocations
1285   // if --apply-dynamic-relocs is used.
1286   // We default to not writing the addends when using RELA relocations since
1287   // any standard conforming tool can find it in r_addend.
1288   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1289                                       OPT_no_apply_dynamic_relocs, false) ||
1290                          !config->isRela;
1291 
1292   config->tocOptimize =
1293       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1294   config->pcRelOptimize =
1295       args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
1296 }
1297 
1298 // Returns a value of "-format" option.
1299 static bool isFormatBinary(StringRef s) {
1300   if (s == "binary")
1301     return true;
1302   if (s == "elf" || s == "default")
1303     return false;
1304   error("unknown -format value: " + s +
1305         " (supported formats: elf, default, binary)");
1306   return false;
1307 }
1308 
1309 void LinkerDriver::createFiles(opt::InputArgList &args) {
1310   // For --{push,pop}-state.
1311   std::vector<std::tuple<bool, bool, bool>> stack;
1312 
1313   // Iterate over argv to process input files and positional arguments.
1314   InputFile::isInGroup = false;
1315   for (auto *arg : args) {
1316     switch (arg->getOption().getID()) {
1317     case OPT_library:
1318       addLibrary(arg->getValue());
1319       break;
1320     case OPT_INPUT:
1321       addFile(arg->getValue(), /*withLOption=*/false);
1322       break;
1323     case OPT_defsym: {
1324       StringRef from;
1325       StringRef to;
1326       std::tie(from, to) = StringRef(arg->getValue()).split('=');
1327       if (from.empty() || to.empty())
1328         error("-defsym: syntax error: " + StringRef(arg->getValue()));
1329       else
1330         readDefsym(from, MemoryBufferRef(to, "-defsym"));
1331       break;
1332     }
1333     case OPT_script:
1334       if (Optional<std::string> path = searchScript(arg->getValue())) {
1335         if (Optional<MemoryBufferRef> mb = readFile(*path))
1336           readLinkerScript(*mb);
1337         break;
1338       }
1339       error(Twine("cannot find linker script ") + arg->getValue());
1340       break;
1341     case OPT_as_needed:
1342       config->asNeeded = true;
1343       break;
1344     case OPT_format:
1345       config->formatBinary = isFormatBinary(arg->getValue());
1346       break;
1347     case OPT_no_as_needed:
1348       config->asNeeded = false;
1349       break;
1350     case OPT_Bstatic:
1351     case OPT_omagic:
1352     case OPT_nmagic:
1353       config->isStatic = true;
1354       break;
1355     case OPT_Bdynamic:
1356       config->isStatic = false;
1357       break;
1358     case OPT_whole_archive:
1359       inWholeArchive = true;
1360       break;
1361     case OPT_no_whole_archive:
1362       inWholeArchive = false;
1363       break;
1364     case OPT_just_symbols:
1365       if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1366         files.push_back(createObjectFile(*mb));
1367         files.back()->justSymbols = true;
1368       }
1369       break;
1370     case OPT_start_group:
1371       if (InputFile::isInGroup)
1372         error("nested --start-group");
1373       InputFile::isInGroup = true;
1374       break;
1375     case OPT_end_group:
1376       if (!InputFile::isInGroup)
1377         error("stray --end-group");
1378       InputFile::isInGroup = false;
1379       ++InputFile::nextGroupId;
1380       break;
1381     case OPT_start_lib:
1382       if (inLib)
1383         error("nested --start-lib");
1384       if (InputFile::isInGroup)
1385         error("may not nest --start-lib in --start-group");
1386       inLib = true;
1387       InputFile::isInGroup = true;
1388       break;
1389     case OPT_end_lib:
1390       if (!inLib)
1391         error("stray --end-lib");
1392       inLib = false;
1393       InputFile::isInGroup = false;
1394       ++InputFile::nextGroupId;
1395       break;
1396     case OPT_push_state:
1397       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1398       break;
1399     case OPT_pop_state:
1400       if (stack.empty()) {
1401         error("unbalanced --push-state/--pop-state");
1402         break;
1403       }
1404       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1405       stack.pop_back();
1406       break;
1407     }
1408   }
1409 
1410   if (files.empty() && errorCount() == 0)
1411     error("no input files");
1412 }
1413 
1414 // If -m <machine_type> was not given, infer it from object files.
1415 void LinkerDriver::inferMachineType() {
1416   if (config->ekind != ELFNoneKind)
1417     return;
1418 
1419   for (InputFile *f : files) {
1420     if (f->ekind == ELFNoneKind)
1421       continue;
1422     config->ekind = f->ekind;
1423     config->emachine = f->emachine;
1424     config->osabi = f->osabi;
1425     config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1426     return;
1427   }
1428   error("target emulation unknown: -m or at least one .o file required");
1429 }
1430 
1431 // Parse -z max-page-size=<value>. The default value is defined by
1432 // each target.
1433 static uint64_t getMaxPageSize(opt::InputArgList &args) {
1434   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1435                                        target->defaultMaxPageSize);
1436   if (!isPowerOf2_64(val))
1437     error("max-page-size: value isn't a power of 2");
1438   if (config->nmagic || config->omagic) {
1439     if (val != target->defaultMaxPageSize)
1440       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1441     return 1;
1442   }
1443   return val;
1444 }
1445 
1446 // Parse -z common-page-size=<value>. The default value is defined by
1447 // each target.
1448 static uint64_t getCommonPageSize(opt::InputArgList &args) {
1449   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1450                                        target->defaultCommonPageSize);
1451   if (!isPowerOf2_64(val))
1452     error("common-page-size: value isn't a power of 2");
1453   if (config->nmagic || config->omagic) {
1454     if (val != target->defaultCommonPageSize)
1455       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1456     return 1;
1457   }
1458   // commonPageSize can't be larger than maxPageSize.
1459   if (val > config->maxPageSize)
1460     val = config->maxPageSize;
1461   return val;
1462 }
1463 
1464 // Parses -image-base option.
1465 static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1466   // Because we are using "Config->maxPageSize" here, this function has to be
1467   // called after the variable is initialized.
1468   auto *arg = args.getLastArg(OPT_image_base);
1469   if (!arg)
1470     return None;
1471 
1472   StringRef s = arg->getValue();
1473   uint64_t v;
1474   if (!to_integer(s, v)) {
1475     error("-image-base: number expected, but got " + s);
1476     return 0;
1477   }
1478   if ((v % config->maxPageSize) != 0)
1479     warn("-image-base: address isn't multiple of page size: " + s);
1480   return v;
1481 }
1482 
1483 // Parses `--exclude-libs=lib,lib,...`.
1484 // The library names may be delimited by commas or colons.
1485 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1486   DenseSet<StringRef> ret;
1487   for (auto *arg : args.filtered(OPT_exclude_libs)) {
1488     StringRef s = arg->getValue();
1489     for (;;) {
1490       size_t pos = s.find_first_of(",:");
1491       if (pos == StringRef::npos)
1492         break;
1493       ret.insert(s.substr(0, pos));
1494       s = s.substr(pos + 1);
1495     }
1496     ret.insert(s);
1497   }
1498   return ret;
1499 }
1500 
1501 // Handles the -exclude-libs option. If a static library file is specified
1502 // by the -exclude-libs option, all public symbols from the archive become
1503 // private unless otherwise specified by version scripts or something.
1504 // A special library name "ALL" means all archive files.
1505 //
1506 // This is not a popular option, but some programs such as bionic libc use it.
1507 static void excludeLibs(opt::InputArgList &args) {
1508   DenseSet<StringRef> libs = getExcludeLibs(args);
1509   bool all = libs.count("ALL");
1510 
1511   auto visit = [&](InputFile *file) {
1512     if (!file->archiveName.empty())
1513       if (all || libs.count(path::filename(file->archiveName)))
1514         for (Symbol *sym : file->getSymbols())
1515           if (!sym->isUndefined() && !sym->isLocal() && sym->file == file)
1516             sym->versionId = VER_NDX_LOCAL;
1517   };
1518 
1519   for (InputFile *file : objectFiles)
1520     visit(file);
1521 
1522   for (BitcodeFile *file : bitcodeFiles)
1523     visit(file);
1524 }
1525 
1526 // Force Sym to be entered in the output.
1527 static void handleUndefined(Symbol *sym) {
1528   // Since a symbol may not be used inside the program, LTO may
1529   // eliminate it. Mark the symbol as "used" to prevent it.
1530   sym->isUsedInRegularObj = true;
1531 
1532   if (sym->isLazy())
1533     sym->fetch();
1534 }
1535 
1536 // As an extension to GNU linkers, lld supports a variant of `-u`
1537 // which accepts wildcard patterns. All symbols that match a given
1538 // pattern are handled as if they were given by `-u`.
1539 static void handleUndefinedGlob(StringRef arg) {
1540   Expected<GlobPattern> pat = GlobPattern::create(arg);
1541   if (!pat) {
1542     error("--undefined-glob: " + toString(pat.takeError()));
1543     return;
1544   }
1545 
1546   std::vector<Symbol *> syms;
1547   for (Symbol *sym : symtab->symbols()) {
1548     // Calling Sym->fetch() from here is not safe because it may
1549     // add new symbols to the symbol table, invalidating the
1550     // current iterator. So we just keep a note.
1551     if (pat->match(sym->getName()))
1552       syms.push_back(sym);
1553   }
1554 
1555   for (Symbol *sym : syms)
1556     handleUndefined(sym);
1557 }
1558 
1559 static void handleLibcall(StringRef name) {
1560   Symbol *sym = symtab->find(name);
1561   if (!sym || !sym->isLazy())
1562     return;
1563 
1564   MemoryBufferRef mb;
1565   if (auto *lo = dyn_cast<LazyObject>(sym))
1566     mb = lo->file->mb;
1567   else
1568     mb = cast<LazyArchive>(sym)->getMemberBuffer();
1569 
1570   if (isBitcode(mb))
1571     sym->fetch();
1572 }
1573 
1574 // Handle --dependency-file=<path>. If that option is given, lld creates a
1575 // file at a given path with the following contents:
1576 //
1577 //   <output-file>: <input-file> ...
1578 //
1579 //   <input-file>:
1580 //
1581 // where <output-file> is a pathname of an output file and <input-file>
1582 // ... is a list of pathnames of all input files. `make` command can read a
1583 // file in the above format and interpret it as a dependency info. We write
1584 // phony targets for every <input-file> to avoid an error when that file is
1585 // removed.
1586 //
1587 // This option is useful if you want to make your final executable to depend
1588 // on all input files including system libraries. Here is why.
1589 //
1590 // When you write a Makefile, you usually write it so that the final
1591 // executable depends on all user-generated object files. Normally, you
1592 // don't make your executable to depend on system libraries (such as libc)
1593 // because you don't know the exact paths of libraries, even though system
1594 // libraries that are linked to your executable statically are technically a
1595 // part of your program. By using --dependency-file option, you can make
1596 // lld to dump dependency info so that you can maintain exact dependencies
1597 // easily.
1598 static void writeDependencyFile() {
1599   std::error_code ec;
1600   raw_fd_ostream os(config->dependencyFile, ec, sys::fs::F_None);
1601   if (ec) {
1602     error("cannot open " + config->dependencyFile + ": " + ec.message());
1603     return;
1604   }
1605 
1606   // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
1607   // * A space is escaped by a backslash which itself must be escaped.
1608   // * A hash sign is escaped by a single backslash.
1609   // * $ is escapes as $$.
1610   auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
1611     llvm::SmallString<256> nativePath;
1612     llvm::sys::path::native(filename.str(), nativePath);
1613     llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
1614     for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
1615       if (nativePath[i] == '#') {
1616         os << '\\';
1617       } else if (nativePath[i] == ' ') {
1618         os << '\\';
1619         unsigned j = i;
1620         while (j > 0 && nativePath[--j] == '\\')
1621           os << '\\';
1622       } else if (nativePath[i] == '$') {
1623         os << '$';
1624       }
1625       os << nativePath[i];
1626     }
1627   };
1628 
1629   os << config->outputFile << ":";
1630   for (StringRef path : config->dependencyFiles) {
1631     os << " \\\n ";
1632     printFilename(os, path);
1633   }
1634   os << "\n";
1635 
1636   for (StringRef path : config->dependencyFiles) {
1637     os << "\n";
1638     printFilename(os, path);
1639     os << ":\n";
1640   }
1641 }
1642 
1643 // Replaces common symbols with defined symbols reside in .bss sections.
1644 // This function is called after all symbol names are resolved. As a
1645 // result, the passes after the symbol resolution won't see any
1646 // symbols of type CommonSymbol.
1647 static void replaceCommonSymbols() {
1648   for (Symbol *sym : symtab->symbols()) {
1649     auto *s = dyn_cast<CommonSymbol>(sym);
1650     if (!s)
1651       continue;
1652 
1653     auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1654     bss->file = s->file;
1655     bss->markDead();
1656     inputSections.push_back(bss);
1657     s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
1658                        /*value=*/0, s->size, bss});
1659   }
1660 }
1661 
1662 // If all references to a DSO happen to be weak, the DSO is not added
1663 // to DT_NEEDED. If that happens, we need to eliminate shared symbols
1664 // created from the DSO. Otherwise, they become dangling references
1665 // that point to a non-existent DSO.
1666 static void demoteSharedSymbols() {
1667   for (Symbol *sym : symtab->symbols()) {
1668     auto *s = dyn_cast<SharedSymbol>(sym);
1669     if (!s || s->getFile().isNeeded)
1670       continue;
1671 
1672     bool used = s->used;
1673     s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type});
1674     s->used = used;
1675   }
1676 }
1677 
1678 // The section referred to by `s` is considered address-significant. Set the
1679 // keepUnique flag on the section if appropriate.
1680 static void markAddrsig(Symbol *s) {
1681   if (auto *d = dyn_cast_or_null<Defined>(s))
1682     if (d->section)
1683       // We don't need to keep text sections unique under --icf=all even if they
1684       // are address-significant.
1685       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
1686         d->section->keepUnique = true;
1687 }
1688 
1689 // Record sections that define symbols mentioned in --keep-unique <symbol>
1690 // and symbols referred to by address-significance tables. These sections are
1691 // ineligible for ICF.
1692 template <class ELFT>
1693 static void findKeepUniqueSections(opt::InputArgList &args) {
1694   for (auto *arg : args.filtered(OPT_keep_unique)) {
1695     StringRef name = arg->getValue();
1696     auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1697     if (!d || !d->section) {
1698       warn("could not find symbol " + name + " to keep unique");
1699       continue;
1700     }
1701     d->section->keepUnique = true;
1702   }
1703 
1704   // --icf=all --ignore-data-address-equality means that we can ignore
1705   // the dynsym and address-significance tables entirely.
1706   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
1707     return;
1708 
1709   // Symbols in the dynsym could be address-significant in other executables
1710   // or DSOs, so we conservatively mark them as address-significant.
1711   for (Symbol *sym : symtab->symbols())
1712     if (sym->includeInDynsym())
1713       markAddrsig(sym);
1714 
1715   // Visit the address-significance table in each object file and mark each
1716   // referenced symbol as address-significant.
1717   for (InputFile *f : objectFiles) {
1718     auto *obj = cast<ObjFile<ELFT>>(f);
1719     ArrayRef<Symbol *> syms = obj->getSymbols();
1720     if (obj->addrsigSec) {
1721       ArrayRef<uint8_t> contents =
1722           check(obj->getObj().getSectionContents(*obj->addrsigSec));
1723       const uint8_t *cur = contents.begin();
1724       while (cur != contents.end()) {
1725         unsigned size;
1726         const char *err;
1727         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1728         if (err)
1729           fatal(toString(f) + ": could not decode addrsig section: " + err);
1730         markAddrsig(syms[symIndex]);
1731         cur += size;
1732       }
1733     } else {
1734       // If an object file does not have an address-significance table,
1735       // conservatively mark all of its symbols as address-significant.
1736       for (Symbol *s : syms)
1737         markAddrsig(s);
1738     }
1739   }
1740 }
1741 
1742 // This function reads a symbol partition specification section. These sections
1743 // are used to control which partition a symbol is allocated to. See
1744 // https://lld.llvm.org/Partitions.html for more details on partitions.
1745 template <typename ELFT>
1746 static void readSymbolPartitionSection(InputSectionBase *s) {
1747   // Read the relocation that refers to the partition's entry point symbol.
1748   Symbol *sym;
1749   if (s->areRelocsRela)
1750     sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]);
1751   else
1752     sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]);
1753   if (!isa<Defined>(sym) || !sym->includeInDynsym())
1754     return;
1755 
1756   StringRef partName = reinterpret_cast<const char *>(s->data().data());
1757   for (Partition &part : partitions) {
1758     if (part.name == partName) {
1759       sym->partition = part.getNumber();
1760       return;
1761     }
1762   }
1763 
1764   // Forbid partitions from being used on incompatible targets, and forbid them
1765   // from being used together with various linker features that assume a single
1766   // set of output sections.
1767   if (script->hasSectionsCommand)
1768     error(toString(s->file) +
1769           ": partitions cannot be used with the SECTIONS command");
1770   if (script->hasPhdrsCommands())
1771     error(toString(s->file) +
1772           ": partitions cannot be used with the PHDRS command");
1773   if (!config->sectionStartMap.empty())
1774     error(toString(s->file) + ": partitions cannot be used with "
1775                               "--section-start, -Ttext, -Tdata or -Tbss");
1776   if (config->emachine == EM_MIPS)
1777     error(toString(s->file) + ": partitions cannot be used on this target");
1778 
1779   // Impose a limit of no more than 254 partitions. This limit comes from the
1780   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1781   // the amount of space devoted to the partition number in RankFlags.
1782   if (partitions.size() == 254)
1783     fatal("may not have more than 254 partitions");
1784 
1785   partitions.emplace_back();
1786   Partition &newPart = partitions.back();
1787   newPart.name = partName;
1788   sym->partition = newPart.getNumber();
1789 }
1790 
1791 static Symbol *addUndefined(StringRef name) {
1792   return symtab->addSymbol(
1793       Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
1794 }
1795 
1796 static Symbol *addUnusedUndefined(StringRef name) {
1797   Undefined sym{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0};
1798   sym.isUsedInRegularObj = false;
1799   return symtab->addSymbol(sym);
1800 }
1801 
1802 // This function is where all the optimizations of link-time
1803 // optimization takes place. When LTO is in use, some input files are
1804 // not in native object file format but in the LLVM bitcode format.
1805 // This function compiles bitcode files into a few big native files
1806 // using LLVM functions and replaces bitcode symbols with the results.
1807 // Because all bitcode files that the program consists of are passed to
1808 // the compiler at once, it can do a whole-program optimization.
1809 template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1810   llvm::TimeTraceScope timeScope("LTO");
1811   // Compile bitcode files and replace bitcode symbols.
1812   lto.reset(new BitcodeCompiler);
1813   for (BitcodeFile *file : bitcodeFiles)
1814     lto->add(*file);
1815 
1816   for (InputFile *file : lto->compile()) {
1817     auto *obj = cast<ObjFile<ELFT>>(file);
1818     obj->parse(/*ignoreComdats=*/true);
1819 
1820     // Parse '@' in symbol names for non-relocatable output.
1821     if (!config->relocatable)
1822       for (Symbol *sym : obj->getGlobalSymbols())
1823         sym->parseSymbolVersion();
1824     objectFiles.push_back(file);
1825   }
1826 }
1827 
1828 // The --wrap option is a feature to rename symbols so that you can write
1829 // wrappers for existing functions. If you pass `-wrap=foo`, all
1830 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1831 // expected to write `wrap_foo` function as a wrapper). The original
1832 // symbol becomes accessible as `real_foo`, so you can call that from your
1833 // wrapper.
1834 //
1835 // This data structure is instantiated for each -wrap option.
1836 struct WrappedSymbol {
1837   Symbol *sym;
1838   Symbol *real;
1839   Symbol *wrap;
1840 };
1841 
1842 // Handles -wrap option.
1843 //
1844 // This function instantiates wrapper symbols. At this point, they seem
1845 // like they are not being used at all, so we explicitly set some flags so
1846 // that LTO won't eliminate them.
1847 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
1848   std::vector<WrappedSymbol> v;
1849   DenseSet<StringRef> seen;
1850 
1851   for (auto *arg : args.filtered(OPT_wrap)) {
1852     StringRef name = arg->getValue();
1853     if (!seen.insert(name).second)
1854       continue;
1855 
1856     Symbol *sym = symtab->find(name);
1857     if (!sym)
1858       continue;
1859 
1860     Symbol *real = addUndefined(saver.save("__real_" + name));
1861     Symbol *wrap = addUnusedUndefined(saver.save("__wrap_" + name));
1862     v.push_back({sym, real, wrap});
1863 
1864     // We want to tell LTO not to inline symbols to be overwritten
1865     // because LTO doesn't know the final symbol contents after renaming.
1866     real->canInline = false;
1867     sym->canInline = false;
1868 
1869     // Tell LTO not to eliminate these symbols.
1870     sym->isUsedInRegularObj = true;
1871     if (!wrap->isUndefined())
1872       wrap->isUsedInRegularObj = true;
1873   }
1874   return v;
1875 }
1876 
1877 // Do renaming for -wrap by updating pointers to symbols.
1878 //
1879 // When this function is executed, only InputFiles and symbol table
1880 // contain pointers to symbol objects. We visit them to replace pointers,
1881 // so that wrapped symbols are swapped as instructed by the command line.
1882 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
1883   DenseMap<Symbol *, Symbol *> map;
1884   for (const WrappedSymbol &w : wrapped) {
1885     map[w.sym] = w.wrap;
1886     map[w.real] = w.sym;
1887   }
1888 
1889   // Update pointers in input files.
1890   parallelForEach(objectFiles, [&](InputFile *file) {
1891     MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
1892     for (size_t i = 0, e = syms.size(); i != e; ++i)
1893       if (Symbol *s = map.lookup(syms[i]))
1894         syms[i] = s;
1895   });
1896 
1897   // Update pointers in the symbol table.
1898   for (const WrappedSymbol &w : wrapped)
1899     symtab->wrap(w.sym, w.real, w.wrap);
1900 }
1901 
1902 // To enable CET (x86's hardware-assited control flow enforcement), each
1903 // source file must be compiled with -fcf-protection. Object files compiled
1904 // with the flag contain feature flags indicating that they are compatible
1905 // with CET. We enable the feature only when all object files are compatible
1906 // with CET.
1907 //
1908 // This is also the case with AARCH64's BTI and PAC which use the similar
1909 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
1910 template <class ELFT> static uint32_t getAndFeatures() {
1911   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
1912       config->emachine != EM_AARCH64)
1913     return 0;
1914 
1915   uint32_t ret = -1;
1916   for (InputFile *f : objectFiles) {
1917     uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1918     if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
1919       warn(toString(f) + ": -z force-bti: file does not have "
1920                          "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
1921       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1922     } else if (config->zForceIbt &&
1923                !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
1924       warn(toString(f) + ": -z force-ibt: file does not have "
1925                          "GNU_PROPERTY_X86_FEATURE_1_IBT property");
1926       features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
1927     }
1928     if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
1929       warn(toString(f) + ": -z pac-plt: file does not have "
1930                          "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
1931       features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1932     }
1933     ret &= features;
1934   }
1935 
1936   // Force enable Shadow Stack.
1937   if (config->zShstk)
1938     ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
1939 
1940   return ret;
1941 }
1942 
1943 // Do actual linking. Note that when this function is called,
1944 // all linker scripts have already been parsed.
1945 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1946   llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
1947   // If a -hash-style option was not given, set to a default value,
1948   // which varies depending on the target.
1949   if (!args.hasArg(OPT_hash_style)) {
1950     if (config->emachine == EM_MIPS)
1951       config->sysvHash = true;
1952     else
1953       config->sysvHash = config->gnuHash = true;
1954   }
1955 
1956   // Default output filename is "a.out" by the Unix tradition.
1957   if (config->outputFile.empty())
1958     config->outputFile = "a.out";
1959 
1960   // Fail early if the output file or map file is not writable. If a user has a
1961   // long link, e.g. due to a large LTO link, they do not wish to run it and
1962   // find that it failed because there was a mistake in their command-line.
1963   if (auto e = tryCreateFile(config->outputFile))
1964     error("cannot open output file " + config->outputFile + ": " + e.message());
1965   if (auto e = tryCreateFile(config->mapFile))
1966     error("cannot open map file " + config->mapFile + ": " + e.message());
1967   if (errorCount())
1968     return;
1969 
1970   // Use default entry point name if no name was given via the command
1971   // line nor linker scripts. For some reason, MIPS entry point name is
1972   // different from others.
1973   config->warnMissingEntry =
1974       (!config->entry.empty() || (!config->shared && !config->relocatable));
1975   if (config->entry.empty() && !config->relocatable)
1976     config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
1977 
1978   // Handle --trace-symbol.
1979   for (auto *arg : args.filtered(OPT_trace_symbol))
1980     symtab->insert(arg->getValue())->traced = true;
1981 
1982   // Handle -u/--undefined before input files. If both a.a and b.so define foo,
1983   // -u foo a.a b.so will fetch a.a.
1984   for (StringRef name : config->undefined)
1985     addUnusedUndefined(name);
1986 
1987   // Add all files to the symbol table. This will add almost all
1988   // symbols that we need to the symbol table. This process might
1989   // add files to the link, via autolinking, these files are always
1990   // appended to the Files vector.
1991   {
1992     llvm::TimeTraceScope timeScope("Parse input files");
1993     for (size_t i = 0; i < files.size(); ++i)
1994       parseFile(files[i]);
1995   }
1996 
1997   // Now that we have every file, we can decide if we will need a
1998   // dynamic symbol table.
1999   // We need one if we were asked to export dynamic symbols or if we are
2000   // producing a shared library.
2001   // We also need one if any shared libraries are used and for pie executables
2002   // (probably because the dynamic linker needs it).
2003   config->hasDynSymTab =
2004       !sharedFiles.empty() || config->isPic || config->exportDynamic;
2005 
2006   // Some symbols (such as __ehdr_start) are defined lazily only when there
2007   // are undefined symbols for them, so we add these to trigger that logic.
2008   for (StringRef name : script->referencedSymbols)
2009     addUndefined(name);
2010 
2011   // Prevent LTO from removing any definition referenced by -u.
2012   for (StringRef name : config->undefined)
2013     if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name)))
2014       sym->isUsedInRegularObj = true;
2015 
2016   // If an entry symbol is in a static archive, pull out that file now.
2017   if (Symbol *sym = symtab->find(config->entry))
2018     handleUndefined(sym);
2019 
2020   // Handle the `--undefined-glob <pattern>` options.
2021   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
2022     handleUndefinedGlob(pat);
2023 
2024   // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2025   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init)))
2026     sym->isUsedInRegularObj = true;
2027   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini)))
2028     sym->isUsedInRegularObj = true;
2029 
2030   // If any of our inputs are bitcode files, the LTO code generator may create
2031   // references to certain library functions that might not be explicit in the
2032   // bitcode file's symbol table. If any of those library functions are defined
2033   // in a bitcode file in an archive member, we need to arrange to use LTO to
2034   // compile those archive members by adding them to the link beforehand.
2035   //
2036   // However, adding all libcall symbols to the link can have undesired
2037   // consequences. For example, the libgcc implementation of
2038   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
2039   // that aborts the program if the Linux kernel does not support 64-bit
2040   // atomics, which would prevent the program from running even if it does not
2041   // use 64-bit atomics.
2042   //
2043   // Therefore, we only add libcall symbols to the link before LTO if we have
2044   // to, i.e. if the symbol's definition is in bitcode. Any other required
2045   // libcall symbols will be added to the link after LTO when we add the LTO
2046   // object file to the link.
2047   if (!bitcodeFiles.empty())
2048     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2049       handleLibcall(s);
2050 
2051   // Return if there were name resolution errors.
2052   if (errorCount())
2053     return;
2054 
2055   // We want to declare linker script's symbols early,
2056   // so that we can version them.
2057   // They also might be exported if referenced by DSOs.
2058   script->declareSymbols();
2059 
2060   // Handle the -exclude-libs option.
2061   if (args.hasArg(OPT_exclude_libs))
2062     excludeLibs(args);
2063 
2064   // Create elfHeader early. We need a dummy section in
2065   // addReservedSymbols to mark the created symbols as not absolute.
2066   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
2067   Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
2068 
2069   // Create wrapped symbols for -wrap option.
2070   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
2071 
2072   // We need to create some reserved symbols such as _end. Create them.
2073   if (!config->relocatable)
2074     addReservedSymbols();
2075 
2076   // Apply version scripts.
2077   //
2078   // For a relocatable output, version scripts don't make sense, and
2079   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
2080   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2081   if (!config->relocatable)
2082     symtab->scanVersionScript();
2083 
2084   // Do link-time optimization if given files are LLVM bitcode files.
2085   // This compiles bitcode files into real object files.
2086   //
2087   // With this the symbol table should be complete. After this, no new names
2088   // except a few linker-synthesized ones will be added to the symbol table.
2089   compileBitcodeFiles<ELFT>();
2090 
2091   // Symbol resolution finished. Report backward reference problems.
2092   reportBackrefs();
2093   if (errorCount())
2094     return;
2095 
2096   // If -thinlto-index-only is given, we should create only "index
2097   // files" and not object files. Index file creation is already done
2098   // in addCombinedLTOObject, so we are done if that's the case.
2099   // Likewise, --plugin-opt=emit-llvm and --plugin-opt=emit-asm are the
2100   // options to create output files in bitcode or assembly code
2101   // repsectively. No object files are generated.
2102   // Also bail out here when only certain thinLTO modules are specified for
2103   // compilation. The intermediate object file are the expected output.
2104   if (config->thinLTOIndexOnly || config->emitLLVM || config->ltoEmitAsm ||
2105       !config->thinLTOModulesToCompile.empty())
2106     return;
2107 
2108   // Apply symbol renames for -wrap.
2109   if (!wrapped.empty())
2110     wrapSymbols(wrapped);
2111 
2112   // Now that we have a complete list of input files.
2113   // Beyond this point, no new files are added.
2114   // Aggregate all input sections into one place.
2115   for (InputFile *f : objectFiles)
2116     for (InputSectionBase *s : f->getSections())
2117       if (s && s != &InputSection::discarded)
2118         inputSections.push_back(s);
2119   for (BinaryFile *f : binaryFiles)
2120     for (InputSectionBase *s : f->getSections())
2121       inputSections.push_back(cast<InputSection>(s));
2122 
2123   llvm::erase_if(inputSections, [](InputSectionBase *s) {
2124     if (s->type == SHT_LLVM_SYMPART) {
2125       readSymbolPartitionSection<ELFT>(s);
2126       return true;
2127     }
2128 
2129     // We do not want to emit debug sections if --strip-all
2130     // or -strip-debug are given.
2131     if (config->strip == StripPolicy::None)
2132       return false;
2133 
2134     if (isDebugSection(*s))
2135       return true;
2136     if (auto *isec = dyn_cast<InputSection>(s))
2137       if (InputSectionBase *rel = isec->getRelocatedSection())
2138         if (isDebugSection(*rel))
2139           return true;
2140 
2141     return false;
2142   });
2143 
2144   // Since we now have a complete set of input files, we can create
2145   // a .d file to record build dependencies.
2146   if (!config->dependencyFile.empty())
2147     writeDependencyFile();
2148 
2149   // Now that the number of partitions is fixed, save a pointer to the main
2150   // partition.
2151   mainPart = &partitions[0];
2152 
2153   // Read .note.gnu.property sections from input object files which
2154   // contain a hint to tweak linker's and loader's behaviors.
2155   config->andFeatures = getAndFeatures<ELFT>();
2156 
2157   // The Target instance handles target-specific stuff, such as applying
2158   // relocations or writing a PLT section. It also contains target-dependent
2159   // values such as a default image base address.
2160   target = getTarget();
2161 
2162   config->eflags = target->calcEFlags();
2163   // maxPageSize (sometimes called abi page size) is the maximum page size that
2164   // the output can be run on. For example if the OS can use 4k or 64k page
2165   // sizes then maxPageSize must be 64k for the output to be useable on both.
2166   // All important alignment decisions must use this value.
2167   config->maxPageSize = getMaxPageSize(args);
2168   // commonPageSize is the most common page size that the output will be run on.
2169   // For example if an OS can use 4k or 64k page sizes and 4k is more common
2170   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
2171   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
2172   // is limited to writing trap instructions on the last executable segment.
2173   config->commonPageSize = getCommonPageSize(args);
2174 
2175   config->imageBase = getImageBase(args);
2176 
2177   if (config->emachine == EM_ARM) {
2178     // FIXME: These warnings can be removed when lld only uses these features
2179     // when the input objects have been compiled with an architecture that
2180     // supports them.
2181     if (config->armHasBlx == false)
2182       warn("lld uses blx instruction, no object with architecture supporting "
2183            "feature detected");
2184   }
2185 
2186   // This adds a .comment section containing a version string.
2187   if (!config->relocatable)
2188     inputSections.push_back(createCommentSection());
2189 
2190   // Replace common symbols with regular symbols.
2191   replaceCommonSymbols();
2192 
2193   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
2194   splitSections<ELFT>();
2195 
2196   // Garbage collection and removal of shared symbols from unused shared objects.
2197   markLive<ELFT>();
2198   demoteSharedSymbols();
2199 
2200   // Make copies of any input sections that need to be copied into each
2201   // partition.
2202   copySectionsIntoPartitions();
2203 
2204   // Create synthesized sections such as .got and .plt. This is called before
2205   // processSectionCommands() so that they can be placed by SECTIONS commands.
2206   createSyntheticSections<ELFT>();
2207 
2208   // Some input sections that are used for exception handling need to be moved
2209   // into synthetic sections. Do that now so that they aren't assigned to
2210   // output sections in the usual way.
2211   if (!config->relocatable)
2212     combineEhSections();
2213 
2214   // Create output sections described by SECTIONS commands.
2215   script->processSectionCommands();
2216 
2217   // Linker scripts control how input sections are assigned to output sections.
2218   // Input sections that were not handled by scripts are called "orphans", and
2219   // they are assigned to output sections by the default rule. Process that.
2220   script->addOrphanSections();
2221 
2222   // Migrate InputSectionDescription::sectionBases to sections. This includes
2223   // merging MergeInputSections into a single MergeSyntheticSection. From this
2224   // point onwards InputSectionDescription::sections should be used instead of
2225   // sectionBases.
2226   for (BaseCommand *base : script->sectionCommands)
2227     if (auto *sec = dyn_cast<OutputSection>(base))
2228       sec->finalizeInputSections();
2229   llvm::erase_if(inputSections,
2230                  [](InputSectionBase *s) { return isa<MergeInputSection>(s); });
2231 
2232   // Two input sections with different output sections should not be folded.
2233   // ICF runs after processSectionCommands() so that we know the output sections.
2234   if (config->icf != ICFLevel::None) {
2235     findKeepUniqueSections<ELFT>(args);
2236     doIcf<ELFT>();
2237   }
2238 
2239   // Read the callgraph now that we know what was gced or icfed
2240   if (config->callGraphProfileSort) {
2241     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
2242       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
2243         readCallGraph(*buffer);
2244     readCallGraphsFromObjectFiles<ELFT>();
2245   }
2246 
2247   // Write the result to the file.
2248   writeResult<ELFT>();
2249 }
2250