xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 02f4cfec)
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/LTO/LTO.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compression.h"
54 #include "llvm/Support/GlobPattern.h"
55 #include "llvm/Support/LEB128.h"
56 #include "llvm/Support/Path.h"
57 #include "llvm/Support/TarWriter.h"
58 #include "llvm/Support/TargetSelect.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstdlib>
61 #include <utility>
62 
63 using namespace llvm;
64 using namespace llvm::ELF;
65 using namespace llvm::object;
66 using namespace llvm::sys;
67 using namespace llvm::support;
68 
69 namespace lld {
70 namespace elf {
71 
72 Configuration *config;
73 LinkerDriver *driver;
74 
75 static void setConfigs(opt::InputArgList &args);
76 static void readConfigs(opt::InputArgList &args);
77 
78 bool link(ArrayRef<const char *> args, bool canExitEarly, 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   enableColors(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->isStatic || 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->fixCortexA8 && config->emachine != EM_ARM)
303     error("--fix-cortex-a8 is only supported on ARM targets");
304 
305   if (config->tocOptimize && config->emachine != EM_PPC64)
306     error("--toc-optimize is only supported on the PowerPC64 target");
307 
308   if (config->pie && config->shared)
309     error("-shared and -pie may not be used together");
310 
311   if (!config->shared && !config->filterList.empty())
312     error("-F may not be used without -shared");
313 
314   if (!config->shared && !config->auxiliaryList.empty())
315     error("-f may not be used without -shared");
316 
317   if (!config->relocatable && !config->defineCommon)
318     error("-no-define-common not supported in non relocatable output");
319 
320   if (config->strip == StripPolicy::All && config->emitRelocs)
321     error("--strip-all and --emit-relocs may not be used together");
322 
323   if (config->zText && config->zIfuncNoplt)
324     error("-z text and -z ifunc-noplt may not be used together");
325 
326   if (config->relocatable) {
327     if (config->shared)
328       error("-r and -shared may not be used together");
329     if (config->gcSections)
330       error("-r and --gc-sections may not be used together");
331     if (config->gdbIndex)
332       error("-r and --gdb-index may not be used together");
333     if (config->icf != ICFLevel::None)
334       error("-r and --icf may not be used together");
335     if (config->pie)
336       error("-r and -pie may not be used together");
337     if (config->exportDynamic)
338       error("-r and --export-dynamic may not be used together");
339   }
340 
341   if (config->executeOnly) {
342     if (config->emachine != EM_AARCH64)
343       error("-execute-only is only supported on AArch64 targets");
344 
345     if (config->singleRoRx && !script->hasSectionsCommand)
346       error("-execute-only and -no-rosegment cannot be used together");
347   }
348 
349   if (config->zRetpolineplt && config->requireCET)
350     error("--require-cet may not be used with -z retpolineplt");
351 
352   if (config->emachine != EM_AARCH64) {
353     if (config->pacPlt)
354       error("--pac-plt only supported on AArch64");
355     if (config->forceBTI)
356       error("--force-bti only supported on AArch64");
357   }
358 }
359 
360 static const char *getReproduceOption(opt::InputArgList &args) {
361   if (auto *arg = args.getLastArg(OPT_reproduce))
362     return arg->getValue();
363   return getenv("LLD_REPRODUCE");
364 }
365 
366 static bool hasZOption(opt::InputArgList &args, StringRef key) {
367   for (auto *arg : args.filtered(OPT_z))
368     if (key == arg->getValue())
369       return true;
370   return false;
371 }
372 
373 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
374                      bool Default) {
375   for (auto *arg : args.filtered_reverse(OPT_z)) {
376     if (k1 == arg->getValue())
377       return true;
378     if (k2 == arg->getValue())
379       return false;
380   }
381   return Default;
382 }
383 
384 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
385   for (auto *arg : args.filtered_reverse(OPT_z)) {
386     StringRef v = arg->getValue();
387     if (v == "noseparate-code")
388       return SeparateSegmentKind::None;
389     if (v == "separate-code")
390       return SeparateSegmentKind::Code;
391     if (v == "separate-loadable-segments")
392       return SeparateSegmentKind::Loadable;
393   }
394   return SeparateSegmentKind::None;
395 }
396 
397 static GnuStackKind getZGnuStack(opt::InputArgList &args) {
398   for (auto *arg : args.filtered_reverse(OPT_z)) {
399     if (StringRef("execstack") == arg->getValue())
400       return GnuStackKind::Exec;
401     if (StringRef("noexecstack") == arg->getValue())
402       return GnuStackKind::NoExec;
403     if (StringRef("nognustack") == arg->getValue())
404       return GnuStackKind::None;
405   }
406 
407   return GnuStackKind::NoExec;
408 }
409 
410 static bool isKnownZFlag(StringRef s) {
411   return s == "combreloc" || s == "copyreloc" || s == "defs" ||
412          s == "execstack" || s == "global" || s == "hazardplt" ||
413          s == "ifunc-noplt" || s == "initfirst" || s == "interpose" ||
414          s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
415          s == "separate-code" || s == "separate-loadable-segments" ||
416          s == "nocombreloc" || s == "nocopyreloc" || s == "nodefaultlib" ||
417          s == "nodelete" || s == "nodlopen" || s == "noexecstack" ||
418          s == "nognustack" ||
419          s == "nokeep-text-section-prefix" || s == "norelro" ||
420          s == "noseparate-code" || s == "notext" || s == "now" ||
421          s == "origin" || s == "relro" || s == "retpolineplt" ||
422          s == "rodynamic" || s == "text" || s == "undefs" || s == "wxneeded" ||
423          s.startswith("common-page-size=") || s.startswith("max-page-size=") ||
424          s.startswith("stack-size=");
425 }
426 
427 // Report an error for an unknown -z option.
428 static void checkZOptions(opt::InputArgList &args) {
429   for (auto *arg : args.filtered(OPT_z))
430     if (!isKnownZFlag(arg->getValue()))
431       error("unknown -z value: " + StringRef(arg->getValue()));
432 }
433 
434 void LinkerDriver::main(ArrayRef<const char *> argsArr) {
435   ELFOptTable parser;
436   opt::InputArgList args = parser.parse(argsArr.slice(1));
437 
438   // Interpret this flag early because error() depends on them.
439   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
440   checkZOptions(args);
441 
442   // Handle -help
443   if (args.hasArg(OPT_help)) {
444     printHelp();
445     return;
446   }
447 
448   // Handle -v or -version.
449   //
450   // A note about "compatible with GNU linkers" message: this is a hack for
451   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
452   // still the newest version in March 2017) or earlier to recognize LLD as
453   // a GNU compatible linker. As long as an output for the -v option
454   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
455   //
456   // This is somewhat ugly hack, but in reality, we had no choice other
457   // than doing this. Considering the very long release cycle of Libtool,
458   // it is not easy to improve it to recognize LLD as a GNU compatible
459   // linker in a timely manner. Even if we can make it, there are still a
460   // lot of "configure" scripts out there that are generated by old version
461   // of Libtool. We cannot convince every software developer to migrate to
462   // the latest version and re-generate scripts. So we have this hack.
463   if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
464     message(getLLDVersion() + " (compatible with GNU linkers)");
465 
466   if (const char *path = getReproduceOption(args)) {
467     // Note that --reproduce is a debug option so you can ignore it
468     // if you are trying to understand the whole picture of the code.
469     Expected<std::unique_ptr<TarWriter>> errOrWriter =
470         TarWriter::create(path, path::stem(path));
471     if (errOrWriter) {
472       tar = std::move(*errOrWriter);
473       tar->append("response.txt", createResponseFile(args));
474       tar->append("version.txt", getLLDVersion() + "\n");
475     } else {
476       error("--reproduce: " + toString(errOrWriter.takeError()));
477     }
478   }
479 
480   readConfigs(args);
481 
482   // The behavior of -v or --version is a bit strange, but this is
483   // needed for compatibility with GNU linkers.
484   if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
485     return;
486   if (args.hasArg(OPT_version))
487     return;
488 
489   initLLVM();
490   createFiles(args);
491   if (errorCount())
492     return;
493 
494   inferMachineType();
495   setConfigs(args);
496   checkOptions();
497   if (errorCount())
498     return;
499 
500   // The Target instance handles target-specific stuff, such as applying
501   // relocations or writing a PLT section. It also contains target-dependent
502   // values such as a default image base address.
503   target = getTarget();
504 
505   switch (config->ekind) {
506   case ELF32LEKind:
507     link<ELF32LE>(args);
508     return;
509   case ELF32BEKind:
510     link<ELF32BE>(args);
511     return;
512   case ELF64LEKind:
513     link<ELF64LE>(args);
514     return;
515   case ELF64BEKind:
516     link<ELF64BE>(args);
517     return;
518   default:
519     llvm_unreachable("unknown Config->EKind");
520   }
521 }
522 
523 static std::string getRpath(opt::InputArgList &args) {
524   std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
525   return llvm::join(v.begin(), v.end(), ":");
526 }
527 
528 // Determines what we should do if there are remaining unresolved
529 // symbols after the name resolution.
530 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &args) {
531   UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
532                                               OPT_warn_unresolved_symbols, true)
533                                      ? UnresolvedPolicy::ReportError
534                                      : UnresolvedPolicy::Warn;
535 
536   // Process the last of -unresolved-symbols, -no-undefined or -z defs.
537   for (auto *arg : llvm::reverse(args)) {
538     switch (arg->getOption().getID()) {
539     case OPT_unresolved_symbols: {
540       StringRef s = arg->getValue();
541       if (s == "ignore-all" || s == "ignore-in-object-files")
542         return UnresolvedPolicy::Ignore;
543       if (s == "ignore-in-shared-libs" || s == "report-all")
544         return errorOrWarn;
545       error("unknown --unresolved-symbols value: " + s);
546       continue;
547     }
548     case OPT_no_undefined:
549       return errorOrWarn;
550     case OPT_z:
551       if (StringRef(arg->getValue()) == "defs")
552         return errorOrWarn;
553       if (StringRef(arg->getValue()) == "undefs")
554         return UnresolvedPolicy::Ignore;
555       continue;
556     }
557   }
558 
559   // -shared implies -unresolved-symbols=ignore-all because missing
560   // symbols are likely to be resolved at runtime using other DSOs.
561   if (config->shared)
562     return UnresolvedPolicy::Ignore;
563   return errorOrWarn;
564 }
565 
566 static Target2Policy getTarget2(opt::InputArgList &args) {
567   StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
568   if (s == "rel")
569     return Target2Policy::Rel;
570   if (s == "abs")
571     return Target2Policy::Abs;
572   if (s == "got-rel")
573     return Target2Policy::GotRel;
574   error("unknown --target2 option: " + s);
575   return Target2Policy::GotRel;
576 }
577 
578 static bool isOutputFormatBinary(opt::InputArgList &args) {
579   StringRef s = args.getLastArgValue(OPT_oformat, "elf");
580   if (s == "binary")
581     return true;
582   if (!s.startswith("elf"))
583     error("unknown --oformat value: " + s);
584   return false;
585 }
586 
587 static DiscardPolicy getDiscard(opt::InputArgList &args) {
588   if (args.hasArg(OPT_relocatable))
589     return DiscardPolicy::None;
590 
591   auto *arg =
592       args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
593   if (!arg)
594     return DiscardPolicy::Default;
595   if (arg->getOption().getID() == OPT_discard_all)
596     return DiscardPolicy::All;
597   if (arg->getOption().getID() == OPT_discard_locals)
598     return DiscardPolicy::Locals;
599   return DiscardPolicy::None;
600 }
601 
602 static StringRef getDynamicLinker(opt::InputArgList &args) {
603   auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
604   if (!arg || arg->getOption().getID() == OPT_no_dynamic_linker)
605     return "";
606   return arg->getValue();
607 }
608 
609 static ICFLevel getICF(opt::InputArgList &args) {
610   auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
611   if (!arg || arg->getOption().getID() == OPT_icf_none)
612     return ICFLevel::None;
613   if (arg->getOption().getID() == OPT_icf_safe)
614     return ICFLevel::Safe;
615   return ICFLevel::All;
616 }
617 
618 static StripPolicy getStrip(opt::InputArgList &args) {
619   if (args.hasArg(OPT_relocatable))
620     return StripPolicy::None;
621 
622   auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
623   if (!arg)
624     return StripPolicy::None;
625   if (arg->getOption().getID() == OPT_strip_all)
626     return StripPolicy::All;
627   return StripPolicy::Debug;
628 }
629 
630 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
631                                     const opt::Arg &arg) {
632   uint64_t va = 0;
633   if (s.startswith("0x"))
634     s = s.drop_front(2);
635   if (!to_integer(s, va, 16))
636     error("invalid argument: " + arg.getAsString(args));
637   return va;
638 }
639 
640 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
641   StringMap<uint64_t> ret;
642   for (auto *arg : args.filtered(OPT_section_start)) {
643     StringRef name;
644     StringRef addr;
645     std::tie(name, addr) = StringRef(arg->getValue()).split('=');
646     ret[name] = parseSectionAddress(addr, args, *arg);
647   }
648 
649   if (auto *arg = args.getLastArg(OPT_Ttext))
650     ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
651   if (auto *arg = args.getLastArg(OPT_Tdata))
652     ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
653   if (auto *arg = args.getLastArg(OPT_Tbss))
654     ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
655   return ret;
656 }
657 
658 static SortSectionPolicy getSortSection(opt::InputArgList &args) {
659   StringRef s = args.getLastArgValue(OPT_sort_section);
660   if (s == "alignment")
661     return SortSectionPolicy::Alignment;
662   if (s == "name")
663     return SortSectionPolicy::Name;
664   if (!s.empty())
665     error("unknown --sort-section rule: " + s);
666   return SortSectionPolicy::Default;
667 }
668 
669 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
670   StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
671   if (s == "warn")
672     return OrphanHandlingPolicy::Warn;
673   if (s == "error")
674     return OrphanHandlingPolicy::Error;
675   if (s != "place")
676     error("unknown --orphan-handling mode: " + s);
677   return OrphanHandlingPolicy::Place;
678 }
679 
680 // Parse --build-id or --build-id=<style>. We handle "tree" as a
681 // synonym for "sha1" because all our hash functions including
682 // -build-id=sha1 are actually tree hashes for performance reasons.
683 static std::pair<BuildIdKind, std::vector<uint8_t>>
684 getBuildId(opt::InputArgList &args) {
685   auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
686   if (!arg)
687     return {BuildIdKind::None, {}};
688 
689   if (arg->getOption().getID() == OPT_build_id)
690     return {BuildIdKind::Fast, {}};
691 
692   StringRef s = arg->getValue();
693   if (s == "fast")
694     return {BuildIdKind::Fast, {}};
695   if (s == "md5")
696     return {BuildIdKind::Md5, {}};
697   if (s == "sha1" || s == "tree")
698     return {BuildIdKind::Sha1, {}};
699   if (s == "uuid")
700     return {BuildIdKind::Uuid, {}};
701   if (s.startswith("0x"))
702     return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
703 
704   if (s != "none")
705     error("unknown --build-id style: " + s);
706   return {BuildIdKind::None, {}};
707 }
708 
709 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
710   StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
711   if (s == "android")
712     return {true, false};
713   if (s == "relr")
714     return {false, true};
715   if (s == "android+relr")
716     return {true, true};
717 
718   if (s != "none")
719     error("unknown -pack-dyn-relocs format: " + s);
720   return {false, false};
721 }
722 
723 static void readCallGraph(MemoryBufferRef mb) {
724   // Build a map from symbol name to section
725   DenseMap<StringRef, Symbol *> map;
726   for (InputFile *file : objectFiles)
727     for (Symbol *sym : file->getSymbols())
728       map[sym->getName()] = sym;
729 
730   auto findSection = [&](StringRef name) -> InputSectionBase * {
731     Symbol *sym = map.lookup(name);
732     if (!sym) {
733       if (config->warnSymbolOrdering)
734         warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
735       return nullptr;
736     }
737     maybeWarnUnorderableSymbol(sym);
738 
739     if (Defined *dr = dyn_cast_or_null<Defined>(sym))
740       return dyn_cast_or_null<InputSectionBase>(dr->section);
741     return nullptr;
742   };
743 
744   for (StringRef line : args::getLines(mb)) {
745     SmallVector<StringRef, 3> fields;
746     line.split(fields, ' ');
747     uint64_t count;
748 
749     if (fields.size() != 3 || !to_integer(fields[2], count)) {
750       error(mb.getBufferIdentifier() + ": parse error");
751       return;
752     }
753 
754     if (InputSectionBase *from = findSection(fields[0]))
755       if (InputSectionBase *to = findSection(fields[1]))
756         config->callGraphProfile[std::make_pair(from, to)] += count;
757   }
758 }
759 
760 template <class ELFT> static void readCallGraphsFromObjectFiles() {
761   for (auto file : objectFiles) {
762     auto *obj = cast<ObjFile<ELFT>>(file);
763 
764     for (const Elf_CGProfile_Impl<ELFT> &cgpe : obj->cgProfile) {
765       auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_from));
766       auto *toSym = dyn_cast<Defined>(&obj->getSymbol(cgpe.cgp_to));
767       if (!fromSym || !toSym)
768         continue;
769 
770       auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
771       auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
772       if (from && to)
773         config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
774     }
775   }
776 }
777 
778 static bool getCompressDebugSections(opt::InputArgList &args) {
779   StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
780   if (s == "none")
781     return false;
782   if (s != "zlib")
783     error("unknown --compress-debug-sections value: " + s);
784   if (!zlib::isAvailable())
785     error("--compress-debug-sections: zlib is not available");
786   return true;
787 }
788 
789 static StringRef getAliasSpelling(opt::Arg *arg) {
790   if (const opt::Arg *alias = arg->getAlias())
791     return alias->getSpelling();
792   return arg->getSpelling();
793 }
794 
795 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
796                                                         unsigned id) {
797   auto *arg = args.getLastArg(id);
798   if (!arg)
799     return {"", ""};
800 
801   StringRef s = arg->getValue();
802   std::pair<StringRef, StringRef> ret = s.split(';');
803   if (ret.second.empty())
804     error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
805   return ret;
806 }
807 
808 // Parse the symbol ordering file and warn for any duplicate entries.
809 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
810   SetVector<StringRef> names;
811   for (StringRef s : args::getLines(mb))
812     if (!names.insert(s) && config->warnSymbolOrdering)
813       warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
814 
815   return names.takeVector();
816 }
817 
818 static void parseClangOption(StringRef opt, const Twine &msg) {
819   std::string err;
820   raw_string_ostream os(err);
821 
822   const char *argv[] = {config->progName.data(), opt.data()};
823   if (cl::ParseCommandLineOptions(2, argv, "", &os))
824     return;
825   os.flush();
826   error(msg + ": " + StringRef(err).trim());
827 }
828 
829 // Initializes Config members by the command line options.
830 static void readConfigs(opt::InputArgList &args) {
831   errorHandler().verbose = args.hasArg(OPT_verbose);
832   errorHandler().fatalWarnings =
833       args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
834   errorHandler().vsDiagnostics =
835       args.hasArg(OPT_visual_studio_diagnostics_format, false);
836   threadsEnabled = args.hasFlag(OPT_threads, OPT_no_threads, true);
837 
838   config->allowMultipleDefinition =
839       args.hasFlag(OPT_allow_multiple_definition,
840                    OPT_no_allow_multiple_definition, false) ||
841       hasZOption(args, "muldefs");
842   config->allowShlibUndefined =
843       args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined,
844                    args.hasArg(OPT_shared));
845   config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
846   config->bsymbolic = args.hasArg(OPT_Bsymbolic);
847   config->bsymbolicFunctions = args.hasArg(OPT_Bsymbolic_functions);
848   config->checkSections =
849       args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
850   config->chroot = args.getLastArgValue(OPT_chroot);
851   config->compressDebugSections = getCompressDebugSections(args);
852   config->cref = args.hasFlag(OPT_cref, OPT_no_cref, false);
853   config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
854                                       !args.hasArg(OPT_relocatable));
855   config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
856   config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
857   config->disableVerify = args.hasArg(OPT_disable_verify);
858   config->discard = getDiscard(args);
859   config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
860   config->dynamicLinker = getDynamicLinker(args);
861   config->ehFrameHdr =
862       args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
863   config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
864   config->emitRelocs = args.hasArg(OPT_emit_relocs);
865   config->callGraphProfileSort = args.hasFlag(
866       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
867   config->enableNewDtags =
868       args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
869   config->entry = args.getLastArgValue(OPT_entry);
870   config->executeOnly =
871       args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
872   config->exportDynamic =
873       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
874   config->filterList = args::getStrings(args, OPT_filter);
875   config->fini = args.getLastArgValue(OPT_fini, "_fini");
876   config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419);
877   config->fixCortexA8 = args.hasArg(OPT_fix_cortex_a8);
878   config->forceBTI = args.hasArg(OPT_force_bti);
879   config->requireCET = args.hasArg(OPT_require_cet);
880   config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
881   config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
882   config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
883   config->icf = getICF(args);
884   config->ignoreDataAddressEquality =
885       args.hasArg(OPT_ignore_data_address_equality);
886   config->ignoreFunctionAddressEquality =
887       args.hasArg(OPT_ignore_function_address_equality);
888   config->init = args.getLastArgValue(OPT_init, "_init");
889   config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
890   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
891   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
892   config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
893   config->ltoNewPassManager = args.hasArg(OPT_lto_new_pass_manager);
894   config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
895   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
896   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
897   config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
898   config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
899   config->mapFile = args.getLastArgValue(OPT_Map);
900   config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
901   config->mergeArmExidx =
902       args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
903   config->mmapOutputFile =
904       args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
905   config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
906   config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
907   config->nostdlib = args.hasArg(OPT_nostdlib);
908   config->oFormatBinary = isOutputFormatBinary(args);
909   config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
910   config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
911   config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
912   config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
913   config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
914   config->optimize = args::getInteger(args, OPT_O, 1);
915   config->orphanHandling = getOrphanHandling(args);
916   config->outputFile = args.getLastArgValue(OPT_o);
917   config->pacPlt = args.hasArg(OPT_pac_plt);
918   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
919   config->printIcfSections =
920       args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
921   config->printGcSections =
922       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
923   config->printSymbolOrder =
924       args.getLastArgValue(OPT_print_symbol_order);
925   config->rpath = getRpath(args);
926   config->relocatable = args.hasArg(OPT_relocatable);
927   config->saveTemps = args.hasArg(OPT_save_temps);
928   config->searchPaths = args::getStrings(args, OPT_library_path);
929   config->sectionStartMap = getSectionStartMap(args);
930   config->shared = args.hasArg(OPT_shared);
931   config->singleRoRx = args.hasArg(OPT_no_rosegment);
932   config->soName = args.getLastArgValue(OPT_soname);
933   config->sortSection = getSortSection(args);
934   config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
935   config->strip = getStrip(args);
936   config->sysroot = args.getLastArgValue(OPT_sysroot);
937   config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
938   config->target2 = getTarget2(args);
939   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
940   config->thinLTOCachePolicy = CHECK(
941       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
942       "--thinlto-cache-policy: invalid cache policy");
943   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
944   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
945                              args.hasArg(OPT_thinlto_index_only_eq);
946   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
947   config->thinLTOJobs = args::getInteger(args, OPT_thinlto_jobs, -1u);
948   config->thinLTOObjectSuffixReplace =
949       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
950   config->thinLTOPrefixReplace =
951       getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
952   config->trace = args.hasArg(OPT_trace);
953   config->undefined = args::getStrings(args, OPT_undefined);
954   config->undefinedVersion =
955       args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
956   config->useAndroidRelrTags = args.hasFlag(
957       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
958   config->unresolvedSymbols = getUnresolvedSymbolPolicy(args);
959   config->warnBackrefs =
960       args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
961   config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
962   config->warnIfuncTextrel =
963       args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
964   config->warnSymbolOrdering =
965       args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
966   config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
967   config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
968   config->zExecstack = getZFlag(args, "execstack", "noexecstack", false);
969   config->zGlobal = hasZOption(args, "global");
970   config->zGnustack = getZGnuStack(args);
971   config->zHazardplt = hasZOption(args, "hazardplt");
972   config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
973   config->zInitfirst = hasZOption(args, "initfirst");
974   config->zInterpose = hasZOption(args, "interpose");
975   config->zKeepTextSectionPrefix = getZFlag(
976       args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
977   config->zNodefaultlib = hasZOption(args, "nodefaultlib");
978   config->zNodelete = hasZOption(args, "nodelete");
979   config->zNodlopen = hasZOption(args, "nodlopen");
980   config->zNow = getZFlag(args, "now", "lazy", false);
981   config->zOrigin = hasZOption(args, "origin");
982   config->zRelro = getZFlag(args, "relro", "norelro", true);
983   config->zRetpolineplt = hasZOption(args, "retpolineplt");
984   config->zRodynamic = hasZOption(args, "rodynamic");
985   config->zSeparate = getZSeparate(args);
986   config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
987   config->zText = getZFlag(args, "text", "notext", true);
988   config->zWxneeded = hasZOption(args, "wxneeded");
989 
990   // Parse LTO options.
991   if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
992     parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
993                      arg->getSpelling());
994 
995   for (auto *arg : args.filtered(OPT_plugin_opt))
996     parseClangOption(arg->getValue(), arg->getSpelling());
997 
998   // Parse -mllvm options.
999   for (auto *arg : args.filtered(OPT_mllvm))
1000     parseClangOption(arg->getValue(), arg->getSpelling());
1001 
1002   if (config->ltoo > 3)
1003     error("invalid optimization level for LTO: " + Twine(config->ltoo));
1004   if (config->ltoPartitions == 0)
1005     error("--lto-partitions: number of threads must be > 0");
1006   if (config->thinLTOJobs == 0)
1007     error("--thinlto-jobs: number of threads must be > 0");
1008 
1009   if (config->splitStackAdjustSize < 0)
1010     error("--split-stack-adjust-size: size must be >= 0");
1011 
1012   // Parse ELF{32,64}{LE,BE} and CPU type.
1013   if (auto *arg = args.getLastArg(OPT_m)) {
1014     StringRef s = arg->getValue();
1015     std::tie(config->ekind, config->emachine, config->osabi) =
1016         parseEmulation(s);
1017     config->mipsN32Abi =
1018         (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
1019     config->emulation = s;
1020   }
1021 
1022   // Parse -hash-style={sysv,gnu,both}.
1023   if (auto *arg = args.getLastArg(OPT_hash_style)) {
1024     StringRef s = arg->getValue();
1025     if (s == "sysv")
1026       config->sysvHash = true;
1027     else if (s == "gnu")
1028       config->gnuHash = true;
1029     else if (s == "both")
1030       config->sysvHash = config->gnuHash = true;
1031     else
1032       error("unknown -hash-style: " + s);
1033   }
1034 
1035   if (args.hasArg(OPT_print_map))
1036     config->mapFile = "-";
1037 
1038   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1039   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1040   // it.
1041   if (config->nmagic || config->omagic)
1042     config->zRelro = false;
1043 
1044   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1045 
1046   std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1047       getPackDynRelocs(args);
1048 
1049   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1050     if (args.hasArg(OPT_call_graph_ordering_file))
1051       error("--symbol-ordering-file and --call-graph-order-file "
1052             "may not be used together");
1053     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1054       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1055       // Also need to disable CallGraphProfileSort to prevent
1056       // LLD order symbols with CGProfile
1057       config->callGraphProfileSort = false;
1058     }
1059   }
1060 
1061   assert(config->versionDefinitions.empty());
1062   config->versionDefinitions.push_back({"local", (uint16_t)VER_NDX_LOCAL, {}});
1063   config->versionDefinitions.push_back(
1064       {"global", (uint16_t)VER_NDX_GLOBAL, {}});
1065 
1066   // If --retain-symbol-file is used, we'll keep only the symbols listed in
1067   // the file and discard all others.
1068   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1069     config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(
1070         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1071     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1072       for (StringRef s : args::getLines(*buffer))
1073         config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back(
1074             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1075   }
1076 
1077   // Parses -dynamic-list and -export-dynamic-symbol. They make some
1078   // symbols private. Note that -export-dynamic takes precedence over them
1079   // as it says all symbols should be exported.
1080   if (!config->exportDynamic) {
1081     for (auto *arg : args.filtered(OPT_dynamic_list))
1082       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1083         readDynamicList(*buffer);
1084 
1085     for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1086       config->dynamicList.push_back(
1087           {arg->getValue(), /*isExternCpp=*/false, /*hasWildcard=*/false});
1088   }
1089 
1090   // If --export-dynamic-symbol=foo is given and symbol foo is defined in
1091   // an object file in an archive file, that object file should be pulled
1092   // out and linked. (It doesn't have to behave like that from technical
1093   // point of view, but this is needed for compatibility with GNU.)
1094   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1095     config->undefined.push_back(arg->getValue());
1096 
1097   for (auto *arg : args.filtered(OPT_version_script))
1098     if (Optional<std::string> path = searchScript(arg->getValue())) {
1099       if (Optional<MemoryBufferRef> buffer = readFile(*path))
1100         readVersionScript(*buffer);
1101     } else {
1102       error(Twine("cannot find version script ") + arg->getValue());
1103     }
1104 }
1105 
1106 // Some Config members do not directly correspond to any particular
1107 // command line options, but computed based on other Config values.
1108 // This function initialize such members. See Config.h for the details
1109 // of these values.
1110 static void setConfigs(opt::InputArgList &args) {
1111   ELFKind k = config->ekind;
1112   uint16_t m = config->emachine;
1113 
1114   config->copyRelocs = (config->relocatable || config->emitRelocs);
1115   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1116   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1117   config->endianness = config->isLE ? endianness::little : endianness::big;
1118   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1119   config->isPic = config->pie || config->shared;
1120   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1121   config->wordsize = config->is64 ? 8 : 4;
1122 
1123   // ELF defines two different ways to store relocation addends as shown below:
1124   //
1125   //  Rel:  Addends are stored to the location where relocations are applied.
1126   //  Rela: Addends are stored as part of relocation entry.
1127   //
1128   // In other words, Rela makes it easy to read addends at the price of extra
1129   // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
1130   // different mechanisms in the first place, but this is how the spec is
1131   // defined.
1132   //
1133   // You cannot choose which one, Rel or Rela, you want to use. Instead each
1134   // ABI defines which one you need to use. The following expression expresses
1135   // that.
1136   config->isRela = m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON ||
1137                    m == EM_PPC || m == EM_PPC64 || m == EM_RISCV ||
1138                    m == EM_X86_64;
1139 
1140   // If the output uses REL relocations we must store the dynamic relocation
1141   // addends to the output sections. We also store addends for RELA relocations
1142   // if --apply-dynamic-relocs is used.
1143   // We default to not writing the addends when using RELA relocations since
1144   // any standard conforming tool can find it in r_addend.
1145   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1146                                       OPT_no_apply_dynamic_relocs, false) ||
1147                          !config->isRela;
1148 
1149   config->tocOptimize =
1150       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1151 }
1152 
1153 // Returns a value of "-format" option.
1154 static bool isFormatBinary(StringRef s) {
1155   if (s == "binary")
1156     return true;
1157   if (s == "elf" || s == "default")
1158     return false;
1159   error("unknown -format value: " + s +
1160         " (supported formats: elf, default, binary)");
1161   return false;
1162 }
1163 
1164 void LinkerDriver::createFiles(opt::InputArgList &args) {
1165   // For --{push,pop}-state.
1166   std::vector<std::tuple<bool, bool, bool>> stack;
1167 
1168   // Iterate over argv to process input files and positional arguments.
1169   for (auto *arg : args) {
1170     switch (arg->getOption().getID()) {
1171     case OPT_library:
1172       addLibrary(arg->getValue());
1173       break;
1174     case OPT_INPUT:
1175       addFile(arg->getValue(), /*withLOption=*/false);
1176       break;
1177     case OPT_defsym: {
1178       StringRef from;
1179       StringRef to;
1180       std::tie(from, to) = StringRef(arg->getValue()).split('=');
1181       if (from.empty() || to.empty())
1182         error("-defsym: syntax error: " + StringRef(arg->getValue()));
1183       else
1184         readDefsym(from, MemoryBufferRef(to, "-defsym"));
1185       break;
1186     }
1187     case OPT_script:
1188       if (Optional<std::string> path = searchScript(arg->getValue())) {
1189         if (Optional<MemoryBufferRef> mb = readFile(*path))
1190           readLinkerScript(*mb);
1191         break;
1192       }
1193       error(Twine("cannot find linker script ") + arg->getValue());
1194       break;
1195     case OPT_as_needed:
1196       config->asNeeded = true;
1197       break;
1198     case OPT_format:
1199       config->formatBinary = isFormatBinary(arg->getValue());
1200       break;
1201     case OPT_no_as_needed:
1202       config->asNeeded = false;
1203       break;
1204     case OPT_Bstatic:
1205     case OPT_omagic:
1206     case OPT_nmagic:
1207       config->isStatic = true;
1208       break;
1209     case OPT_Bdynamic:
1210       config->isStatic = false;
1211       break;
1212     case OPT_whole_archive:
1213       inWholeArchive = true;
1214       break;
1215     case OPT_no_whole_archive:
1216       inWholeArchive = false;
1217       break;
1218     case OPT_just_symbols:
1219       if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1220         files.push_back(createObjectFile(*mb));
1221         files.back()->justSymbols = true;
1222       }
1223       break;
1224     case OPT_start_group:
1225       if (InputFile::isInGroup)
1226         error("nested --start-group");
1227       InputFile::isInGroup = true;
1228       break;
1229     case OPT_end_group:
1230       if (!InputFile::isInGroup)
1231         error("stray --end-group");
1232       InputFile::isInGroup = false;
1233       ++InputFile::nextGroupId;
1234       break;
1235     case OPT_start_lib:
1236       if (inLib)
1237         error("nested --start-lib");
1238       if (InputFile::isInGroup)
1239         error("may not nest --start-lib in --start-group");
1240       inLib = true;
1241       InputFile::isInGroup = true;
1242       break;
1243     case OPT_end_lib:
1244       if (!inLib)
1245         error("stray --end-lib");
1246       inLib = false;
1247       InputFile::isInGroup = false;
1248       ++InputFile::nextGroupId;
1249       break;
1250     case OPT_push_state:
1251       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1252       break;
1253     case OPT_pop_state:
1254       if (stack.empty()) {
1255         error("unbalanced --push-state/--pop-state");
1256         break;
1257       }
1258       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1259       stack.pop_back();
1260       break;
1261     }
1262   }
1263 
1264   if (files.empty() && errorCount() == 0)
1265     error("no input files");
1266 }
1267 
1268 // If -m <machine_type> was not given, infer it from object files.
1269 void LinkerDriver::inferMachineType() {
1270   if (config->ekind != ELFNoneKind)
1271     return;
1272 
1273   for (InputFile *f : files) {
1274     if (f->ekind == ELFNoneKind)
1275       continue;
1276     config->ekind = f->ekind;
1277     config->emachine = f->emachine;
1278     config->osabi = f->osabi;
1279     config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1280     return;
1281   }
1282   error("target emulation unknown: -m or at least one .o file required");
1283 }
1284 
1285 // Parse -z max-page-size=<value>. The default value is defined by
1286 // each target.
1287 static uint64_t getMaxPageSize(opt::InputArgList &args) {
1288   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1289                                        target->defaultMaxPageSize);
1290   if (!isPowerOf2_64(val))
1291     error("max-page-size: value isn't a power of 2");
1292   if (config->nmagic || config->omagic) {
1293     if (val != target->defaultMaxPageSize)
1294       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1295     return 1;
1296   }
1297   return val;
1298 }
1299 
1300 // Parse -z common-page-size=<value>. The default value is defined by
1301 // each target.
1302 static uint64_t getCommonPageSize(opt::InputArgList &args) {
1303   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1304                                        target->defaultCommonPageSize);
1305   if (!isPowerOf2_64(val))
1306     error("common-page-size: value isn't a power of 2");
1307   if (config->nmagic || config->omagic) {
1308     if (val != target->defaultCommonPageSize)
1309       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1310     return 1;
1311   }
1312   // commonPageSize can't be larger than maxPageSize.
1313   if (val > config->maxPageSize)
1314     val = config->maxPageSize;
1315   return val;
1316 }
1317 
1318 // Parses -image-base option.
1319 static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1320   // Because we are using "Config->maxPageSize" here, this function has to be
1321   // called after the variable is initialized.
1322   auto *arg = args.getLastArg(OPT_image_base);
1323   if (!arg)
1324     return None;
1325 
1326   StringRef s = arg->getValue();
1327   uint64_t v;
1328   if (!to_integer(s, v)) {
1329     error("-image-base: number expected, but got " + s);
1330     return 0;
1331   }
1332   if ((v % config->maxPageSize) != 0)
1333     warn("-image-base: address isn't multiple of page size: " + s);
1334   return v;
1335 }
1336 
1337 // Parses `--exclude-libs=lib,lib,...`.
1338 // The library names may be delimited by commas or colons.
1339 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1340   DenseSet<StringRef> ret;
1341   for (auto *arg : args.filtered(OPT_exclude_libs)) {
1342     StringRef s = arg->getValue();
1343     for (;;) {
1344       size_t pos = s.find_first_of(",:");
1345       if (pos == StringRef::npos)
1346         break;
1347       ret.insert(s.substr(0, pos));
1348       s = s.substr(pos + 1);
1349     }
1350     ret.insert(s);
1351   }
1352   return ret;
1353 }
1354 
1355 // Handles the -exclude-libs option. If a static library file is specified
1356 // by the -exclude-libs option, all public symbols from the archive become
1357 // private unless otherwise specified by version scripts or something.
1358 // A special library name "ALL" means all archive files.
1359 //
1360 // This is not a popular option, but some programs such as bionic libc use it.
1361 static void excludeLibs(opt::InputArgList &args) {
1362   DenseSet<StringRef> libs = getExcludeLibs(args);
1363   bool all = libs.count("ALL");
1364 
1365   auto visit = [&](InputFile *file) {
1366     if (!file->archiveName.empty())
1367       if (all || libs.count(path::filename(file->archiveName)))
1368         for (Symbol *sym : file->getSymbols())
1369           if (!sym->isLocal() && sym->file == file)
1370             sym->versionId = VER_NDX_LOCAL;
1371   };
1372 
1373   for (InputFile *file : objectFiles)
1374     visit(file);
1375 
1376   for (BitcodeFile *file : bitcodeFiles)
1377     visit(file);
1378 }
1379 
1380 // Force Sym to be entered in the output. Used for -u or equivalent.
1381 static void handleUndefined(Symbol *sym) {
1382   // Since a symbol may not be used inside the program, LTO may
1383   // eliminate it. Mark the symbol as "used" to prevent it.
1384   sym->isUsedInRegularObj = true;
1385 
1386   if (sym->isLazy())
1387     sym->fetch();
1388 }
1389 
1390 // As an extension to GNU linkers, lld supports a variant of `-u`
1391 // which accepts wildcard patterns. All symbols that match a given
1392 // pattern are handled as if they were given by `-u`.
1393 static void handleUndefinedGlob(StringRef arg) {
1394   Expected<GlobPattern> pat = GlobPattern::create(arg);
1395   if (!pat) {
1396     error("--undefined-glob: " + toString(pat.takeError()));
1397     return;
1398   }
1399 
1400   std::vector<Symbol *> syms;
1401   symtab->forEachSymbol([&](Symbol *sym) {
1402     // Calling Sym->fetch() from here is not safe because it may
1403     // add new symbols to the symbol table, invalidating the
1404     // current iterator. So we just keep a note.
1405     if (pat->match(sym->getName()))
1406       syms.push_back(sym);
1407   });
1408 
1409   for (Symbol *sym : syms)
1410     handleUndefined(sym);
1411 }
1412 
1413 static void handleLibcall(StringRef name) {
1414   Symbol *sym = symtab->find(name);
1415   if (!sym || !sym->isLazy())
1416     return;
1417 
1418   MemoryBufferRef mb;
1419   if (auto *lo = dyn_cast<LazyObject>(sym))
1420     mb = lo->file->mb;
1421   else
1422     mb = cast<LazyArchive>(sym)->getMemberBuffer();
1423 
1424   if (isBitcode(mb))
1425     sym->fetch();
1426 }
1427 
1428 // Replaces common symbols with defined symbols reside in .bss sections.
1429 // This function is called after all symbol names are resolved. As a
1430 // result, the passes after the symbol resolution won't see any
1431 // symbols of type CommonSymbol.
1432 static void replaceCommonSymbols() {
1433   symtab->forEachSymbol([](Symbol *sym) {
1434     auto *s = dyn_cast<CommonSymbol>(sym);
1435     if (!s)
1436       return;
1437 
1438     auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1439     bss->file = s->file;
1440     bss->markDead();
1441     inputSections.push_back(bss);
1442     s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
1443                        /*value=*/0, s->size, bss});
1444   });
1445 }
1446 
1447 // If all references to a DSO happen to be weak, the DSO is not added
1448 // to DT_NEEDED. If that happens, we need to eliminate shared symbols
1449 // created from the DSO. Otherwise, they become dangling references
1450 // that point to a non-existent DSO.
1451 static void demoteSharedSymbols() {
1452   symtab->forEachSymbol([](Symbol *sym) {
1453     auto *s = dyn_cast<SharedSymbol>(sym);
1454     if (!s || s->getFile().isNeeded)
1455       return;
1456 
1457     bool used = s->used;
1458     s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type});
1459     s->used = used;
1460   });
1461 }
1462 
1463 // The section referred to by `s` is considered address-significant. Set the
1464 // keepUnique flag on the section if appropriate.
1465 static void markAddrsig(Symbol *s) {
1466   if (auto *d = dyn_cast_or_null<Defined>(s))
1467     if (d->section)
1468       // We don't need to keep text sections unique under --icf=all even if they
1469       // are address-significant.
1470       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
1471         d->section->keepUnique = true;
1472 }
1473 
1474 // Record sections that define symbols mentioned in --keep-unique <symbol>
1475 // and symbols referred to by address-significance tables. These sections are
1476 // ineligible for ICF.
1477 template <class ELFT>
1478 static void findKeepUniqueSections(opt::InputArgList &args) {
1479   for (auto *arg : args.filtered(OPT_keep_unique)) {
1480     StringRef name = arg->getValue();
1481     auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1482     if (!d || !d->section) {
1483       warn("could not find symbol " + name + " to keep unique");
1484       continue;
1485     }
1486     d->section->keepUnique = true;
1487   }
1488 
1489   // --icf=all --ignore-data-address-equality means that we can ignore
1490   // the dynsym and address-significance tables entirely.
1491   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
1492     return;
1493 
1494   // Symbols in the dynsym could be address-significant in other executables
1495   // or DSOs, so we conservatively mark them as address-significant.
1496   symtab->forEachSymbol([&](Symbol *sym) {
1497     if (sym->includeInDynsym())
1498       markAddrsig(sym);
1499   });
1500 
1501   // Visit the address-significance table in each object file and mark each
1502   // referenced symbol as address-significant.
1503   for (InputFile *f : objectFiles) {
1504     auto *obj = cast<ObjFile<ELFT>>(f);
1505     ArrayRef<Symbol *> syms = obj->getSymbols();
1506     if (obj->addrsigSec) {
1507       ArrayRef<uint8_t> contents =
1508           check(obj->getObj().getSectionContents(obj->addrsigSec));
1509       const uint8_t *cur = contents.begin();
1510       while (cur != contents.end()) {
1511         unsigned size;
1512         const char *err;
1513         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1514         if (err)
1515           fatal(toString(f) + ": could not decode addrsig section: " + err);
1516         markAddrsig(syms[symIndex]);
1517         cur += size;
1518       }
1519     } else {
1520       // If an object file does not have an address-significance table,
1521       // conservatively mark all of its symbols as address-significant.
1522       for (Symbol *s : syms)
1523         markAddrsig(s);
1524     }
1525   }
1526 }
1527 
1528 // This function reads a symbol partition specification section. These sections
1529 // are used to control which partition a symbol is allocated to. See
1530 // https://lld.llvm.org/Partitions.html for more details on partitions.
1531 template <typename ELFT>
1532 static void readSymbolPartitionSection(InputSectionBase *s) {
1533   // Read the relocation that refers to the partition's entry point symbol.
1534   Symbol *sym;
1535   if (s->areRelocsRela)
1536     sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]);
1537   else
1538     sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]);
1539   if (!isa<Defined>(sym) || !sym->includeInDynsym())
1540     return;
1541 
1542   StringRef partName = reinterpret_cast<const char *>(s->data().data());
1543   for (Partition &part : partitions) {
1544     if (part.name == partName) {
1545       sym->partition = part.getNumber();
1546       return;
1547     }
1548   }
1549 
1550   // Forbid partitions from being used on incompatible targets, and forbid them
1551   // from being used together with various linker features that assume a single
1552   // set of output sections.
1553   if (script->hasSectionsCommand)
1554     error(toString(s->file) +
1555           ": partitions cannot be used with the SECTIONS command");
1556   if (script->hasPhdrsCommands())
1557     error(toString(s->file) +
1558           ": partitions cannot be used with the PHDRS command");
1559   if (!config->sectionStartMap.empty())
1560     error(toString(s->file) + ": partitions cannot be used with "
1561                               "--section-start, -Ttext, -Tdata or -Tbss");
1562   if (config->emachine == EM_MIPS)
1563     error(toString(s->file) + ": partitions cannot be used on this target");
1564 
1565   // Impose a limit of no more than 254 partitions. This limit comes from the
1566   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1567   // the amount of space devoted to the partition number in RankFlags.
1568   if (partitions.size() == 254)
1569     fatal("may not have more than 254 partitions");
1570 
1571   partitions.emplace_back();
1572   Partition &newPart = partitions.back();
1573   newPart.name = partName;
1574   sym->partition = newPart.getNumber();
1575 }
1576 
1577 static Symbol *addUndefined(StringRef name) {
1578   return symtab->addSymbol(
1579       Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
1580 }
1581 
1582 // This function is where all the optimizations of link-time
1583 // optimization takes place. When LTO is in use, some input files are
1584 // not in native object file format but in the LLVM bitcode format.
1585 // This function compiles bitcode files into a few big native files
1586 // using LLVM functions and replaces bitcode symbols with the results.
1587 // Because all bitcode files that the program consists of are passed to
1588 // the compiler at once, it can do a whole-program optimization.
1589 template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1590   // Compile bitcode files and replace bitcode symbols.
1591   lto.reset(new BitcodeCompiler);
1592   for (BitcodeFile *file : bitcodeFiles)
1593     lto->add(*file);
1594 
1595   for (InputFile *file : lto->compile()) {
1596     auto *obj = cast<ObjFile<ELFT>>(file);
1597     obj->parse(/*ignoreComdats=*/true);
1598     for (Symbol *sym : obj->getGlobalSymbols())
1599       sym->parseSymbolVersion();
1600     objectFiles.push_back(file);
1601   }
1602 }
1603 
1604 // The --wrap option is a feature to rename symbols so that you can write
1605 // wrappers for existing functions. If you pass `-wrap=foo`, all
1606 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1607 // expected to write `wrap_foo` function as a wrapper). The original
1608 // symbol becomes accessible as `real_foo`, so you can call that from your
1609 // wrapper.
1610 //
1611 // This data structure is instantiated for each -wrap option.
1612 struct WrappedSymbol {
1613   Symbol *sym;
1614   Symbol *real;
1615   Symbol *wrap;
1616 };
1617 
1618 // Handles -wrap option.
1619 //
1620 // This function instantiates wrapper symbols. At this point, they seem
1621 // like they are not being used at all, so we explicitly set some flags so
1622 // that LTO won't eliminate them.
1623 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
1624   std::vector<WrappedSymbol> v;
1625   DenseSet<StringRef> seen;
1626 
1627   for (auto *arg : args.filtered(OPT_wrap)) {
1628     StringRef name = arg->getValue();
1629     if (!seen.insert(name).second)
1630       continue;
1631 
1632     Symbol *sym = symtab->find(name);
1633     if (!sym)
1634       continue;
1635 
1636     Symbol *real = addUndefined(saver.save("__real_" + name));
1637     Symbol *wrap = addUndefined(saver.save("__wrap_" + name));
1638     v.push_back({sym, real, wrap});
1639 
1640     // We want to tell LTO not to inline symbols to be overwritten
1641     // because LTO doesn't know the final symbol contents after renaming.
1642     real->canInline = false;
1643     sym->canInline = false;
1644 
1645     // Tell LTO not to eliminate these symbols.
1646     sym->isUsedInRegularObj = true;
1647     wrap->isUsedInRegularObj = true;
1648   }
1649   return v;
1650 }
1651 
1652 // Do renaming for -wrap by updating pointers to symbols.
1653 //
1654 // When this function is executed, only InputFiles and symbol table
1655 // contain pointers to symbol objects. We visit them to replace pointers,
1656 // so that wrapped symbols are swapped as instructed by the command line.
1657 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
1658   DenseMap<Symbol *, Symbol *> map;
1659   for (const WrappedSymbol &w : wrapped) {
1660     map[w.sym] = w.wrap;
1661     map[w.real] = w.sym;
1662   }
1663 
1664   // Update pointers in input files.
1665   parallelForEach(objectFiles, [&](InputFile *file) {
1666     MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
1667     for (size_t i = 0, e = syms.size(); i != e; ++i)
1668       if (Symbol *s = map.lookup(syms[i]))
1669         syms[i] = s;
1670   });
1671 
1672   // Update pointers in the symbol table.
1673   for (const WrappedSymbol &w : wrapped)
1674     symtab->wrap(w.sym, w.real, w.wrap);
1675 }
1676 
1677 // To enable CET (x86's hardware-assited control flow enforcement), each
1678 // source file must be compiled with -fcf-protection. Object files compiled
1679 // with the flag contain feature flags indicating that they are compatible
1680 // with CET. We enable the feature only when all object files are compatible
1681 // with CET.
1682 //
1683 // This function returns the merged feature flags. If 0, we cannot enable CET.
1684 // This is also the case with AARCH64's BTI and PAC which use the similar
1685 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
1686 //
1687 // Note that the CET-aware PLT is not implemented yet. We do error
1688 // check only.
1689 template <class ELFT> static uint32_t getAndFeatures() {
1690   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
1691       config->emachine != EM_AARCH64)
1692     return 0;
1693 
1694   uint32_t ret = -1;
1695   for (InputFile *f : objectFiles) {
1696     uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1697     if (config->forceBTI && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
1698       warn(toString(f) + ": --force-bti: file does not have BTI property");
1699       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1700     } else if (!features && config->requireCET)
1701       error(toString(f) + ": --require-cet: file is not compatible with CET");
1702     ret &= features;
1703   }
1704 
1705   // Force enable pointer authentication Plt, we don't warn in this case as
1706   // this does not require support in the object for correctness.
1707   if (config->pacPlt)
1708     ret |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1709 
1710   return ret;
1711 }
1712 
1713 // Do actual linking. Note that when this function is called,
1714 // all linker scripts have already been parsed.
1715 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1716   // If a -hash-style option was not given, set to a default value,
1717   // which varies depending on the target.
1718   if (!args.hasArg(OPT_hash_style)) {
1719     if (config->emachine == EM_MIPS)
1720       config->sysvHash = true;
1721     else
1722       config->sysvHash = config->gnuHash = true;
1723   }
1724 
1725   // Default output filename is "a.out" by the Unix tradition.
1726   if (config->outputFile.empty())
1727     config->outputFile = "a.out";
1728 
1729   // Fail early if the output file or map file is not writable. If a user has a
1730   // long link, e.g. due to a large LTO link, they do not wish to run it and
1731   // find that it failed because there was a mistake in their command-line.
1732   if (auto e = tryCreateFile(config->outputFile))
1733     error("cannot open output file " + config->outputFile + ": " + e.message());
1734   if (auto e = tryCreateFile(config->mapFile))
1735     error("cannot open map file " + config->mapFile + ": " + e.message());
1736   if (errorCount())
1737     return;
1738 
1739   // Use default entry point name if no name was given via the command
1740   // line nor linker scripts. For some reason, MIPS entry point name is
1741   // different from others.
1742   config->warnMissingEntry =
1743       (!config->entry.empty() || (!config->shared && !config->relocatable));
1744   if (config->entry.empty() && !config->relocatable)
1745     config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
1746 
1747   // Handle --trace-symbol.
1748   for (auto *arg : args.filtered(OPT_trace_symbol))
1749     symtab->insert(arg->getValue())->traced = true;
1750 
1751   // Add all files to the symbol table. This will add almost all
1752   // symbols that we need to the symbol table. This process might
1753   // add files to the link, via autolinking, these files are always
1754   // appended to the Files vector.
1755   for (size_t i = 0; i < files.size(); ++i)
1756     parseFile(files[i]);
1757 
1758   // Now that we have every file, we can decide if we will need a
1759   // dynamic symbol table.
1760   // We need one if we were asked to export dynamic symbols or if we are
1761   // producing a shared library.
1762   // We also need one if any shared libraries are used and for pie executables
1763   // (probably because the dynamic linker needs it).
1764   config->hasDynSymTab =
1765       !sharedFiles.empty() || config->isPic || config->exportDynamic;
1766 
1767   // Some symbols (such as __ehdr_start) are defined lazily only when there
1768   // are undefined symbols for them, so we add these to trigger that logic.
1769   for (StringRef name : script->referencedSymbols)
1770     addUndefined(name);
1771 
1772   // Handle the `--undefined <sym>` options.
1773   for (StringRef arg : config->undefined)
1774     if (Symbol *sym = symtab->find(arg))
1775       handleUndefined(sym);
1776 
1777   // If an entry symbol is in a static archive, pull out that file now.
1778   if (Symbol *sym = symtab->find(config->entry))
1779     handleUndefined(sym);
1780 
1781   // Handle the `--undefined-glob <pattern>` options.
1782   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
1783     handleUndefinedGlob(pat);
1784 
1785   // If any of our inputs are bitcode files, the LTO code generator may create
1786   // references to certain library functions that might not be explicit in the
1787   // bitcode file's symbol table. If any of those library functions are defined
1788   // in a bitcode file in an archive member, we need to arrange to use LTO to
1789   // compile those archive members by adding them to the link beforehand.
1790   //
1791   // However, adding all libcall symbols to the link can have undesired
1792   // consequences. For example, the libgcc implementation of
1793   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1794   // that aborts the program if the Linux kernel does not support 64-bit
1795   // atomics, which would prevent the program from running even if it does not
1796   // use 64-bit atomics.
1797   //
1798   // Therefore, we only add libcall symbols to the link before LTO if we have
1799   // to, i.e. if the symbol's definition is in bitcode. Any other required
1800   // libcall symbols will be added to the link after LTO when we add the LTO
1801   // object file to the link.
1802   if (!bitcodeFiles.empty())
1803     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
1804       handleLibcall(s);
1805 
1806   // Return if there were name resolution errors.
1807   if (errorCount())
1808     return;
1809 
1810   // Now when we read all script files, we want to finalize order of linker
1811   // script commands, which can be not yet final because of INSERT commands.
1812   script->processInsertCommands();
1813 
1814   // We want to declare linker script's symbols early,
1815   // so that we can version them.
1816   // They also might be exported if referenced by DSOs.
1817   script->declareSymbols();
1818 
1819   // Handle the -exclude-libs option.
1820   if (args.hasArg(OPT_exclude_libs))
1821     excludeLibs(args);
1822 
1823   // Create elfHeader early. We need a dummy section in
1824   // addReservedSymbols to mark the created symbols as not absolute.
1825   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1826   Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
1827 
1828   // Create wrapped symbols for -wrap option.
1829   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
1830 
1831   // We need to create some reserved symbols such as _end. Create them.
1832   if (!config->relocatable)
1833     addReservedSymbols();
1834 
1835   // Apply version scripts.
1836   //
1837   // For a relocatable output, version scripts don't make sense, and
1838   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1839   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1840   if (!config->relocatable)
1841     symtab->scanVersionScript();
1842 
1843   // Do link-time optimization if given files are LLVM bitcode files.
1844   // This compiles bitcode files into real object files.
1845   //
1846   // With this the symbol table should be complete. After this, no new names
1847   // except a few linker-synthesized ones will be added to the symbol table.
1848   compileBitcodeFiles<ELFT>();
1849   if (errorCount())
1850     return;
1851 
1852   // If -thinlto-index-only is given, we should create only "index
1853   // files" and not object files. Index file creation is already done
1854   // in addCombinedLTOObject, so we are done if that's the case.
1855   if (config->thinLTOIndexOnly)
1856     return;
1857 
1858   // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1859   // an output file in bitcode and exit, so that you can just get a
1860   // combined bitcode file.
1861   if (config->emitLLVM)
1862     return;
1863 
1864   // Apply symbol renames for -wrap.
1865   if (!wrapped.empty())
1866     wrapSymbols(wrapped);
1867 
1868   // Now that we have a complete list of input files.
1869   // Beyond this point, no new files are added.
1870   // Aggregate all input sections into one place.
1871   for (InputFile *f : objectFiles)
1872     for (InputSectionBase *s : f->getSections())
1873       if (s && s != &InputSection::discarded)
1874         inputSections.push_back(s);
1875   for (BinaryFile *f : binaryFiles)
1876     for (InputSectionBase *s : f->getSections())
1877       inputSections.push_back(cast<InputSection>(s));
1878 
1879   llvm::erase_if(inputSections, [](InputSectionBase *s) {
1880     if (s->type == SHT_LLVM_SYMPART) {
1881       readSymbolPartitionSection<ELFT>(s);
1882       return true;
1883     }
1884 
1885     // We do not want to emit debug sections if --strip-all
1886     // or -strip-debug are given.
1887     return config->strip != StripPolicy::None &&
1888            (s->name.startswith(".debug") || s->name.startswith(".zdebug"));
1889   });
1890 
1891   // Now that the number of partitions is fixed, save a pointer to the main
1892   // partition.
1893   mainPart = &partitions[0];
1894 
1895   // Read .note.gnu.property sections from input object files which
1896   // contain a hint to tweak linker's and loader's behaviors.
1897   config->andFeatures = getAndFeatures<ELFT>();
1898 
1899   // The Target instance handles target-specific stuff, such as applying
1900   // relocations or writing a PLT section. It also contains target-dependent
1901   // values such as a default image base address.
1902   target = getTarget();
1903 
1904   config->eflags = target->calcEFlags();
1905   // maxPageSize (sometimes called abi page size) is the maximum page size that
1906   // the output can be run on. For example if the OS can use 4k or 64k page
1907   // sizes then maxPageSize must be 64k for the output to be useable on both.
1908   // All important alignment decisions must use this value.
1909   config->maxPageSize = getMaxPageSize(args);
1910   // commonPageSize is the most common page size that the output will be run on.
1911   // For example if an OS can use 4k or 64k page sizes and 4k is more common
1912   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
1913   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
1914   // is limited to writing trap instructions on the last executable segment.
1915   config->commonPageSize = getCommonPageSize(args);
1916 
1917   config->imageBase = getImageBase(args);
1918 
1919   if (config->emachine == EM_ARM) {
1920     // FIXME: These warnings can be removed when lld only uses these features
1921     // when the input objects have been compiled with an architecture that
1922     // supports them.
1923     if (config->armHasBlx == false)
1924       warn("lld uses blx instruction, no object with architecture supporting "
1925            "feature detected");
1926   }
1927 
1928   // This adds a .comment section containing a version string.
1929   if (!config->relocatable)
1930     inputSections.push_back(createCommentSection());
1931 
1932   // Replace common symbols with regular symbols.
1933   replaceCommonSymbols();
1934 
1935   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
1936   splitSections<ELFT>();
1937 
1938   // Garbage collection and removal of shared symbols from unused shared objects.
1939   markLive<ELFT>();
1940   demoteSharedSymbols();
1941 
1942   // Make copies of any input sections that need to be copied into each
1943   // partition.
1944   copySectionsIntoPartitions();
1945 
1946   // Create synthesized sections such as .got and .plt. This is called before
1947   // processSectionCommands() so that they can be placed by SECTIONS commands.
1948   createSyntheticSections<ELFT>();
1949 
1950   // Some input sections that are used for exception handling need to be moved
1951   // into synthetic sections. Do that now so that they aren't assigned to
1952   // output sections in the usual way.
1953   if (!config->relocatable)
1954     combineEhSections();
1955 
1956   // Create output sections described by SECTIONS commands.
1957   script->processSectionCommands();
1958 
1959   // Linker scripts control how input sections are assigned to output sections.
1960   // Input sections that were not handled by scripts are called "orphans", and
1961   // they are assigned to output sections by the default rule. Process that.
1962   script->addOrphanSections();
1963 
1964   // Migrate InputSectionDescription::sectionBases to sections. This includes
1965   // merging MergeInputSections into a single MergeSyntheticSection. From this
1966   // point onwards InputSectionDescription::sections should be used instead of
1967   // sectionBases.
1968   for (BaseCommand *base : script->sectionCommands)
1969     if (auto *sec = dyn_cast<OutputSection>(base))
1970       sec->finalizeInputSections();
1971   llvm::erase_if(inputSections,
1972                  [](InputSectionBase *s) { return isa<MergeInputSection>(s); });
1973 
1974   // Two input sections with different output sections should not be folded.
1975   // ICF runs after processSectionCommands() so that we know the output sections.
1976   if (config->icf != ICFLevel::None) {
1977     findKeepUniqueSections<ELFT>(args);
1978     doIcf<ELFT>();
1979   }
1980 
1981   // Read the callgraph now that we know what was gced or icfed
1982   if (config->callGraphProfileSort) {
1983     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
1984       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1985         readCallGraph(*buffer);
1986     readCallGraphsFromObjectFiles<ELFT>();
1987   }
1988 
1989   // Write the result to the file.
1990   writeResult<ELFT>();
1991 }
1992 
1993 } // namespace elf
1994 } // namespace lld
1995