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