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