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