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