xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 72122d05)
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/Threads.h"
47 #include "lld/Common/Version.h"
48 #include "llvm/ADT/SetVector.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSwitch.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compression.h"
53 #include "llvm/Support/LEB128.h"
54 #include "llvm/Support/Path.h"
55 #include "llvm/Support/TarWriter.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <cstdlib>
59 #include <utility>
60 
61 using namespace llvm;
62 using namespace llvm::ELF;
63 using namespace llvm::object;
64 using namespace llvm::sys;
65 using namespace llvm::support;
66 
67 using namespace lld;
68 using namespace lld::elf;
69 
70 Configuration *elf::Config;
71 LinkerDriver *elf::Driver;
72 
73 static void setConfigs(opt::InputArgList &Args);
74 
75 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
76                raw_ostream &Error) {
77   errorHandler().LogName = args::getFilenameWithoutExe(Args[0]);
78   errorHandler().ErrorLimitExceededMsg =
79       "too many errors emitted, stopping now (use "
80       "-error-limit=0 to see all errors)";
81   errorHandler().ErrorOS = &Error;
82   errorHandler().ExitEarly = CanExitEarly;
83   errorHandler().ColorDiagnostics = Error.has_colors();
84 
85   InputSections.clear();
86   OutputSections.clear();
87   BinaryFiles.clear();
88   BitcodeFiles.clear();
89   ObjectFiles.clear();
90   SharedFiles.clear();
91 
92   Config = make<Configuration>();
93   Driver = make<LinkerDriver>();
94   Script = make<LinkerScript>();
95   Symtab = make<SymbolTable>();
96 
97   Tar = nullptr;
98   memset(&In, 0, sizeof(In));
99 
100   Config->ProgName = Args[0];
101 
102   Driver->main(Args);
103 
104   // Exit immediately if we don't need to return to the caller.
105   // This saves time because the overhead of calling destructors
106   // for all globally-allocated objects is not negligible.
107   if (CanExitEarly)
108     exitLld(errorCount() ? 1 : 0);
109 
110   freeArena();
111   return !errorCount();
112 }
113 
114 // Parses a linker -m option.
115 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
116   uint8_t OSABI = 0;
117   StringRef S = Emul;
118   if (S.endswith("_fbsd")) {
119     S = S.drop_back(5);
120     OSABI = ELFOSABI_FREEBSD;
121   }
122 
123   std::pair<ELFKind, uint16_t> Ret =
124       StringSwitch<std::pair<ELFKind, uint16_t>>(S)
125           .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
126                  {ELF64LEKind, EM_AARCH64})
127           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
128           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
129           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
130           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
131           .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
132           .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
133           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
134           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
135           .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
136           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
137           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
138           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
139           .Case("elf_i386", {ELF32LEKind, EM_386})
140           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
141           .Default({ELFNoneKind, EM_NONE});
142 
143   if (Ret.first == ELFNoneKind)
144     error("unknown emulation: " + Emul);
145   return std::make_tuple(Ret.first, Ret.second, OSABI);
146 }
147 
148 // Returns slices of MB by parsing MB as an archive file.
149 // Each slice consists of a member file in the archive.
150 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
151     MemoryBufferRef MB) {
152   std::unique_ptr<Archive> File =
153       CHECK(Archive::create(MB),
154             MB.getBufferIdentifier() + ": failed to parse archive");
155 
156   std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
157   Error Err = Error::success();
158   bool AddToTar = File->isThin() && Tar;
159   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
160     Archive::Child C =
161         CHECK(COrErr, MB.getBufferIdentifier() +
162                           ": could not get the child of the archive");
163     MemoryBufferRef MBRef =
164         CHECK(C.getMemoryBufferRef(),
165               MB.getBufferIdentifier() +
166                   ": could not get the buffer for a child of the archive");
167     if (AddToTar)
168       Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer());
169     V.push_back(std::make_pair(MBRef, C.getChildOffset()));
170   }
171   if (Err)
172     fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
173           toString(std::move(Err)));
174 
175   // Take ownership of memory buffers created for members of thin archives.
176   for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
177     make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
178 
179   return V;
180 }
181 
182 // Opens a file and create a file object. Path has to be resolved already.
183 void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
184   using namespace sys::fs;
185 
186   Optional<MemoryBufferRef> Buffer = readFile(Path);
187   if (!Buffer.hasValue())
188     return;
189   MemoryBufferRef MBRef = *Buffer;
190 
191   if (Config->FormatBinary) {
192     Files.push_back(make<BinaryFile>(MBRef));
193     return;
194   }
195 
196   switch (identify_magic(MBRef.getBuffer())) {
197   case file_magic::unknown:
198     readLinkerScript(MBRef);
199     return;
200   case file_magic::archive: {
201     // Handle -whole-archive.
202     if (InWholeArchive) {
203       for (const auto &P : getArchiveMembers(MBRef))
204         Files.push_back(createObjectFile(P.first, Path, P.second));
205       return;
206     }
207 
208     std::unique_ptr<Archive> File =
209         CHECK(Archive::create(MBRef), Path + ": failed to parse archive");
210 
211     // If an archive file has no symbol table, it is likely that a user
212     // is attempting LTO and using a default ar command that doesn't
213     // understand the LLVM bitcode file. It is a pretty common error, so
214     // we'll handle it as if it had a symbol table.
215     if (!File->isEmpty() && !File->hasSymbolTable()) {
216       // Check if all members are bitcode files. If not, ignore, which is the
217       // default action without the LTO hack described above.
218       for (const std::pair<MemoryBufferRef, uint64_t> &P :
219            getArchiveMembers(MBRef))
220         if (identify_magic(P.first.getBuffer()) != file_magic::bitcode)
221           return;
222 
223       for (const std::pair<MemoryBufferRef, uint64_t> &P :
224            getArchiveMembers(MBRef))
225         Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
226       return;
227     }
228 
229     // Handle the regular case.
230     Files.push_back(make<ArchiveFile>(std::move(File)));
231     return;
232   }
233   case file_magic::elf_shared_object:
234     if (Config->Static || Config->Relocatable) {
235       error("attempted static link of dynamic object " + Path);
236       return;
237     }
238 
239     // DSOs usually have DT_SONAME tags in their ELF headers, and the
240     // sonames are used to identify DSOs. But if they are missing,
241     // they are identified by filenames. We don't know whether the new
242     // file has a DT_SONAME or not because we haven't parsed it yet.
243     // Here, we set the default soname for the file because we might
244     // need it later.
245     //
246     // If a file was specified by -lfoo, the directory part is not
247     // significant, as a user did not specify it. This behavior is
248     // compatible with GNU.
249     Files.push_back(
250         createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path));
251     return;
252   case file_magic::bitcode:
253   case file_magic::elf_relocatable:
254     if (InLib)
255       Files.push_back(make<LazyObjFile>(MBRef, "", 0));
256     else
257       Files.push_back(createObjectFile(MBRef));
258     break;
259   default:
260     error(Path + ": unknown file type");
261   }
262 }
263 
264 // Add a given library by searching it from input search paths.
265 void LinkerDriver::addLibrary(StringRef Name) {
266   if (Optional<std::string> Path = searchLibrary(Name))
267     addFile(*Path, /*WithLOption=*/true);
268   else
269     error("unable to find library -l" + Name);
270 }
271 
272 // This function is called on startup. We need this for LTO since
273 // LTO calls LLVM functions to compile bitcode files to native code.
274 // Technically this can be delayed until we read bitcode files, but
275 // we don't bother to do lazily because the initialization is fast.
276 static void initLLVM() {
277   InitializeAllTargets();
278   InitializeAllTargetMCs();
279   InitializeAllAsmPrinters();
280   InitializeAllAsmParsers();
281 }
282 
283 // Some command line options or some combinations of them are not allowed.
284 // This function checks for such errors.
285 static void checkOptions() {
286   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
287   // table which is a relatively new feature.
288   if (Config->EMachine == EM_MIPS && Config->GnuHash)
289     error("the .gnu.hash section is not compatible with the MIPS target");
290 
291   if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64)
292     error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
293 
294   if (Config->TocOptimize && Config->EMachine != EM_PPC64)
295     error("--toc-optimize is only supported on the PowerPC64 target");
296 
297   if (Config->Pie && Config->Shared)
298     error("-shared and -pie may not be used together");
299 
300   if (!Config->Shared && !Config->FilterList.empty())
301     error("-F may not be used without -shared");
302 
303   if (!Config->Shared && !Config->AuxiliaryList.empty())
304     error("-f may not be used without -shared");
305 
306   if (!Config->Relocatable && !Config->DefineCommon)
307     error("-no-define-common not supported in non relocatable output");
308 
309   if (Config->Relocatable) {
310     if (Config->Shared)
311       error("-r and -shared may not be used together");
312     if (Config->GcSections)
313       error("-r and --gc-sections may not be used together");
314     if (Config->GdbIndex)
315       error("-r and --gdb-index may not be used together");
316     if (Config->ICF != ICFLevel::None)
317       error("-r and --icf may not be used together");
318     if (Config->Pie)
319       error("-r and -pie may not be used together");
320   }
321 
322   if (Config->ExecuteOnly) {
323     if (Config->EMachine != EM_AARCH64)
324       error("-execute-only is only supported on AArch64 targets");
325 
326     if (Config->SingleRoRx && !Script->HasSectionsCommand)
327       error("-execute-only and -no-rosegment cannot be used together");
328   }
329 }
330 
331 static const char *getReproduceOption(opt::InputArgList &Args) {
332   if (auto *Arg = Args.getLastArg(OPT_reproduce))
333     return Arg->getValue();
334   return getenv("LLD_REPRODUCE");
335 }
336 
337 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
338   for (auto *Arg : Args.filtered(OPT_z))
339     if (Key == Arg->getValue())
340       return true;
341   return false;
342 }
343 
344 static bool getZFlag(opt::InputArgList &Args, StringRef K1, StringRef K2,
345                      bool Default) {
346   for (auto *Arg : Args.filtered_reverse(OPT_z)) {
347     if (K1 == Arg->getValue())
348       return true;
349     if (K2 == Arg->getValue())
350       return false;
351   }
352   return Default;
353 }
354 
355 static bool isKnownZFlag(StringRef S) {
356   return S == "combreloc" || S == "copyreloc" || S == "defs" ||
357          S == "execstack" || S == "global" || S == "hazardplt" ||
358          S == "initfirst" || S == "interpose" ||
359          S == "keep-text-section-prefix" || S == "lazy" || S == "muldefs" ||
360          S == "nocombreloc" || S == "nocopyreloc" || S == "nodefaultlib" ||
361          S == "nodelete" || S == "nodlopen" || S == "noexecstack" ||
362          S == "nokeep-text-section-prefix" || S == "norelro" || S == "notext" ||
363          S == "now" || S == "origin" || S == "relro" || S == "retpolineplt" ||
364          S == "rodynamic" || S == "text" || S == "wxneeded" ||
365          S.startswith("max-page-size=") || S.startswith("stack-size=");
366 }
367 
368 // Report an error for an unknown -z option.
369 static void checkZOptions(opt::InputArgList &Args) {
370   for (auto *Arg : Args.filtered(OPT_z))
371     if (!isKnownZFlag(Arg->getValue()))
372       error("unknown -z value: " + StringRef(Arg->getValue()));
373 }
374 
375 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
376   ELFOptTable Parser;
377   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
378 
379   // Interpret this flag early because error() depends on them.
380   errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
381   checkZOptions(Args);
382 
383   // Handle -help
384   if (Args.hasArg(OPT_help)) {
385     printHelp();
386     return;
387   }
388 
389   // Handle -v or -version.
390   //
391   // A note about "compatible with GNU linkers" message: this is a hack for
392   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
393   // still the newest version in March 2017) or earlier to recognize LLD as
394   // a GNU compatible linker. As long as an output for the -v option
395   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
396   //
397   // This is somewhat ugly hack, but in reality, we had no choice other
398   // than doing this. Considering the very long release cycle of Libtool,
399   // it is not easy to improve it to recognize LLD as a GNU compatible
400   // linker in a timely manner. Even if we can make it, there are still a
401   // lot of "configure" scripts out there that are generated by old version
402   // of Libtool. We cannot convince every software developer to migrate to
403   // the latest version and re-generate scripts. So we have this hack.
404   if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
405     message(getLLDVersion() + " (compatible with GNU linkers)");
406 
407   if (const char *Path = getReproduceOption(Args)) {
408     // Note that --reproduce is a debug option so you can ignore it
409     // if you are trying to understand the whole picture of the code.
410     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
411         TarWriter::create(Path, path::stem(Path));
412     if (ErrOrWriter) {
413       Tar = std::move(*ErrOrWriter);
414       Tar->append("response.txt", createResponseFile(Args));
415       Tar->append("version.txt", getLLDVersion() + "\n");
416     } else {
417       error("--reproduce: " + toString(ErrOrWriter.takeError()));
418     }
419   }
420 
421   readConfigs(Args);
422 
423   // The behavior of -v or --version is a bit strange, but this is
424   // needed for compatibility with GNU linkers.
425   if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT))
426     return;
427   if (Args.hasArg(OPT_version))
428     return;
429 
430   initLLVM();
431   createFiles(Args);
432   if (errorCount())
433     return;
434 
435   inferMachineType();
436   setConfigs(Args);
437   checkOptions();
438   if (errorCount())
439     return;
440 
441   switch (Config->EKind) {
442   case ELF32LEKind:
443     link<ELF32LE>(Args);
444     return;
445   case ELF32BEKind:
446     link<ELF32BE>(Args);
447     return;
448   case ELF64LEKind:
449     link<ELF64LE>(Args);
450     return;
451   case ELF64BEKind:
452     link<ELF64BE>(Args);
453     return;
454   default:
455     llvm_unreachable("unknown Config->EKind");
456   }
457 }
458 
459 static std::string getRpath(opt::InputArgList &Args) {
460   std::vector<StringRef> V = args::getStrings(Args, OPT_rpath);
461   return llvm::join(V.begin(), V.end(), ":");
462 }
463 
464 // Determines what we should do if there are remaining unresolved
465 // symbols after the name resolution.
466 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
467   UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols,
468                                               OPT_warn_unresolved_symbols, true)
469                                      ? UnresolvedPolicy::ReportError
470                                      : UnresolvedPolicy::Warn;
471 
472   // Process the last of -unresolved-symbols, -no-undefined or -z defs.
473   for (auto *Arg : llvm::reverse(Args)) {
474     switch (Arg->getOption().getID()) {
475     case OPT_unresolved_symbols: {
476       StringRef S = Arg->getValue();
477       if (S == "ignore-all" || S == "ignore-in-object-files")
478         return UnresolvedPolicy::Ignore;
479       if (S == "ignore-in-shared-libs" || S == "report-all")
480         return ErrorOrWarn;
481       error("unknown --unresolved-symbols value: " + S);
482       continue;
483     }
484     case OPT_no_undefined:
485       return ErrorOrWarn;
486     case OPT_z:
487       if (StringRef(Arg->getValue()) == "defs")
488         return ErrorOrWarn;
489       continue;
490     }
491   }
492 
493   // -shared implies -unresolved-symbols=ignore-all because missing
494   // symbols are likely to be resolved at runtime using other DSOs.
495   if (Config->Shared)
496     return UnresolvedPolicy::Ignore;
497   return ErrorOrWarn;
498 }
499 
500 static Target2Policy getTarget2(opt::InputArgList &Args) {
501   StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
502   if (S == "rel")
503     return Target2Policy::Rel;
504   if (S == "abs")
505     return Target2Policy::Abs;
506   if (S == "got-rel")
507     return Target2Policy::GotRel;
508   error("unknown --target2 option: " + S);
509   return Target2Policy::GotRel;
510 }
511 
512 static bool isOutputFormatBinary(opt::InputArgList &Args) {
513   StringRef S = Args.getLastArgValue(OPT_oformat, "elf");
514   if (S == "binary")
515     return true;
516   if (!S.startswith("elf"))
517     error("unknown --oformat value: " + S);
518   return false;
519 }
520 
521 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
522   if (Args.hasArg(OPT_relocatable))
523     return DiscardPolicy::None;
524 
525   auto *Arg =
526       Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
527   if (!Arg)
528     return DiscardPolicy::Default;
529   if (Arg->getOption().getID() == OPT_discard_all)
530     return DiscardPolicy::All;
531   if (Arg->getOption().getID() == OPT_discard_locals)
532     return DiscardPolicy::Locals;
533   return DiscardPolicy::None;
534 }
535 
536 static StringRef getDynamicLinker(opt::InputArgList &Args) {
537   auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
538   if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
539     return "";
540   return Arg->getValue();
541 }
542 
543 static ICFLevel getICF(opt::InputArgList &Args) {
544   auto *Arg = Args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
545   if (!Arg || Arg->getOption().getID() == OPT_icf_none)
546     return ICFLevel::None;
547   if (Arg->getOption().getID() == OPT_icf_safe)
548     return ICFLevel::Safe;
549   return ICFLevel::All;
550 }
551 
552 static StripPolicy getStrip(opt::InputArgList &Args) {
553   if (Args.hasArg(OPT_relocatable))
554     return StripPolicy::None;
555 
556   auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
557   if (!Arg)
558     return StripPolicy::None;
559   if (Arg->getOption().getID() == OPT_strip_all)
560     return StripPolicy::All;
561   return StripPolicy::Debug;
562 }
563 
564 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) {
565   uint64_t VA = 0;
566   if (S.startswith("0x"))
567     S = S.drop_front(2);
568   if (!to_integer(S, VA, 16))
569     error("invalid argument: " + toString(Arg));
570   return VA;
571 }
572 
573 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
574   StringMap<uint64_t> Ret;
575   for (auto *Arg : Args.filtered(OPT_section_start)) {
576     StringRef Name;
577     StringRef Addr;
578     std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
579     Ret[Name] = parseSectionAddress(Addr, *Arg);
580   }
581 
582   if (auto *Arg = Args.getLastArg(OPT_Ttext))
583     Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg);
584   if (auto *Arg = Args.getLastArg(OPT_Tdata))
585     Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg);
586   if (auto *Arg = Args.getLastArg(OPT_Tbss))
587     Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg);
588   return Ret;
589 }
590 
591 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
592   StringRef S = Args.getLastArgValue(OPT_sort_section);
593   if (S == "alignment")
594     return SortSectionPolicy::Alignment;
595   if (S == "name")
596     return SortSectionPolicy::Name;
597   if (!S.empty())
598     error("unknown --sort-section rule: " + S);
599   return SortSectionPolicy::Default;
600 }
601 
602 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) {
603   StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place");
604   if (S == "warn")
605     return OrphanHandlingPolicy::Warn;
606   if (S == "error")
607     return OrphanHandlingPolicy::Error;
608   if (S != "place")
609     error("unknown --orphan-handling mode: " + S);
610   return OrphanHandlingPolicy::Place;
611 }
612 
613 // Parse --build-id or --build-id=<style>. We handle "tree" as a
614 // synonym for "sha1" because all our hash functions including
615 // -build-id=sha1 are actually tree hashes for performance reasons.
616 static std::pair<BuildIdKind, std::vector<uint8_t>>
617 getBuildId(opt::InputArgList &Args) {
618   auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
619   if (!Arg)
620     return {BuildIdKind::None, {}};
621 
622   if (Arg->getOption().getID() == OPT_build_id)
623     return {BuildIdKind::Fast, {}};
624 
625   StringRef S = Arg->getValue();
626   if (S == "fast")
627     return {BuildIdKind::Fast, {}};
628   if (S == "md5")
629     return {BuildIdKind::Md5, {}};
630   if (S == "sha1" || S == "tree")
631     return {BuildIdKind::Sha1, {}};
632   if (S == "uuid")
633     return {BuildIdKind::Uuid, {}};
634   if (S.startswith("0x"))
635     return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
636 
637   if (S != "none")
638     error("unknown --build-id style: " + S);
639   return {BuildIdKind::None, {}};
640 }
641 
642 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &Args) {
643   StringRef S = Args.getLastArgValue(OPT_pack_dyn_relocs, "none");
644   if (S == "android")
645     return {true, false};
646   if (S == "relr")
647     return {false, true};
648   if (S == "android+relr")
649     return {true, true};
650 
651   if (S != "none")
652     error("unknown -pack-dyn-relocs format: " + S);
653   return {false, false};
654 }
655 
656 static void readCallGraph(MemoryBufferRef MB) {
657   // Build a map from symbol name to section
658   DenseMap<StringRef, Symbol *> Map;
659   for (InputFile *File : ObjectFiles)
660     for (Symbol *Sym : File->getSymbols())
661       Map[Sym->getName()] = Sym;
662 
663   auto FindSection = [&](StringRef Name) -> InputSectionBase * {
664     Symbol *Sym = Map.lookup(Name);
665     if (!Sym) {
666       if (Config->WarnSymbolOrdering)
667         warn(MB.getBufferIdentifier() + ": no such symbol: " + Name);
668       return nullptr;
669     }
670     maybeWarnUnorderableSymbol(Sym);
671 
672     if (Defined *DR = dyn_cast_or_null<Defined>(Sym))
673       return dyn_cast_or_null<InputSectionBase>(DR->Section);
674     return nullptr;
675   };
676 
677   for (StringRef Line : args::getLines(MB)) {
678     SmallVector<StringRef, 3> Fields;
679     Line.split(Fields, ' ');
680     uint64_t Count;
681 
682     if (Fields.size() != 3 || !to_integer(Fields[2], Count)) {
683       error(MB.getBufferIdentifier() + ": parse error");
684       return;
685     }
686 
687     if (InputSectionBase *From = FindSection(Fields[0]))
688       if (InputSectionBase *To = FindSection(Fields[1]))
689         Config->CallGraphProfile[std::make_pair(From, To)] += Count;
690   }
691 }
692 
693 template <class ELFT> static void readCallGraphsFromObjectFiles() {
694   for (auto File : ObjectFiles) {
695     auto *Obj = cast<ObjFile<ELFT>>(File);
696 
697     for (const Elf_CGProfile_Impl<ELFT> &CGPE : Obj->CGProfile) {
698       auto *FromSym = dyn_cast<Defined>(&Obj->getSymbol(CGPE.cgp_from));
699       auto *ToSym = dyn_cast<Defined>(&Obj->getSymbol(CGPE.cgp_to));
700       if (!FromSym || !ToSym)
701         continue;
702 
703       auto *From = dyn_cast_or_null<InputSectionBase>(FromSym->Section);
704       auto *To = dyn_cast_or_null<InputSectionBase>(ToSym->Section);
705       if (From && To)
706         Config->CallGraphProfile[{From, To}] += CGPE.cgp_weight;
707     }
708   }
709 }
710 
711 static bool getCompressDebugSections(opt::InputArgList &Args) {
712   StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
713   if (S == "none")
714     return false;
715   if (S != "zlib")
716     error("unknown --compress-debug-sections value: " + S);
717   if (!zlib::isAvailable())
718     error("--compress-debug-sections: zlib is not available");
719   return true;
720 }
721 
722 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &Args,
723                                                         unsigned Id) {
724   auto *Arg = Args.getLastArg(Id);
725   if (!Arg)
726     return {"", ""};
727 
728   StringRef S = Arg->getValue();
729   std::pair<StringRef, StringRef> Ret = S.split(';');
730   if (Ret.second.empty())
731     error(Arg->getSpelling() + " expects 'old;new' format, but got " + S);
732   return Ret;
733 }
734 
735 // Parse the symbol ordering file and warn for any duplicate entries.
736 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef MB) {
737   SetVector<StringRef> Names;
738   for (StringRef S : args::getLines(MB))
739     if (!Names.insert(S) && Config->WarnSymbolOrdering)
740       warn(MB.getBufferIdentifier() + ": duplicate ordered symbol: " + S);
741 
742   return Names.takeVector();
743 }
744 
745 static void parseClangOption(StringRef Opt, const Twine &Msg) {
746   std::string Err;
747   raw_string_ostream OS(Err);
748 
749   const char *Argv[] = {Config->ProgName.data(), Opt.data()};
750   if (cl::ParseCommandLineOptions(2, Argv, "", &OS))
751     return;
752   OS.flush();
753   error(Msg + ": " + StringRef(Err).trim());
754 }
755 
756 // Initializes Config members by the command line options.
757 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
758   errorHandler().Verbose = Args.hasArg(OPT_verbose);
759   errorHandler().FatalWarnings =
760       Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
761   ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
762 
763   Config->AllowMultipleDefinition =
764       Args.hasFlag(OPT_allow_multiple_definition,
765                    OPT_no_allow_multiple_definition, false) ||
766       hasZOption(Args, "muldefs");
767   Config->AllowShlibUndefined =
768       Args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined,
769                    Args.hasArg(OPT_shared));
770   Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary);
771   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
772   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
773   Config->CheckSections =
774       Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
775   Config->Chroot = Args.getLastArgValue(OPT_chroot);
776   Config->CompressDebugSections = getCompressDebugSections(Args);
777   Config->Cref = Args.hasFlag(OPT_cref, OPT_no_cref, false);
778   Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common,
779                                       !Args.hasArg(OPT_relocatable));
780   Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
781   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
782   Config->Discard = getDiscard(Args);
783   Config->DwoDir = Args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
784   Config->DynamicLinker = getDynamicLinker(Args);
785   Config->EhFrameHdr =
786       Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
787   Config->EmitLLVM = Args.hasArg(OPT_plugin_opt_emit_llvm, false);
788   Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
789   Config->CallGraphProfileSort = Args.hasFlag(
790       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
791   Config->EnableNewDtags =
792       Args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
793   Config->Entry = Args.getLastArgValue(OPT_entry);
794   Config->ExecuteOnly =
795       Args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
796   Config->ExportDynamic =
797       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
798   Config->FilterList = args::getStrings(Args, OPT_filter);
799   Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
800   Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419);
801   Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
802   Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
803   Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
804   Config->ICF = getICF(Args);
805   Config->IgnoreDataAddressEquality =
806       Args.hasArg(OPT_ignore_data_address_equality);
807   Config->IgnoreFunctionAddressEquality =
808       Args.hasArg(OPT_ignore_function_address_equality);
809   Config->Init = Args.getLastArgValue(OPT_init, "_init");
810   Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
811   Config->LTOCSProfileGenerate = Args.hasArg(OPT_lto_cs_profile_generate);
812   Config->LTOCSProfileFile = Args.getLastArgValue(OPT_lto_cs_profile_file);
813   Config->LTODebugPassManager = Args.hasArg(OPT_lto_debug_pass_manager);
814   Config->LTONewPassManager = Args.hasArg(OPT_lto_new_pass_manager);
815   Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
816   Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
817   Config->LTOObjPath = Args.getLastArgValue(OPT_plugin_opt_obj_path_eq);
818   Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
819   Config->LTOSampleProfile = Args.getLastArgValue(OPT_lto_sample_profile);
820   Config->MapFile = Args.getLastArgValue(OPT_Map);
821   Config->MipsGotSize = args::getInteger(Args, OPT_mips_got_size, 0xfff0);
822   Config->MergeArmExidx =
823       Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
824   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
825   Config->Nostdlib = Args.hasArg(OPT_nostdlib);
826   Config->OFormatBinary = isOutputFormatBinary(Args);
827   Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false);
828   Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
829   Config->OptRemarksPasses = Args.getLastArgValue(OPT_opt_remarks_passes);
830   Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
831   Config->Optimize = args::getInteger(Args, OPT_O, 1);
832   Config->OrphanHandling = getOrphanHandling(Args);
833   Config->OutputFile = Args.getLastArgValue(OPT_o);
834   Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false);
835   Config->PrintIcfSections =
836       Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
837   Config->PrintGcSections =
838       Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
839   Config->Rpath = getRpath(Args);
840   Config->Relocatable = Args.hasArg(OPT_relocatable);
841   Config->SaveTemps = Args.hasArg(OPT_save_temps);
842   Config->SearchPaths = args::getStrings(Args, OPT_library_path);
843   Config->SectionStartMap = getSectionStartMap(Args);
844   Config->Shared = Args.hasArg(OPT_shared);
845   Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
846   Config->SoName = Args.getLastArgValue(OPT_soname);
847   Config->SortSection = getSortSection(Args);
848   Config->SplitStackAdjustSize = args::getInteger(Args, OPT_split_stack_adjust_size, 16384);
849   Config->Strip = getStrip(Args);
850   Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
851   Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
852   Config->Target2 = getTarget2(Args);
853   Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
854   Config->ThinLTOCachePolicy = CHECK(
855       parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
856       "--thinlto-cache-policy: invalid cache policy");
857   Config->ThinLTOEmitImportsFiles =
858       Args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files);
859   Config->ThinLTOIndexOnly = Args.hasArg(OPT_plugin_opt_thinlto_index_only) ||
860                              Args.hasArg(OPT_plugin_opt_thinlto_index_only_eq);
861   Config->ThinLTOIndexOnlyArg =
862       Args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq);
863   Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
864   Config->ThinLTOObjectSuffixReplace =
865       getOldNewOptions(Args, OPT_plugin_opt_thinlto_object_suffix_replace_eq);
866   Config->ThinLTOPrefixReplace =
867       getOldNewOptions(Args, OPT_plugin_opt_thinlto_prefix_replace_eq);
868   Config->Trace = Args.hasArg(OPT_trace);
869   Config->Undefined = args::getStrings(Args, OPT_undefined);
870   Config->UndefinedVersion =
871       Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
872   Config->UseAndroidRelrTags = Args.hasFlag(
873       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
874   Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
875   Config->WarnBackrefs =
876       Args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
877   Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
878   Config->WarnIfuncTextrel =
879       Args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
880   Config->WarnSymbolOrdering =
881       Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
882   Config->ZCombreloc = getZFlag(Args, "combreloc", "nocombreloc", true);
883   Config->ZCopyreloc = getZFlag(Args, "copyreloc", "nocopyreloc", true);
884   Config->ZExecstack = getZFlag(Args, "execstack", "noexecstack", false);
885   Config->ZGlobal = hasZOption(Args, "global");
886   Config->ZHazardplt = hasZOption(Args, "hazardplt");
887   Config->ZInitfirst = hasZOption(Args, "initfirst");
888   Config->ZInterpose = hasZOption(Args, "interpose");
889   Config->ZKeepTextSectionPrefix = getZFlag(
890       Args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
891   Config->ZNodefaultlib = hasZOption(Args, "nodefaultlib");
892   Config->ZNodelete = hasZOption(Args, "nodelete");
893   Config->ZNodlopen = hasZOption(Args, "nodlopen");
894   Config->ZNow = getZFlag(Args, "now", "lazy", false);
895   Config->ZOrigin = hasZOption(Args, "origin");
896   Config->ZRelro = getZFlag(Args, "relro", "norelro", true);
897   Config->ZRetpolineplt = hasZOption(Args, "retpolineplt");
898   Config->ZRodynamic = hasZOption(Args, "rodynamic");
899   Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
900   Config->ZText = getZFlag(Args, "text", "notext", true);
901   Config->ZWxneeded = hasZOption(Args, "wxneeded");
902 
903   // Parse LTO options.
904   if (auto *Arg = Args.getLastArg(OPT_plugin_opt_mcpu_eq))
905     parseClangOption(Saver.save("-mcpu=" + StringRef(Arg->getValue())),
906                      Arg->getSpelling());
907 
908   for (auto *Arg : Args.filtered(OPT_plugin_opt))
909     parseClangOption(Arg->getValue(), Arg->getSpelling());
910 
911   // Parse -mllvm options.
912   for (auto *Arg : Args.filtered(OPT_mllvm))
913     parseClangOption(Arg->getValue(), Arg->getSpelling());
914 
915   if (Config->LTOO > 3)
916     error("invalid optimization level for LTO: " + Twine(Config->LTOO));
917   if (Config->LTOPartitions == 0)
918     error("--lto-partitions: number of threads must be > 0");
919   if (Config->ThinLTOJobs == 0)
920     error("--thinlto-jobs: number of threads must be > 0");
921 
922   if (Config->SplitStackAdjustSize < 0)
923     error("--split-stack-adjust-size: size must be >= 0");
924 
925   // Parse ELF{32,64}{LE,BE} and CPU type.
926   if (auto *Arg = Args.getLastArg(OPT_m)) {
927     StringRef S = Arg->getValue();
928     std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
929         parseEmulation(S);
930     Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
931     Config->Emulation = S;
932   }
933 
934   // Parse -hash-style={sysv,gnu,both}.
935   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
936     StringRef S = Arg->getValue();
937     if (S == "sysv")
938       Config->SysvHash = true;
939     else if (S == "gnu")
940       Config->GnuHash = true;
941     else if (S == "both")
942       Config->SysvHash = Config->GnuHash = true;
943     else
944       error("unknown -hash-style: " + S);
945   }
946 
947   if (Args.hasArg(OPT_print_map))
948     Config->MapFile = "-";
949 
950   // --omagic is an option to create old-fashioned executables in which
951   // .text segments are writable. Today, the option is still in use to
952   // create special-purpose programs such as boot loaders. It doesn't
953   // make sense to create PT_GNU_RELRO for such executables.
954   if (Config->Omagic)
955     Config->ZRelro = false;
956 
957   std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
958 
959   std::tie(Config->AndroidPackDynRelocs, Config->RelrPackDynRelocs) =
960       getPackDynRelocs(Args);
961 
962   if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
963     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
964       Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer);
965 
966   // If --retain-symbol-file is used, we'll keep only the symbols listed in
967   // the file and discard all others.
968   if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
969     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
970     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
971       for (StringRef S : args::getLines(*Buffer))
972         Config->VersionScriptGlobals.push_back(
973             {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
974   }
975 
976   bool HasExportDynamic =
977       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
978 
979   // Parses -dynamic-list and -export-dynamic-symbol. They make some
980   // symbols private. Note that -export-dynamic takes precedence over them
981   // as it says all symbols should be exported.
982   if (!HasExportDynamic) {
983     for (auto *Arg : Args.filtered(OPT_dynamic_list))
984       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
985         readDynamicList(*Buffer);
986 
987     for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
988       Config->DynamicList.push_back(
989           {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
990   }
991 
992   // If --export-dynamic-symbol=foo is given and symbol foo is defined in
993   // an object file in an archive file, that object file should be pulled
994   // out and linked. (It doesn't have to behave like that from technical
995   // point of view, but this is needed for compatibility with GNU.)
996   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
997     Config->Undefined.push_back(Arg->getValue());
998 
999   for (auto *Arg : Args.filtered(OPT_version_script))
1000     if (Optional<std::string> Path = searchScript(Arg->getValue())) {
1001       if (Optional<MemoryBufferRef> Buffer = readFile(*Path))
1002         readVersionScript(*Buffer);
1003     } else {
1004       error(Twine("cannot find version script ") + Arg->getValue());
1005     }
1006 }
1007 
1008 // Some Config members do not directly correspond to any particular
1009 // command line options, but computed based on other Config values.
1010 // This function initialize such members. See Config.h for the details
1011 // of these values.
1012 static void setConfigs(opt::InputArgList &Args) {
1013   ELFKind K = Config->EKind;
1014   uint16_t M = Config->EMachine;
1015 
1016   Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
1017   Config->Is64 = (K == ELF64LEKind || K == ELF64BEKind);
1018   Config->IsLE = (K == ELF32LEKind || K == ELF64LEKind);
1019   Config->Endianness = Config->IsLE ? endianness::little : endianness::big;
1020   Config->IsMips64EL = (K == ELF64LEKind && M == EM_MIPS);
1021   Config->Pic = Config->Pie || Config->Shared;
1022   Config->PicThunk = Args.hasArg(OPT_pic_veneer, Config->Pic);
1023   Config->Wordsize = Config->Is64 ? 8 : 4;
1024 
1025   // ELF defines two different ways to store relocation addends as shown below:
1026   //
1027   //  Rel:  Addends are stored to the location where relocations are applied.
1028   //  Rela: Addends are stored as part of relocation entry.
1029   //
1030   // In other words, Rela makes it easy to read addends at the price of extra
1031   // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
1032   // different mechanisms in the first place, but this is how the spec is
1033   // defined.
1034   //
1035   // You cannot choose which one, Rel or Rela, you want to use. Instead each
1036   // ABI defines which one you need to use. The following expression expresses
1037   // that.
1038   Config->IsRela = M == EM_AARCH64 || M == EM_AMDGPU || M == EM_HEXAGON ||
1039                    M == EM_PPC || M == EM_PPC64 || M == EM_RISCV ||
1040                    M == EM_X86_64;
1041 
1042   // If the output uses REL relocations we must store the dynamic relocation
1043   // addends to the output sections. We also store addends for RELA relocations
1044   // if --apply-dynamic-relocs is used.
1045   // We default to not writing the addends when using RELA relocations since
1046   // any standard conforming tool can find it in r_addend.
1047   Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs,
1048                                       OPT_no_apply_dynamic_relocs, false) ||
1049                          !Config->IsRela;
1050 
1051   Config->TocOptimize =
1052       Args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, M == EM_PPC64);
1053 }
1054 
1055 // Returns a value of "-format" option.
1056 static bool isFormatBinary(StringRef S) {
1057   if (S == "binary")
1058     return true;
1059   if (S == "elf" || S == "default")
1060     return false;
1061   error("unknown -format value: " + S +
1062         " (supported formats: elf, default, binary)");
1063   return false;
1064 }
1065 
1066 void LinkerDriver::createFiles(opt::InputArgList &Args) {
1067   // For --{push,pop}-state.
1068   std::vector<std::tuple<bool, bool, bool>> Stack;
1069 
1070   // Iterate over argv to process input files and positional arguments.
1071   for (auto *Arg : Args) {
1072     switch (Arg->getOption().getUnaliasedOption().getID()) {
1073     case OPT_library:
1074       addLibrary(Arg->getValue());
1075       break;
1076     case OPT_INPUT:
1077       addFile(Arg->getValue(), /*WithLOption=*/false);
1078       break;
1079     case OPT_defsym: {
1080       StringRef From;
1081       StringRef To;
1082       std::tie(From, To) = StringRef(Arg->getValue()).split('=');
1083       if (From.empty() || To.empty())
1084         error("-defsym: syntax error: " + StringRef(Arg->getValue()));
1085       else
1086         readDefsym(From, MemoryBufferRef(To, "-defsym"));
1087       break;
1088     }
1089     case OPT_script:
1090       if (Optional<std::string> Path = searchScript(Arg->getValue())) {
1091         if (Optional<MemoryBufferRef> MB = readFile(*Path))
1092           readLinkerScript(*MB);
1093         break;
1094       }
1095       error(Twine("cannot find linker script ") + Arg->getValue());
1096       break;
1097     case OPT_as_needed:
1098       Config->AsNeeded = true;
1099       break;
1100     case OPT_format:
1101       Config->FormatBinary = isFormatBinary(Arg->getValue());
1102       break;
1103     case OPT_no_as_needed:
1104       Config->AsNeeded = false;
1105       break;
1106     case OPT_Bstatic:
1107       Config->Static = true;
1108       break;
1109     case OPT_Bdynamic:
1110       Config->Static = false;
1111       break;
1112     case OPT_whole_archive:
1113       InWholeArchive = true;
1114       break;
1115     case OPT_no_whole_archive:
1116       InWholeArchive = false;
1117       break;
1118     case OPT_just_symbols:
1119       if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue())) {
1120         Files.push_back(createObjectFile(*MB));
1121         Files.back()->JustSymbols = true;
1122       }
1123       break;
1124     case OPT_start_group:
1125       if (InputFile::IsInGroup)
1126         error("nested --start-group");
1127       InputFile::IsInGroup = true;
1128       break;
1129     case OPT_end_group:
1130       if (!InputFile::IsInGroup)
1131         error("stray --end-group");
1132       InputFile::IsInGroup = false;
1133       ++InputFile::NextGroupId;
1134       break;
1135     case OPT_start_lib:
1136       if (InLib)
1137         error("nested --start-lib");
1138       if (InputFile::IsInGroup)
1139         error("may not nest --start-lib in --start-group");
1140       InLib = true;
1141       InputFile::IsInGroup = true;
1142       break;
1143     case OPT_end_lib:
1144       if (!InLib)
1145         error("stray --end-lib");
1146       InLib = false;
1147       InputFile::IsInGroup = false;
1148       ++InputFile::NextGroupId;
1149       break;
1150     case OPT_push_state:
1151       Stack.emplace_back(Config->AsNeeded, Config->Static, InWholeArchive);
1152       break;
1153     case OPT_pop_state:
1154       if (Stack.empty()) {
1155         error("unbalanced --push-state/--pop-state");
1156         break;
1157       }
1158       std::tie(Config->AsNeeded, Config->Static, InWholeArchive) = Stack.back();
1159       Stack.pop_back();
1160       break;
1161     }
1162   }
1163 
1164   if (Files.empty() && errorCount() == 0)
1165     error("no input files");
1166 }
1167 
1168 // If -m <machine_type> was not given, infer it from object files.
1169 void LinkerDriver::inferMachineType() {
1170   if (Config->EKind != ELFNoneKind)
1171     return;
1172 
1173   for (InputFile *F : Files) {
1174     if (F->EKind == ELFNoneKind)
1175       continue;
1176     Config->EKind = F->EKind;
1177     Config->EMachine = F->EMachine;
1178     Config->OSABI = F->OSABI;
1179     Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
1180     return;
1181   }
1182   error("target emulation unknown: -m or at least one .o file required");
1183 }
1184 
1185 // Parse -z max-page-size=<value>. The default value is defined by
1186 // each target.
1187 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
1188   uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
1189                                        Target->DefaultMaxPageSize);
1190   if (!isPowerOf2_64(Val))
1191     error("max-page-size: value isn't a power of 2");
1192   return Val;
1193 }
1194 
1195 // Parses -image-base option.
1196 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
1197   // Because we are using "Config->MaxPageSize" here, this function has to be
1198   // called after the variable is initialized.
1199   auto *Arg = Args.getLastArg(OPT_image_base);
1200   if (!Arg)
1201     return None;
1202 
1203   StringRef S = Arg->getValue();
1204   uint64_t V;
1205   if (!to_integer(S, V)) {
1206     error("-image-base: number expected, but got " + S);
1207     return 0;
1208   }
1209   if ((V % Config->MaxPageSize) != 0)
1210     warn("-image-base: address isn't multiple of page size: " + S);
1211   return V;
1212 }
1213 
1214 // Parses `--exclude-libs=lib,lib,...`.
1215 // The library names may be delimited by commas or colons.
1216 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
1217   DenseSet<StringRef> Ret;
1218   for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
1219     StringRef S = Arg->getValue();
1220     for (;;) {
1221       size_t Pos = S.find_first_of(",:");
1222       if (Pos == StringRef::npos)
1223         break;
1224       Ret.insert(S.substr(0, Pos));
1225       S = S.substr(Pos + 1);
1226     }
1227     Ret.insert(S);
1228   }
1229   return Ret;
1230 }
1231 
1232 // Handles the -exclude-libs option. If a static library file is specified
1233 // by the -exclude-libs option, all public symbols from the archive become
1234 // private unless otherwise specified by version scripts or something.
1235 // A special library name "ALL" means all archive files.
1236 //
1237 // This is not a popular option, but some programs such as bionic libc use it.
1238 static void excludeLibs(opt::InputArgList &Args) {
1239   DenseSet<StringRef> Libs = getExcludeLibs(Args);
1240   bool All = Libs.count("ALL");
1241 
1242   auto Visit = [&](InputFile *File) {
1243     if (!File->ArchiveName.empty())
1244       if (All || Libs.count(path::filename(File->ArchiveName)))
1245         for (Symbol *Sym : File->getSymbols())
1246           if (!Sym->isLocal() && Sym->File == File)
1247             Sym->VersionId = VER_NDX_LOCAL;
1248   };
1249 
1250   for (InputFile *File : ObjectFiles)
1251     Visit(File);
1252 
1253   for (BitcodeFile *File : BitcodeFiles)
1254     Visit(File);
1255 }
1256 
1257 // Force Sym to be entered in the output. Used for -u or equivalent.
1258 template <class ELFT> static void handleUndefined(StringRef Name) {
1259   Symbol *Sym = Symtab->find(Name);
1260   if (!Sym)
1261     return;
1262 
1263   // Since symbol S may not be used inside the program, LTO may
1264   // eliminate it. Mark the symbol as "used" to prevent it.
1265   Sym->IsUsedInRegularObj = true;
1266 
1267   if (Sym->isLazy())
1268     Symtab->fetchLazy<ELFT>(Sym);
1269 }
1270 
1271 template <class ELFT> static void handleLibcall(StringRef Name) {
1272   Symbol *Sym = Symtab->find(Name);
1273   if (!Sym || !Sym->isLazy())
1274     return;
1275 
1276   MemoryBufferRef MB;
1277   if (auto *LO = dyn_cast<LazyObject>(Sym))
1278     MB = LO->File->MB;
1279   else
1280     MB = cast<LazyArchive>(Sym)->getMemberBuffer();
1281 
1282   if (isBitcode(MB))
1283     Symtab->fetchLazy<ELFT>(Sym);
1284 }
1285 
1286 // If all references to a DSO happen to be weak, the DSO is not added
1287 // to DT_NEEDED. If that happens, we need to eliminate shared symbols
1288 // created from the DSO. Otherwise, they become dangling references
1289 // that point to a non-existent DSO.
1290 template <class ELFT> static void demoteSharedSymbols() {
1291   for (Symbol *Sym : Symtab->getSymbols()) {
1292     if (auto *S = dyn_cast<SharedSymbol>(Sym)) {
1293       if (!S->getFile<ELFT>().IsNeeded) {
1294         bool Used = S->Used;
1295         replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_WEAK, S->StOther,
1296                                  S->Type);
1297         S->Used = Used;
1298       }
1299     }
1300   }
1301 }
1302 
1303 // The section referred to by S is considered address-significant. Set the
1304 // KeepUnique flag on the section if appropriate.
1305 static void markAddrsig(Symbol *S) {
1306   if (auto *D = dyn_cast_or_null<Defined>(S))
1307     if (D->Section)
1308       // We don't need to keep text sections unique under --icf=all even if they
1309       // are address-significant.
1310       if (Config->ICF == ICFLevel::Safe || !(D->Section->Flags & SHF_EXECINSTR))
1311         D->Section->KeepUnique = true;
1312 }
1313 
1314 // Record sections that define symbols mentioned in --keep-unique <symbol>
1315 // and symbols referred to by address-significance tables. These sections are
1316 // ineligible for ICF.
1317 template <class ELFT>
1318 static void findKeepUniqueSections(opt::InputArgList &Args) {
1319   for (auto *Arg : Args.filtered(OPT_keep_unique)) {
1320     StringRef Name = Arg->getValue();
1321     auto *D = dyn_cast_or_null<Defined>(Symtab->find(Name));
1322     if (!D || !D->Section) {
1323       warn("could not find symbol " + Name + " to keep unique");
1324       continue;
1325     }
1326     D->Section->KeepUnique = true;
1327   }
1328 
1329   // --icf=all --ignore-data-address-equality means that we can ignore
1330   // the dynsym and address-significance tables entirely.
1331   if (Config->ICF == ICFLevel::All && Config->IgnoreDataAddressEquality)
1332     return;
1333 
1334   // Symbols in the dynsym could be address-significant in other executables
1335   // or DSOs, so we conservatively mark them as address-significant.
1336   for (Symbol *S : Symtab->getSymbols())
1337     if (S->includeInDynsym())
1338       markAddrsig(S);
1339 
1340   // Visit the address-significance table in each object file and mark each
1341   // referenced symbol as address-significant.
1342   for (InputFile *F : ObjectFiles) {
1343     auto *Obj = cast<ObjFile<ELFT>>(F);
1344     ArrayRef<Symbol *> Syms = Obj->getSymbols();
1345     if (Obj->AddrsigSec) {
1346       ArrayRef<uint8_t> Contents =
1347           check(Obj->getObj().getSectionContents(Obj->AddrsigSec));
1348       const uint8_t *Cur = Contents.begin();
1349       while (Cur != Contents.end()) {
1350         unsigned Size;
1351         const char *Err;
1352         uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
1353         if (Err)
1354           fatal(toString(F) + ": could not decode addrsig section: " + Err);
1355         markAddrsig(Syms[SymIndex]);
1356         Cur += Size;
1357       }
1358     } else {
1359       // If an object file does not have an address-significance table,
1360       // conservatively mark all of its symbols as address-significant.
1361       for (Symbol *S : Syms)
1362         markAddrsig(S);
1363     }
1364   }
1365 }
1366 
1367 template <class ELFT> static Symbol *addUndefined(StringRef Name) {
1368   return Symtab->addUndefined<ELFT>(Name, STB_GLOBAL, STV_DEFAULT, 0, false,
1369                                     nullptr);
1370 }
1371 
1372 // The --wrap option is a feature to rename symbols so that you can write
1373 // wrappers for existing functions. If you pass `-wrap=foo`, all
1374 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1375 // expected to write `wrap_foo` function as a wrapper). The original
1376 // symbol becomes accessible as `real_foo`, so you can call that from your
1377 // wrapper.
1378 //
1379 // This data structure is instantiated for each -wrap option.
1380 struct WrappedSymbol {
1381   Symbol *Sym;
1382   Symbol *Real;
1383   Symbol *Wrap;
1384 };
1385 
1386 // Handles -wrap option.
1387 //
1388 // This function instantiates wrapper symbols. At this point, they seem
1389 // like they are not being used at all, so we explicitly set some flags so
1390 // that LTO won't eliminate them.
1391 template <class ELFT>
1392 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &Args) {
1393   std::vector<WrappedSymbol> V;
1394   DenseSet<StringRef> Seen;
1395 
1396   for (auto *Arg : Args.filtered(OPT_wrap)) {
1397     StringRef Name = Arg->getValue();
1398     if (!Seen.insert(Name).second)
1399       continue;
1400 
1401     Symbol *Sym = Symtab->find(Name);
1402     if (!Sym)
1403       continue;
1404 
1405     Symbol *Real = addUndefined<ELFT>(Saver.save("__real_" + Name));
1406     Symbol *Wrap = addUndefined<ELFT>(Saver.save("__wrap_" + Name));
1407     V.push_back({Sym, Real, Wrap});
1408 
1409     // We want to tell LTO not to inline symbols to be overwritten
1410     // because LTO doesn't know the final symbol contents after renaming.
1411     Real->CanInline = false;
1412     Sym->CanInline = false;
1413 
1414     // Tell LTO not to eliminate these symbols.
1415     Sym->IsUsedInRegularObj = true;
1416     Wrap->IsUsedInRegularObj = true;
1417   }
1418   return V;
1419 }
1420 
1421 // Do renaming for -wrap by updating pointers to symbols.
1422 //
1423 // When this function is executed, only InputFiles and symbol table
1424 // contain pointers to symbol objects. We visit them to replace pointers,
1425 // so that wrapped symbols are swapped as instructed by the command line.
1426 static void wrapSymbols(ArrayRef<WrappedSymbol> Wrapped) {
1427   DenseMap<Symbol *, Symbol *> Map;
1428   for (const WrappedSymbol &W : Wrapped) {
1429     Map[W.Sym] = W.Wrap;
1430     Map[W.Real] = W.Sym;
1431   }
1432 
1433   // Update pointers in input files.
1434   parallelForEach(ObjectFiles, [&](InputFile *File) {
1435     std::vector<Symbol *> &Syms = File->getMutableSymbols();
1436     for (size_t I = 0, E = Syms.size(); I != E; ++I)
1437       if (Symbol *S = Map.lookup(Syms[I]))
1438         Syms[I] = S;
1439   });
1440 
1441   // Update pointers in the symbol table.
1442   for (const WrappedSymbol &W : Wrapped)
1443     Symtab->wrap(W.Sym, W.Real, W.Wrap);
1444 }
1445 
1446 static const char *LibcallRoutineNames[] = {
1447 #define HANDLE_LIBCALL(code, name) name,
1448 #include "llvm/IR/RuntimeLibcalls.def"
1449 #undef HANDLE_LIBCALL
1450 };
1451 
1452 // Do actual linking. Note that when this function is called,
1453 // all linker scripts have already been parsed.
1454 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1455   Target = getTarget();
1456 
1457   Config->MaxPageSize = getMaxPageSize(Args);
1458   Config->ImageBase = getImageBase(Args);
1459 
1460   // If a -hash-style option was not given, set to a default value,
1461   // which varies depending on the target.
1462   if (!Args.hasArg(OPT_hash_style)) {
1463     if (Config->EMachine == EM_MIPS)
1464       Config->SysvHash = true;
1465     else
1466       Config->SysvHash = Config->GnuHash = true;
1467   }
1468 
1469   // Default output filename is "a.out" by the Unix tradition.
1470   if (Config->OutputFile.empty())
1471     Config->OutputFile = "a.out";
1472 
1473   // Fail early if the output file or map file is not writable. If a user has a
1474   // long link, e.g. due to a large LTO link, they do not wish to run it and
1475   // find that it failed because there was a mistake in their command-line.
1476   if (auto E = tryCreateFile(Config->OutputFile))
1477     error("cannot open output file " + Config->OutputFile + ": " + E.message());
1478   if (auto E = tryCreateFile(Config->MapFile))
1479     error("cannot open map file " + Config->MapFile + ": " + E.message());
1480   if (errorCount())
1481     return;
1482 
1483   // Use default entry point name if no name was given via the command
1484   // line nor linker scripts. For some reason, MIPS entry point name is
1485   // different from others.
1486   Config->WarnMissingEntry =
1487       (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
1488   if (Config->Entry.empty() && !Config->Relocatable)
1489     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
1490 
1491   // Handle --trace-symbol.
1492   for (auto *Arg : Args.filtered(OPT_trace_symbol))
1493     Symtab->trace(Arg->getValue());
1494 
1495   // Add all files to the symbol table. This will add almost all
1496   // symbols that we need to the symbol table.
1497   for (InputFile *F : Files)
1498     Symtab->addFile<ELFT>(F);
1499 
1500   // Now that we have every file, we can decide if we will need a
1501   // dynamic symbol table.
1502   // We need one if we were asked to export dynamic symbols or if we are
1503   // producing a shared library.
1504   // We also need one if any shared libraries are used and for pie executables
1505   // (probably because the dynamic linker needs it).
1506   Config->HasDynSymTab =
1507       !SharedFiles.empty() || Config->Pic || Config->ExportDynamic;
1508 
1509   // Some symbols (such as __ehdr_start) are defined lazily only when there
1510   // are undefined symbols for them, so we add these to trigger that logic.
1511   for (StringRef Name : Script->ReferencedSymbols)
1512     addUndefined<ELFT>(Name);
1513 
1514   // Handle the `--undefined <sym>` options.
1515   for (StringRef S : Config->Undefined)
1516     handleUndefined<ELFT>(S);
1517 
1518   // If an entry symbol is in a static archive, pull out that file now.
1519   handleUndefined<ELFT>(Config->Entry);
1520 
1521   // If any of our inputs are bitcode files, the LTO code generator may create
1522   // references to certain library functions that might not be explicit in the
1523   // bitcode file's symbol table. If any of those library functions are defined
1524   // in a bitcode file in an archive member, we need to arrange to use LTO to
1525   // compile those archive members by adding them to the link beforehand.
1526   //
1527   // However, adding all libcall symbols to the link can have undesired
1528   // consequences. For example, the libgcc implementation of
1529   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1530   // that aborts the program if the Linux kernel does not support 64-bit
1531   // atomics, which would prevent the program from running even if it does not
1532   // use 64-bit atomics.
1533   //
1534   // Therefore, we only add libcall symbols to the link before LTO if we have
1535   // to, i.e. if the symbol's definition is in bitcode. Any other required
1536   // libcall symbols will be added to the link after LTO when we add the LTO
1537   // object file to the link.
1538   if (!BitcodeFiles.empty())
1539     for (const char *S : LibcallRoutineNames)
1540       handleLibcall<ELFT>(S);
1541 
1542   // Return if there were name resolution errors.
1543   if (errorCount())
1544     return;
1545 
1546   // Now when we read all script files, we want to finalize order of linker
1547   // script commands, which can be not yet final because of INSERT commands.
1548   Script->processInsertCommands();
1549 
1550   // We want to declare linker script's symbols early,
1551   // so that we can version them.
1552   // They also might be exported if referenced by DSOs.
1553   Script->declareSymbols();
1554 
1555   // Handle the -exclude-libs option.
1556   if (Args.hasArg(OPT_exclude_libs))
1557     excludeLibs(Args);
1558 
1559   // Create ElfHeader early. We need a dummy section in
1560   // addReservedSymbols to mark the created symbols as not absolute.
1561   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1562   Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1563 
1564   // Create wrapped symbols for -wrap option.
1565   std::vector<WrappedSymbol> Wrapped = addWrappedSymbols<ELFT>(Args);
1566 
1567   // We need to create some reserved symbols such as _end. Create them.
1568   if (!Config->Relocatable)
1569     addReservedSymbols();
1570 
1571   // Apply version scripts.
1572   //
1573   // For a relocatable output, version scripts don't make sense, and
1574   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1575   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1576   if (!Config->Relocatable)
1577     Symtab->scanVersionScript();
1578 
1579   // Do link-time optimization if given files are LLVM bitcode files.
1580   // This compiles bitcode files into real object files.
1581   //
1582   // With this the symbol table should be complete. After this, no new names
1583   // except a few linker-synthesized ones will be added to the symbol table.
1584   Symtab->addCombinedLTOObject<ELFT>();
1585   if (errorCount())
1586     return;
1587 
1588   // If -thinlto-index-only is given, we should create only "index
1589   // files" and not object files. Index file creation is already done
1590   // in addCombinedLTOObject, so we are done if that's the case.
1591   if (Config->ThinLTOIndexOnly)
1592     return;
1593 
1594   // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1595   // an output file in bitcode and exit, so that you can just get a
1596   // combined bitcode file.
1597   if (Config->EmitLLVM)
1598     return;
1599 
1600   // Apply symbol renames for -wrap.
1601   if (!Wrapped.empty())
1602     wrapSymbols(Wrapped);
1603 
1604   // Now that we have a complete list of input files.
1605   // Beyond this point, no new files are added.
1606   // Aggregate all input sections into one place.
1607   for (InputFile *F : ObjectFiles)
1608     for (InputSectionBase *S : F->getSections())
1609       if (S && S != &InputSection::Discarded)
1610         InputSections.push_back(S);
1611   for (BinaryFile *F : BinaryFiles)
1612     for (InputSectionBase *S : F->getSections())
1613       InputSections.push_back(cast<InputSection>(S));
1614 
1615   // We do not want to emit debug sections if --strip-all
1616   // or -strip-debug are given.
1617   if (Config->Strip != StripPolicy::None)
1618     llvm::erase_if(InputSections, [](InputSectionBase *S) {
1619       return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1620     });
1621 
1622   Config->EFlags = Target->calcEFlags();
1623 
1624   if (Config->EMachine == EM_ARM) {
1625     // FIXME: These warnings can be removed when lld only uses these features
1626     // when the input objects have been compiled with an architecture that
1627     // supports them.
1628     if (Config->ARMHasBlx == false)
1629       warn("lld uses blx instruction, no object with architecture supporting "
1630            "feature detected");
1631   }
1632 
1633   // This adds a .comment section containing a version string. We have to add it
1634   // before mergeSections because the .comment section is a mergeable section.
1635   if (!Config->Relocatable)
1636     InputSections.push_back(createCommentSection());
1637 
1638   // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1639   // and identical code folding.
1640   splitSections<ELFT>();
1641   markLive<ELFT>();
1642   demoteSharedSymbols<ELFT>();
1643   mergeSections();
1644   if (Config->ICF != ICFLevel::None) {
1645     findKeepUniqueSections<ELFT>(Args);
1646     doIcf<ELFT>();
1647   }
1648 
1649   // Read the callgraph now that we know what was gced or icfed
1650   if (Config->CallGraphProfileSort) {
1651     if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1652       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1653         readCallGraph(*Buffer);
1654     readCallGraphsFromObjectFiles<ELFT>();
1655   }
1656 
1657   // Write the result to the file.
1658   writeResult<ELFT>();
1659 }
1660