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