xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 4c1581e2)
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->PrintSymbolOrder =
840       Args.getLastArgValue(OPT_print_symbol_order);
841   Config->Rpath = getRpath(Args);
842   Config->Relocatable = Args.hasArg(OPT_relocatable);
843   Config->SaveTemps = Args.hasArg(OPT_save_temps);
844   Config->SearchPaths = args::getStrings(Args, OPT_library_path);
845   Config->SectionStartMap = getSectionStartMap(Args);
846   Config->Shared = Args.hasArg(OPT_shared);
847   Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
848   Config->SoName = Args.getLastArgValue(OPT_soname);
849   Config->SortSection = getSortSection(Args);
850   Config->SplitStackAdjustSize = args::getInteger(Args, OPT_split_stack_adjust_size, 16384);
851   Config->Strip = getStrip(Args);
852   Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
853   Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
854   Config->Target2 = getTarget2(Args);
855   Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
856   Config->ThinLTOCachePolicy = CHECK(
857       parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
858       "--thinlto-cache-policy: invalid cache policy");
859   Config->ThinLTOEmitImportsFiles =
860       Args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files);
861   Config->ThinLTOIndexOnly = Args.hasArg(OPT_plugin_opt_thinlto_index_only) ||
862                              Args.hasArg(OPT_plugin_opt_thinlto_index_only_eq);
863   Config->ThinLTOIndexOnlyArg =
864       Args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq);
865   Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
866   Config->ThinLTOObjectSuffixReplace =
867       getOldNewOptions(Args, OPT_plugin_opt_thinlto_object_suffix_replace_eq);
868   Config->ThinLTOPrefixReplace =
869       getOldNewOptions(Args, OPT_plugin_opt_thinlto_prefix_replace_eq);
870   Config->Trace = Args.hasArg(OPT_trace);
871   Config->Undefined = args::getStrings(Args, OPT_undefined);
872   Config->UndefinedVersion =
873       Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
874   Config->UseAndroidRelrTags = Args.hasFlag(
875       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
876   Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
877   Config->WarnBackrefs =
878       Args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
879   Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
880   Config->WarnIfuncTextrel =
881       Args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
882   Config->WarnSymbolOrdering =
883       Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
884   Config->ZCombreloc = getZFlag(Args, "combreloc", "nocombreloc", true);
885   Config->ZCopyreloc = getZFlag(Args, "copyreloc", "nocopyreloc", true);
886   Config->ZExecstack = getZFlag(Args, "execstack", "noexecstack", false);
887   Config->ZGlobal = hasZOption(Args, "global");
888   Config->ZHazardplt = hasZOption(Args, "hazardplt");
889   Config->ZInitfirst = hasZOption(Args, "initfirst");
890   Config->ZInterpose = hasZOption(Args, "interpose");
891   Config->ZKeepTextSectionPrefix = getZFlag(
892       Args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
893   Config->ZNodefaultlib = hasZOption(Args, "nodefaultlib");
894   Config->ZNodelete = hasZOption(Args, "nodelete");
895   Config->ZNodlopen = hasZOption(Args, "nodlopen");
896   Config->ZNow = getZFlag(Args, "now", "lazy", false);
897   Config->ZOrigin = hasZOption(Args, "origin");
898   Config->ZRelro = getZFlag(Args, "relro", "norelro", true);
899   Config->ZRetpolineplt = hasZOption(Args, "retpolineplt");
900   Config->ZRodynamic = hasZOption(Args, "rodynamic");
901   Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
902   Config->ZText = getZFlag(Args, "text", "notext", true);
903   Config->ZWxneeded = hasZOption(Args, "wxneeded");
904 
905   // Parse LTO options.
906   if (auto *Arg = Args.getLastArg(OPT_plugin_opt_mcpu_eq))
907     parseClangOption(Saver.save("-mcpu=" + StringRef(Arg->getValue())),
908                      Arg->getSpelling());
909 
910   for (auto *Arg : Args.filtered(OPT_plugin_opt))
911     parseClangOption(Arg->getValue(), Arg->getSpelling());
912 
913   // Parse -mllvm options.
914   for (auto *Arg : Args.filtered(OPT_mllvm))
915     parseClangOption(Arg->getValue(), Arg->getSpelling());
916 
917   if (Config->LTOO > 3)
918     error("invalid optimization level for LTO: " + Twine(Config->LTOO));
919   if (Config->LTOPartitions == 0)
920     error("--lto-partitions: number of threads must be > 0");
921   if (Config->ThinLTOJobs == 0)
922     error("--thinlto-jobs: number of threads must be > 0");
923 
924   if (Config->SplitStackAdjustSize < 0)
925     error("--split-stack-adjust-size: size must be >= 0");
926 
927   // Parse ELF{32,64}{LE,BE} and CPU type.
928   if (auto *Arg = Args.getLastArg(OPT_m)) {
929     StringRef S = Arg->getValue();
930     std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
931         parseEmulation(S);
932     Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
933     Config->Emulation = S;
934   }
935 
936   // Parse -hash-style={sysv,gnu,both}.
937   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
938     StringRef S = Arg->getValue();
939     if (S == "sysv")
940       Config->SysvHash = true;
941     else if (S == "gnu")
942       Config->GnuHash = true;
943     else if (S == "both")
944       Config->SysvHash = Config->GnuHash = true;
945     else
946       error("unknown -hash-style: " + S);
947   }
948 
949   if (Args.hasArg(OPT_print_map))
950     Config->MapFile = "-";
951 
952   // --omagic is an option to create old-fashioned executables in which
953   // .text segments are writable. Today, the option is still in use to
954   // create special-purpose programs such as boot loaders. It doesn't
955   // make sense to create PT_GNU_RELRO for such executables.
956   if (Config->Omagic)
957     Config->ZRelro = false;
958 
959   std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
960 
961   std::tie(Config->AndroidPackDynRelocs, Config->RelrPackDynRelocs) =
962       getPackDynRelocs(Args);
963 
964   if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
965     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
966       Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer);
967 
968   // If --retain-symbol-file is used, we'll keep only the symbols listed in
969   // the file and discard all others.
970   if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
971     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
972     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
973       for (StringRef S : args::getLines(*Buffer))
974         Config->VersionScriptGlobals.push_back(
975             {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
976   }
977 
978   bool HasExportDynamic =
979       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
980 
981   // Parses -dynamic-list and -export-dynamic-symbol. They make some
982   // symbols private. Note that -export-dynamic takes precedence over them
983   // as it says all symbols should be exported.
984   if (!HasExportDynamic) {
985     for (auto *Arg : Args.filtered(OPT_dynamic_list))
986       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
987         readDynamicList(*Buffer);
988 
989     for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
990       Config->DynamicList.push_back(
991           {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
992   }
993 
994   // If --export-dynamic-symbol=foo is given and symbol foo is defined in
995   // an object file in an archive file, that object file should be pulled
996   // out and linked. (It doesn't have to behave like that from technical
997   // point of view, but this is needed for compatibility with GNU.)
998   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
999     Config->Undefined.push_back(Arg->getValue());
1000 
1001   for (auto *Arg : Args.filtered(OPT_version_script))
1002     if (Optional<std::string> Path = searchScript(Arg->getValue())) {
1003       if (Optional<MemoryBufferRef> Buffer = readFile(*Path))
1004         readVersionScript(*Buffer);
1005     } else {
1006       error(Twine("cannot find version script ") + Arg->getValue());
1007     }
1008 }
1009 
1010 // Some Config members do not directly correspond to any particular
1011 // command line options, but computed based on other Config values.
1012 // This function initialize such members. See Config.h for the details
1013 // of these values.
1014 static void setConfigs(opt::InputArgList &Args) {
1015   ELFKind K = Config->EKind;
1016   uint16_t M = Config->EMachine;
1017 
1018   Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
1019   Config->Is64 = (K == ELF64LEKind || K == ELF64BEKind);
1020   Config->IsLE = (K == ELF32LEKind || K == ELF64LEKind);
1021   Config->Endianness = Config->IsLE ? endianness::little : endianness::big;
1022   Config->IsMips64EL = (K == ELF64LEKind && M == EM_MIPS);
1023   Config->Pic = Config->Pie || Config->Shared;
1024   Config->PicThunk = Args.hasArg(OPT_pic_veneer, Config->Pic);
1025   Config->Wordsize = Config->Is64 ? 8 : 4;
1026 
1027   // ELF defines two different ways to store relocation addends as shown below:
1028   //
1029   //  Rel:  Addends are stored to the location where relocations are applied.
1030   //  Rela: Addends are stored as part of relocation entry.
1031   //
1032   // In other words, Rela makes it easy to read addends at the price of extra
1033   // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
1034   // different mechanisms in the first place, but this is how the spec is
1035   // defined.
1036   //
1037   // You cannot choose which one, Rel or Rela, you want to use. Instead each
1038   // ABI defines which one you need to use. The following expression expresses
1039   // that.
1040   Config->IsRela = M == EM_AARCH64 || M == EM_AMDGPU || M == EM_HEXAGON ||
1041                    M == EM_PPC || M == EM_PPC64 || M == EM_RISCV ||
1042                    M == EM_X86_64;
1043 
1044   // If the output uses REL relocations we must store the dynamic relocation
1045   // addends to the output sections. We also store addends for RELA relocations
1046   // if --apply-dynamic-relocs is used.
1047   // We default to not writing the addends when using RELA relocations since
1048   // any standard conforming tool can find it in r_addend.
1049   Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs,
1050                                       OPT_no_apply_dynamic_relocs, false) ||
1051                          !Config->IsRela;
1052 
1053   Config->TocOptimize =
1054       Args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, M == EM_PPC64);
1055 }
1056 
1057 // Returns a value of "-format" option.
1058 static bool isFormatBinary(StringRef S) {
1059   if (S == "binary")
1060     return true;
1061   if (S == "elf" || S == "default")
1062     return false;
1063   error("unknown -format value: " + S +
1064         " (supported formats: elf, default, binary)");
1065   return false;
1066 }
1067 
1068 void LinkerDriver::createFiles(opt::InputArgList &Args) {
1069   // For --{push,pop}-state.
1070   std::vector<std::tuple<bool, bool, bool>> Stack;
1071 
1072   // Iterate over argv to process input files and positional arguments.
1073   for (auto *Arg : Args) {
1074     switch (Arg->getOption().getUnaliasedOption().getID()) {
1075     case OPT_library:
1076       addLibrary(Arg->getValue());
1077       break;
1078     case OPT_INPUT:
1079       addFile(Arg->getValue(), /*WithLOption=*/false);
1080       break;
1081     case OPT_defsym: {
1082       StringRef From;
1083       StringRef To;
1084       std::tie(From, To) = StringRef(Arg->getValue()).split('=');
1085       if (From.empty() || To.empty())
1086         error("-defsym: syntax error: " + StringRef(Arg->getValue()));
1087       else
1088         readDefsym(From, MemoryBufferRef(To, "-defsym"));
1089       break;
1090     }
1091     case OPT_script:
1092       if (Optional<std::string> Path = searchScript(Arg->getValue())) {
1093         if (Optional<MemoryBufferRef> MB = readFile(*Path))
1094           readLinkerScript(*MB);
1095         break;
1096       }
1097       error(Twine("cannot find linker script ") + Arg->getValue());
1098       break;
1099     case OPT_as_needed:
1100       Config->AsNeeded = true;
1101       break;
1102     case OPT_format:
1103       Config->FormatBinary = isFormatBinary(Arg->getValue());
1104       break;
1105     case OPT_no_as_needed:
1106       Config->AsNeeded = false;
1107       break;
1108     case OPT_Bstatic:
1109       Config->Static = true;
1110       break;
1111     case OPT_Bdynamic:
1112       Config->Static = false;
1113       break;
1114     case OPT_whole_archive:
1115       InWholeArchive = true;
1116       break;
1117     case OPT_no_whole_archive:
1118       InWholeArchive = false;
1119       break;
1120     case OPT_just_symbols:
1121       if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue())) {
1122         Files.push_back(createObjectFile(*MB));
1123         Files.back()->JustSymbols = true;
1124       }
1125       break;
1126     case OPT_start_group:
1127       if (InputFile::IsInGroup)
1128         error("nested --start-group");
1129       InputFile::IsInGroup = true;
1130       break;
1131     case OPT_end_group:
1132       if (!InputFile::IsInGroup)
1133         error("stray --end-group");
1134       InputFile::IsInGroup = false;
1135       ++InputFile::NextGroupId;
1136       break;
1137     case OPT_start_lib:
1138       if (InLib)
1139         error("nested --start-lib");
1140       if (InputFile::IsInGroup)
1141         error("may not nest --start-lib in --start-group");
1142       InLib = true;
1143       InputFile::IsInGroup = true;
1144       break;
1145     case OPT_end_lib:
1146       if (!InLib)
1147         error("stray --end-lib");
1148       InLib = false;
1149       InputFile::IsInGroup = false;
1150       ++InputFile::NextGroupId;
1151       break;
1152     case OPT_push_state:
1153       Stack.emplace_back(Config->AsNeeded, Config->Static, InWholeArchive);
1154       break;
1155     case OPT_pop_state:
1156       if (Stack.empty()) {
1157         error("unbalanced --push-state/--pop-state");
1158         break;
1159       }
1160       std::tie(Config->AsNeeded, Config->Static, InWholeArchive) = Stack.back();
1161       Stack.pop_back();
1162       break;
1163     }
1164   }
1165 
1166   if (Files.empty() && errorCount() == 0)
1167     error("no input files");
1168 }
1169 
1170 // If -m <machine_type> was not given, infer it from object files.
1171 void LinkerDriver::inferMachineType() {
1172   if (Config->EKind != ELFNoneKind)
1173     return;
1174 
1175   for (InputFile *F : Files) {
1176     if (F->EKind == ELFNoneKind)
1177       continue;
1178     Config->EKind = F->EKind;
1179     Config->EMachine = F->EMachine;
1180     Config->OSABI = F->OSABI;
1181     Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
1182     return;
1183   }
1184   error("target emulation unknown: -m or at least one .o file required");
1185 }
1186 
1187 // Parse -z max-page-size=<value>. The default value is defined by
1188 // each target.
1189 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
1190   uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
1191                                        Target->DefaultMaxPageSize);
1192   if (!isPowerOf2_64(Val))
1193     error("max-page-size: value isn't a power of 2");
1194   return Val;
1195 }
1196 
1197 // Parses -image-base option.
1198 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
1199   // Because we are using "Config->MaxPageSize" here, this function has to be
1200   // called after the variable is initialized.
1201   auto *Arg = Args.getLastArg(OPT_image_base);
1202   if (!Arg)
1203     return None;
1204 
1205   StringRef S = Arg->getValue();
1206   uint64_t V;
1207   if (!to_integer(S, V)) {
1208     error("-image-base: number expected, but got " + S);
1209     return 0;
1210   }
1211   if ((V % Config->MaxPageSize) != 0)
1212     warn("-image-base: address isn't multiple of page size: " + S);
1213   return V;
1214 }
1215 
1216 // Parses `--exclude-libs=lib,lib,...`.
1217 // The library names may be delimited by commas or colons.
1218 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
1219   DenseSet<StringRef> Ret;
1220   for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
1221     StringRef S = Arg->getValue();
1222     for (;;) {
1223       size_t Pos = S.find_first_of(",:");
1224       if (Pos == StringRef::npos)
1225         break;
1226       Ret.insert(S.substr(0, Pos));
1227       S = S.substr(Pos + 1);
1228     }
1229     Ret.insert(S);
1230   }
1231   return Ret;
1232 }
1233 
1234 // Handles the -exclude-libs option. If a static library file is specified
1235 // by the -exclude-libs option, all public symbols from the archive become
1236 // private unless otherwise specified by version scripts or something.
1237 // A special library name "ALL" means all archive files.
1238 //
1239 // This is not a popular option, but some programs such as bionic libc use it.
1240 static void excludeLibs(opt::InputArgList &Args) {
1241   DenseSet<StringRef> Libs = getExcludeLibs(Args);
1242   bool All = Libs.count("ALL");
1243 
1244   auto Visit = [&](InputFile *File) {
1245     if (!File->ArchiveName.empty())
1246       if (All || Libs.count(path::filename(File->ArchiveName)))
1247         for (Symbol *Sym : File->getSymbols())
1248           if (!Sym->isLocal() && Sym->File == File)
1249             Sym->VersionId = VER_NDX_LOCAL;
1250   };
1251 
1252   for (InputFile *File : ObjectFiles)
1253     Visit(File);
1254 
1255   for (BitcodeFile *File : BitcodeFiles)
1256     Visit(File);
1257 }
1258 
1259 // Force Sym to be entered in the output. Used for -u or equivalent.
1260 template <class ELFT> static void handleUndefined(StringRef Name) {
1261   Symbol *Sym = Symtab->find(Name);
1262   if (!Sym)
1263     return;
1264 
1265   // Since symbol S may not be used inside the program, LTO may
1266   // eliminate it. Mark the symbol as "used" to prevent it.
1267   Sym->IsUsedInRegularObj = true;
1268 
1269   if (Sym->isLazy())
1270     Symtab->fetchLazy<ELFT>(Sym);
1271 }
1272 
1273 template <class ELFT> static void handleLibcall(StringRef Name) {
1274   Symbol *Sym = Symtab->find(Name);
1275   if (!Sym || !Sym->isLazy())
1276     return;
1277 
1278   MemoryBufferRef MB;
1279   if (auto *LO = dyn_cast<LazyObject>(Sym))
1280     MB = LO->File->MB;
1281   else
1282     MB = cast<LazyArchive>(Sym)->getMemberBuffer();
1283 
1284   if (isBitcode(MB))
1285     Symtab->fetchLazy<ELFT>(Sym);
1286 }
1287 
1288 // If all references to a DSO happen to be weak, the DSO is not added
1289 // to DT_NEEDED. If that happens, we need to eliminate shared symbols
1290 // created from the DSO. Otherwise, they become dangling references
1291 // that point to a non-existent DSO.
1292 template <class ELFT> static void demoteSharedSymbols() {
1293   for (Symbol *Sym : Symtab->getSymbols()) {
1294     if (auto *S = dyn_cast<SharedSymbol>(Sym)) {
1295       if (!S->getFile<ELFT>().IsNeeded) {
1296         bool Used = S->Used;
1297         replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_WEAK, S->StOther,
1298                                  S->Type);
1299         S->Used = Used;
1300       }
1301     }
1302   }
1303 }
1304 
1305 // The section referred to by S is considered address-significant. Set the
1306 // KeepUnique flag on the section if appropriate.
1307 static void markAddrsig(Symbol *S) {
1308   if (auto *D = dyn_cast_or_null<Defined>(S))
1309     if (D->Section)
1310       // We don't need to keep text sections unique under --icf=all even if they
1311       // are address-significant.
1312       if (Config->ICF == ICFLevel::Safe || !(D->Section->Flags & SHF_EXECINSTR))
1313         D->Section->KeepUnique = true;
1314 }
1315 
1316 // Record sections that define symbols mentioned in --keep-unique <symbol>
1317 // and symbols referred to by address-significance tables. These sections are
1318 // ineligible for ICF.
1319 template <class ELFT>
1320 static void findKeepUniqueSections(opt::InputArgList &Args) {
1321   for (auto *Arg : Args.filtered(OPT_keep_unique)) {
1322     StringRef Name = Arg->getValue();
1323     auto *D = dyn_cast_or_null<Defined>(Symtab->find(Name));
1324     if (!D || !D->Section) {
1325       warn("could not find symbol " + Name + " to keep unique");
1326       continue;
1327     }
1328     D->Section->KeepUnique = true;
1329   }
1330 
1331   // --icf=all --ignore-data-address-equality means that we can ignore
1332   // the dynsym and address-significance tables entirely.
1333   if (Config->ICF == ICFLevel::All && Config->IgnoreDataAddressEquality)
1334     return;
1335 
1336   // Symbols in the dynsym could be address-significant in other executables
1337   // or DSOs, so we conservatively mark them as address-significant.
1338   for (Symbol *S : Symtab->getSymbols())
1339     if (S->includeInDynsym())
1340       markAddrsig(S);
1341 
1342   // Visit the address-significance table in each object file and mark each
1343   // referenced symbol as address-significant.
1344   for (InputFile *F : ObjectFiles) {
1345     auto *Obj = cast<ObjFile<ELFT>>(F);
1346     ArrayRef<Symbol *> Syms = Obj->getSymbols();
1347     if (Obj->AddrsigSec) {
1348       ArrayRef<uint8_t> Contents =
1349           check(Obj->getObj().getSectionContents(Obj->AddrsigSec));
1350       const uint8_t *Cur = Contents.begin();
1351       while (Cur != Contents.end()) {
1352         unsigned Size;
1353         const char *Err;
1354         uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
1355         if (Err)
1356           fatal(toString(F) + ": could not decode addrsig section: " + Err);
1357         markAddrsig(Syms[SymIndex]);
1358         Cur += Size;
1359       }
1360     } else {
1361       // If an object file does not have an address-significance table,
1362       // conservatively mark all of its symbols as address-significant.
1363       for (Symbol *S : Syms)
1364         markAddrsig(S);
1365     }
1366   }
1367 }
1368 
1369 template <class ELFT> static Symbol *addUndefined(StringRef Name) {
1370   return Symtab->addUndefined<ELFT>(Name, STB_GLOBAL, STV_DEFAULT, 0, false,
1371                                     nullptr);
1372 }
1373 
1374 // The --wrap option is a feature to rename symbols so that you can write
1375 // wrappers for existing functions. If you pass `-wrap=foo`, all
1376 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1377 // expected to write `wrap_foo` function as a wrapper). The original
1378 // symbol becomes accessible as `real_foo`, so you can call that from your
1379 // wrapper.
1380 //
1381 // This data structure is instantiated for each -wrap option.
1382 struct WrappedSymbol {
1383   Symbol *Sym;
1384   Symbol *Real;
1385   Symbol *Wrap;
1386 };
1387 
1388 // Handles -wrap option.
1389 //
1390 // This function instantiates wrapper symbols. At this point, they seem
1391 // like they are not being used at all, so we explicitly set some flags so
1392 // that LTO won't eliminate them.
1393 template <class ELFT>
1394 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &Args) {
1395   std::vector<WrappedSymbol> V;
1396   DenseSet<StringRef> Seen;
1397 
1398   for (auto *Arg : Args.filtered(OPT_wrap)) {
1399     StringRef Name = Arg->getValue();
1400     if (!Seen.insert(Name).second)
1401       continue;
1402 
1403     Symbol *Sym = Symtab->find(Name);
1404     if (!Sym)
1405       continue;
1406 
1407     Symbol *Real = addUndefined<ELFT>(Saver.save("__real_" + Name));
1408     Symbol *Wrap = addUndefined<ELFT>(Saver.save("__wrap_" + Name));
1409     V.push_back({Sym, Real, Wrap});
1410 
1411     // We want to tell LTO not to inline symbols to be overwritten
1412     // because LTO doesn't know the final symbol contents after renaming.
1413     Real->CanInline = false;
1414     Sym->CanInline = false;
1415 
1416     // Tell LTO not to eliminate these symbols.
1417     Sym->IsUsedInRegularObj = true;
1418     Wrap->IsUsedInRegularObj = true;
1419   }
1420   return V;
1421 }
1422 
1423 // Do renaming for -wrap by updating pointers to symbols.
1424 //
1425 // When this function is executed, only InputFiles and symbol table
1426 // contain pointers to symbol objects. We visit them to replace pointers,
1427 // so that wrapped symbols are swapped as instructed by the command line.
1428 static void wrapSymbols(ArrayRef<WrappedSymbol> Wrapped) {
1429   DenseMap<Symbol *, Symbol *> Map;
1430   for (const WrappedSymbol &W : Wrapped) {
1431     Map[W.Sym] = W.Wrap;
1432     Map[W.Real] = W.Sym;
1433   }
1434 
1435   // Update pointers in input files.
1436   parallelForEach(ObjectFiles, [&](InputFile *File) {
1437     std::vector<Symbol *> &Syms = File->getMutableSymbols();
1438     for (size_t I = 0, E = Syms.size(); I != E; ++I)
1439       if (Symbol *S = Map.lookup(Syms[I]))
1440         Syms[I] = S;
1441   });
1442 
1443   // Update pointers in the symbol table.
1444   for (const WrappedSymbol &W : Wrapped)
1445     Symtab->wrap(W.Sym, W.Real, W.Wrap);
1446 }
1447 
1448 static const char *LibcallRoutineNames[] = {
1449 #define HANDLE_LIBCALL(code, name) name,
1450 #include "llvm/IR/RuntimeLibcalls.def"
1451 #undef HANDLE_LIBCALL
1452 };
1453 
1454 // Do actual linking. Note that when this function is called,
1455 // all linker scripts have already been parsed.
1456 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1457   // If a -hash-style option was not given, set to a default value,
1458   // which varies depending on the target.
1459   if (!Args.hasArg(OPT_hash_style)) {
1460     if (Config->EMachine == EM_MIPS)
1461       Config->SysvHash = true;
1462     else
1463       Config->SysvHash = Config->GnuHash = true;
1464   }
1465 
1466   // Default output filename is "a.out" by the Unix tradition.
1467   if (Config->OutputFile.empty())
1468     Config->OutputFile = "a.out";
1469 
1470   // Fail early if the output file or map file is not writable. If a user has a
1471   // long link, e.g. due to a large LTO link, they do not wish to run it and
1472   // find that it failed because there was a mistake in their command-line.
1473   if (auto E = tryCreateFile(Config->OutputFile))
1474     error("cannot open output file " + Config->OutputFile + ": " + E.message());
1475   if (auto E = tryCreateFile(Config->MapFile))
1476     error("cannot open map file " + Config->MapFile + ": " + E.message());
1477   if (errorCount())
1478     return;
1479 
1480   // Use default entry point name if no name was given via the command
1481   // line nor linker scripts. For some reason, MIPS entry point name is
1482   // different from others.
1483   Config->WarnMissingEntry =
1484       (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
1485   if (Config->Entry.empty() && !Config->Relocatable)
1486     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
1487 
1488   // Handle --trace-symbol.
1489   for (auto *Arg : Args.filtered(OPT_trace_symbol))
1490     Symtab->trace(Arg->getValue());
1491 
1492   // Add all files to the symbol table. This will add almost all
1493   // symbols that we need to the symbol table.
1494   for (InputFile *F : Files)
1495     Symtab->addFile<ELFT>(F);
1496 
1497   // Now that we have every file, we can decide if we will need a
1498   // dynamic symbol table.
1499   // We need one if we were asked to export dynamic symbols or if we are
1500   // producing a shared library.
1501   // We also need one if any shared libraries are used and for pie executables
1502   // (probably because the dynamic linker needs it).
1503   Config->HasDynSymTab =
1504       !SharedFiles.empty() || Config->Pic || Config->ExportDynamic;
1505 
1506   // Some symbols (such as __ehdr_start) are defined lazily only when there
1507   // are undefined symbols for them, so we add these to trigger that logic.
1508   for (StringRef Name : Script->ReferencedSymbols)
1509     addUndefined<ELFT>(Name);
1510 
1511   // Handle the `--undefined <sym>` options.
1512   for (StringRef S : Config->Undefined)
1513     handleUndefined<ELFT>(S);
1514 
1515   // If an entry symbol is in a static archive, pull out that file now.
1516   handleUndefined<ELFT>(Config->Entry);
1517 
1518   // If any of our inputs are bitcode files, the LTO code generator may create
1519   // references to certain library functions that might not be explicit in the
1520   // bitcode file's symbol table. If any of those library functions are defined
1521   // in a bitcode file in an archive member, we need to arrange to use LTO to
1522   // compile those archive members by adding them to the link beforehand.
1523   //
1524   // However, adding all libcall symbols to the link can have undesired
1525   // consequences. For example, the libgcc implementation of
1526   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1527   // that aborts the program if the Linux kernel does not support 64-bit
1528   // atomics, which would prevent the program from running even if it does not
1529   // use 64-bit atomics.
1530   //
1531   // Therefore, we only add libcall symbols to the link before LTO if we have
1532   // to, i.e. if the symbol's definition is in bitcode. Any other required
1533   // libcall symbols will be added to the link after LTO when we add the LTO
1534   // object file to the link.
1535   if (!BitcodeFiles.empty())
1536     for (const char *S : LibcallRoutineNames)
1537       handleLibcall<ELFT>(S);
1538 
1539   // Return if there were name resolution errors.
1540   if (errorCount())
1541     return;
1542 
1543   // Now when we read all script files, we want to finalize order of linker
1544   // script commands, which can be not yet final because of INSERT commands.
1545   Script->processInsertCommands();
1546 
1547   // We want to declare linker script's symbols early,
1548   // so that we can version them.
1549   // They also might be exported if referenced by DSOs.
1550   Script->declareSymbols();
1551 
1552   // Handle the -exclude-libs option.
1553   if (Args.hasArg(OPT_exclude_libs))
1554     excludeLibs(Args);
1555 
1556   // Create ElfHeader early. We need a dummy section in
1557   // addReservedSymbols to mark the created symbols as not absolute.
1558   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1559   Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1560 
1561   // Create wrapped symbols for -wrap option.
1562   std::vector<WrappedSymbol> Wrapped = addWrappedSymbols<ELFT>(Args);
1563 
1564   // We need to create some reserved symbols such as _end. Create them.
1565   if (!Config->Relocatable)
1566     addReservedSymbols();
1567 
1568   // Apply version scripts.
1569   //
1570   // For a relocatable output, version scripts don't make sense, and
1571   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1572   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1573   if (!Config->Relocatable)
1574     Symtab->scanVersionScript();
1575 
1576   // Do link-time optimization if given files are LLVM bitcode files.
1577   // This compiles bitcode files into real object files.
1578   //
1579   // With this the symbol table should be complete. After this, no new names
1580   // except a few linker-synthesized ones will be added to the symbol table.
1581   Symtab->addCombinedLTOObject<ELFT>();
1582   if (errorCount())
1583     return;
1584 
1585   // If -thinlto-index-only is given, we should create only "index
1586   // files" and not object files. Index file creation is already done
1587   // in addCombinedLTOObject, so we are done if that's the case.
1588   if (Config->ThinLTOIndexOnly)
1589     return;
1590 
1591   // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1592   // an output file in bitcode and exit, so that you can just get a
1593   // combined bitcode file.
1594   if (Config->EmitLLVM)
1595     return;
1596 
1597   // Apply symbol renames for -wrap.
1598   if (!Wrapped.empty())
1599     wrapSymbols(Wrapped);
1600 
1601   // Now that we have a complete list of input files.
1602   // Beyond this point, no new files are added.
1603   // Aggregate all input sections into one place.
1604   for (InputFile *F : ObjectFiles)
1605     for (InputSectionBase *S : F->getSections())
1606       if (S && S != &InputSection::Discarded)
1607         InputSections.push_back(S);
1608   for (BinaryFile *F : BinaryFiles)
1609     for (InputSectionBase *S : F->getSections())
1610       InputSections.push_back(cast<InputSection>(S));
1611 
1612   // We do not want to emit debug sections if --strip-all
1613   // or -strip-debug are given.
1614   if (Config->Strip != StripPolicy::None) {
1615     llvm::erase_if(InputSections, [](InputSectionBase *S) {
1616       return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1617     });
1618   }
1619 
1620   // The Target instance handles target-specific stuff, such as applying
1621   // relocations or writing a PLT section. It also contains target-dependent
1622   // values such as a default image base address.
1623   Target = getTarget();
1624 
1625   Config->EFlags = Target->calcEFlags();
1626   Config->MaxPageSize = getMaxPageSize(Args);
1627   Config->ImageBase = getImageBase(Args);
1628 
1629   if (Config->EMachine == EM_ARM) {
1630     // FIXME: These warnings can be removed when lld only uses these features
1631     // when the input objects have been compiled with an architecture that
1632     // supports them.
1633     if (Config->ARMHasBlx == false)
1634       warn("lld uses blx instruction, no object with architecture supporting "
1635            "feature detected");
1636   }
1637 
1638   // This adds a .comment section containing a version string. We have to add it
1639   // before mergeSections because the .comment section is a mergeable section.
1640   if (!Config->Relocatable)
1641     InputSections.push_back(createCommentSection());
1642 
1643   // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1644   // and identical code folding.
1645   splitSections<ELFT>();
1646   markLive<ELFT>();
1647   demoteSharedSymbols<ELFT>();
1648   mergeSections();
1649   if (Config->ICF != ICFLevel::None) {
1650     findKeepUniqueSections<ELFT>(Args);
1651     doIcf<ELFT>();
1652   }
1653 
1654   // Read the callgraph now that we know what was gced or icfed
1655   if (Config->CallGraphProfileSort) {
1656     if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1657       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1658         readCallGraph(*Buffer);
1659     readCallGraphsFromObjectFiles<ELFT>();
1660   }
1661 
1662   // Write the result to the file.
1663   writeResult<ELFT>();
1664 }
1665