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