xref: /freebsd/contrib/llvm-project/lld/ELF/Driver.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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/Version.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/ADT/StringSwitch.h"
50 #include "llvm/Config/llvm-config.h"
51 #include "llvm/LTO/LTO.h"
52 #include "llvm/Remarks/HotnessThresholdParser.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Compression.h"
55 #include "llvm/Support/GlobPattern.h"
56 #include "llvm/Support/LEB128.h"
57 #include "llvm/Support/Parallel.h"
58 #include "llvm/Support/Path.h"
59 #include "llvm/Support/TarWriter.h"
60 #include "llvm/Support/TargetSelect.h"
61 #include "llvm/Support/TimeProfiler.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include <cstdlib>
64 #include <utility>
65 
66 using namespace llvm;
67 using namespace llvm::ELF;
68 using namespace llvm::object;
69 using namespace llvm::sys;
70 using namespace llvm::support;
71 using namespace lld;
72 using namespace lld::elf;
73 
74 Configuration *elf::config;
75 LinkerDriver *elf::driver;
76 
77 static void setConfigs(opt::InputArgList &args);
78 static void readConfigs(opt::InputArgList &args);
79 
80 bool elf::link(ArrayRef<const char *> args, bool canExitEarly,
81                raw_ostream &stdoutOS, raw_ostream &stderrOS) {
82   lld::stdoutOS = &stdoutOS;
83   lld::stderrOS = &stderrOS;
84 
85   errorHandler().cleanupCallback = []() {
86     freeArena();
87 
88     inputSections.clear();
89     outputSections.clear();
90     archiveFiles.clear();
91     binaryFiles.clear();
92     bitcodeFiles.clear();
93     lazyObjFiles.clear();
94     objectFiles.clear();
95     sharedFiles.clear();
96     backwardReferences.clear();
97     whyExtract.clear();
98 
99     tar = nullptr;
100     memset(&in, 0, sizeof(in));
101 
102     partitions = {Partition()};
103 
104     SharedFile::vernauxNum = 0;
105   };
106 
107   errorHandler().logName = args::getFilenameWithoutExe(args[0]);
108   errorHandler().errorLimitExceededMsg =
109       "too many errors emitted, stopping now (use "
110       "-error-limit=0 to see all errors)";
111   errorHandler().exitEarly = canExitEarly;
112   stderrOS.enable_colors(stderrOS.has_colors());
113 
114   config = make<Configuration>();
115   driver = make<LinkerDriver>();
116   script = make<LinkerScript>();
117   symtab = make<SymbolTable>();
118 
119   partitions = {Partition()};
120 
121   config->progName = args[0];
122 
123   driver->linkerMain(args);
124 
125   // Exit immediately if we don't need to return to the caller.
126   // This saves time because the overhead of calling destructors
127   // for all globally-allocated objects is not negligible.
128   if (canExitEarly)
129     exitLld(errorCount() ? 1 : 0);
130 
131   bool ret = errorCount() == 0;
132   if (!canExitEarly)
133     errorHandler().reset();
134   return ret;
135 }
136 
137 // Parses a linker -m option.
138 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef emul) {
139   uint8_t osabi = 0;
140   StringRef s = emul;
141   if (s.endswith("_fbsd")) {
142     s = s.drop_back(5);
143     osabi = ELFOSABI_FREEBSD;
144   }
145 
146   std::pair<ELFKind, uint16_t> ret =
147       StringSwitch<std::pair<ELFKind, uint16_t>>(s)
148           .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
149           .Cases("aarch64elfb", "aarch64linuxb", {ELF64BEKind, EM_AARCH64})
150           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
151           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
152           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
153           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
154           .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
155           .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
156           .Cases("elf32lppc", "elf32lppclinux", {ELF32LEKind, EM_PPC})
157           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
158           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
159           .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
160           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
161           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
162           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
163           .Case("elf_i386", {ELF32LEKind, EM_386})
164           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
165           .Case("elf64_sparc", {ELF64BEKind, EM_SPARCV9})
166           .Case("msp430elf", {ELF32LEKind, EM_MSP430})
167           .Default({ELFNoneKind, EM_NONE});
168 
169   if (ret.first == ELFNoneKind)
170     error("unknown emulation: " + emul);
171   if (ret.second == EM_MSP430)
172     osabi = ELFOSABI_STANDALONE;
173   return std::make_tuple(ret.first, ret.second, osabi);
174 }
175 
176 // Returns slices of MB by parsing MB as an archive file.
177 // Each slice consists of a member file in the archive.
178 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
179     MemoryBufferRef mb) {
180   std::unique_ptr<Archive> file =
181       CHECK(Archive::create(mb),
182             mb.getBufferIdentifier() + ": failed to parse archive");
183 
184   std::vector<std::pair<MemoryBufferRef, uint64_t>> v;
185   Error err = Error::success();
186   bool addToTar = file->isThin() && tar;
187   for (const Archive::Child &c : file->children(err)) {
188     MemoryBufferRef mbref =
189         CHECK(c.getMemoryBufferRef(),
190               mb.getBufferIdentifier() +
191                   ": could not get the buffer for a child of the archive");
192     if (addToTar)
193       tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
194     v.push_back(std::make_pair(mbref, c.getChildOffset()));
195   }
196   if (err)
197     fatal(mb.getBufferIdentifier() + ": Archive::children failed: " +
198           toString(std::move(err)));
199 
200   // Take ownership of memory buffers created for members of thin archives.
201   for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
202     make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
203 
204   return v;
205 }
206 
207 // Opens a file and create a file object. Path has to be resolved already.
208 void LinkerDriver::addFile(StringRef path, bool withLOption) {
209   using namespace sys::fs;
210 
211   Optional<MemoryBufferRef> buffer = readFile(path);
212   if (!buffer.hasValue())
213     return;
214   MemoryBufferRef mbref = *buffer;
215 
216   if (config->formatBinary) {
217     files.push_back(make<BinaryFile>(mbref));
218     return;
219   }
220 
221   switch (identify_magic(mbref.getBuffer())) {
222   case file_magic::unknown:
223     readLinkerScript(mbref);
224     return;
225   case file_magic::archive: {
226     if (inWholeArchive) {
227       for (const auto &p : getArchiveMembers(mbref))
228         files.push_back(createObjectFile(p.first, path, p.second));
229       return;
230     }
231 
232     std::unique_ptr<Archive> file =
233         CHECK(Archive::create(mbref), path + ": failed to parse archive");
234 
235     // If an archive file has no symbol table, it is likely that a user
236     // is attempting LTO and using a default ar command that doesn't
237     // understand the LLVM bitcode file. It is a pretty common error, so
238     // we'll handle it as if it had a symbol table.
239     if (!file->isEmpty() && !file->hasSymbolTable()) {
240       // Check if all members are bitcode files. If not, ignore, which is the
241       // default action without the LTO hack described above.
242       for (const std::pair<MemoryBufferRef, uint64_t> &p :
243            getArchiveMembers(mbref))
244         if (identify_magic(p.first.getBuffer()) != file_magic::bitcode) {
245           error(path + ": archive has no index; run ranlib to add one");
246           return;
247         }
248 
249       for (const std::pair<MemoryBufferRef, uint64_t> &p :
250            getArchiveMembers(mbref))
251         files.push_back(make<LazyObjFile>(p.first, path, p.second));
252       return;
253     }
254 
255     // Handle the regular case.
256     files.push_back(make<ArchiveFile>(std::move(file)));
257     return;
258   }
259   case file_magic::elf_shared_object:
260     if (config->isStatic || config->relocatable) {
261       error("attempted static link of dynamic object " + path);
262       return;
263     }
264 
265     // Shared objects are identified by soname. soname is (if specified)
266     // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
267     // the directory part is ignored. Note that path may be a temporary and
268     // cannot be stored into SharedFile::soName.
269     path = mbref.getBufferIdentifier();
270     files.push_back(
271         make<SharedFile>(mbref, withLOption ? path::filename(path) : path));
272     return;
273   case file_magic::bitcode:
274   case file_magic::elf_relocatable:
275     if (inLib)
276       files.push_back(make<LazyObjFile>(mbref, "", 0));
277     else
278       files.push_back(createObjectFile(mbref));
279     break;
280   default:
281     error(path + ": unknown file type");
282   }
283 }
284 
285 // Add a given library by searching it from input search paths.
286 void LinkerDriver::addLibrary(StringRef name) {
287   if (Optional<std::string> path = searchLibrary(name))
288     addFile(*path, /*withLOption=*/true);
289   else
290     error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
291 }
292 
293 // This function is called on startup. We need this for LTO since
294 // LTO calls LLVM functions to compile bitcode files to native code.
295 // Technically this can be delayed until we read bitcode files, but
296 // we don't bother to do lazily because the initialization is fast.
297 static void initLLVM() {
298   InitializeAllTargets();
299   InitializeAllTargetMCs();
300   InitializeAllAsmPrinters();
301   InitializeAllAsmParsers();
302 }
303 
304 // Some command line options or some combinations of them are not allowed.
305 // This function checks for such errors.
306 static void checkOptions() {
307   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
308   // table which is a relatively new feature.
309   if (config->emachine == EM_MIPS && config->gnuHash)
310     error("the .gnu.hash section is not compatible with the MIPS target");
311 
312   if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
313     error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
314 
315   if (config->fixCortexA8 && config->emachine != EM_ARM)
316     error("--fix-cortex-a8 is only supported on ARM targets");
317 
318   if (config->tocOptimize && config->emachine != EM_PPC64)
319     error("--toc-optimize is only supported on PowerPC64 targets");
320 
321   if (config->pcRelOptimize && config->emachine != EM_PPC64)
322     error("--pcrel-optimize is only supported on PowerPC64 targets");
323 
324   if (config->pie && config->shared)
325     error("-shared and -pie may not be used together");
326 
327   if (!config->shared && !config->filterList.empty())
328     error("-F may not be used without -shared");
329 
330   if (!config->shared && !config->auxiliaryList.empty())
331     error("-f may not be used without -shared");
332 
333   if (!config->relocatable && !config->defineCommon)
334     error("-no-define-common not supported in non relocatable output");
335 
336   if (config->strip == StripPolicy::All && config->emitRelocs)
337     error("--strip-all and --emit-relocs may not be used together");
338 
339   if (config->zText && config->zIfuncNoplt)
340     error("-z text and -z ifunc-noplt may not be used together");
341 
342   if (config->relocatable) {
343     if (config->shared)
344       error("-r and -shared may not be used together");
345     if (config->gdbIndex)
346       error("-r and --gdb-index may not be used together");
347     if (config->icf != ICFLevel::None)
348       error("-r and --icf may not be used together");
349     if (config->pie)
350       error("-r and -pie may not be used together");
351     if (config->exportDynamic)
352       error("-r and --export-dynamic may not be used together");
353   }
354 
355   if (config->executeOnly) {
356     if (config->emachine != EM_AARCH64)
357       error("--execute-only is only supported on AArch64 targets");
358 
359     if (config->singleRoRx && !script->hasSectionsCommand)
360       error("--execute-only and --no-rosegment cannot be used together");
361   }
362 
363   if (config->zRetpolineplt && config->zForceIbt)
364     error("-z force-ibt may not be used with -z retpolineplt");
365 
366   if (config->emachine != EM_AARCH64) {
367     if (config->zPacPlt)
368       error("-z pac-plt only supported on AArch64");
369     if (config->zForceBti)
370       error("-z force-bti only supported on AArch64");
371   }
372 }
373 
374 static const char *getReproduceOption(opt::InputArgList &args) {
375   if (auto *arg = args.getLastArg(OPT_reproduce))
376     return arg->getValue();
377   return getenv("LLD_REPRODUCE");
378 }
379 
380 static bool hasZOption(opt::InputArgList &args, StringRef key) {
381   for (auto *arg : args.filtered(OPT_z))
382     if (key == arg->getValue())
383       return true;
384   return false;
385 }
386 
387 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
388                      bool Default) {
389   for (auto *arg : args.filtered_reverse(OPT_z)) {
390     if (k1 == arg->getValue())
391       return true;
392     if (k2 == arg->getValue())
393       return false;
394   }
395   return Default;
396 }
397 
398 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
399   for (auto *arg : args.filtered_reverse(OPT_z)) {
400     StringRef v = arg->getValue();
401     if (v == "noseparate-code")
402       return SeparateSegmentKind::None;
403     if (v == "separate-code")
404       return SeparateSegmentKind::Code;
405     if (v == "separate-loadable-segments")
406       return SeparateSegmentKind::Loadable;
407   }
408   return SeparateSegmentKind::None;
409 }
410 
411 static GnuStackKind getZGnuStack(opt::InputArgList &args) {
412   for (auto *arg : args.filtered_reverse(OPT_z)) {
413     if (StringRef("execstack") == arg->getValue())
414       return GnuStackKind::Exec;
415     if (StringRef("noexecstack") == arg->getValue())
416       return GnuStackKind::NoExec;
417     if (StringRef("nognustack") == arg->getValue())
418       return GnuStackKind::None;
419   }
420 
421   return GnuStackKind::NoExec;
422 }
423 
424 static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
425   for (auto *arg : args.filtered_reverse(OPT_z)) {
426     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
427     if (kv.first == "start-stop-visibility") {
428       if (kv.second == "default")
429         return STV_DEFAULT;
430       else if (kv.second == "internal")
431         return STV_INTERNAL;
432       else if (kv.second == "hidden")
433         return STV_HIDDEN;
434       else if (kv.second == "protected")
435         return STV_PROTECTED;
436       error("unknown -z start-stop-visibility= value: " + StringRef(kv.second));
437     }
438   }
439   return STV_PROTECTED;
440 }
441 
442 static bool isKnownZFlag(StringRef s) {
443   return s == "combreloc" || s == "copyreloc" || s == "defs" ||
444          s == "execstack" || s == "force-bti" || s == "force-ibt" ||
445          s == "global" || s == "hazardplt" || s == "ifunc-noplt" ||
446          s == "initfirst" || s == "interpose" ||
447          s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
448          s == "separate-code" || s == "separate-loadable-segments" ||
449          s == "start-stop-gc" || s == "nocombreloc" || s == "nocopyreloc" ||
450          s == "nodefaultlib" || s == "nodelete" || s == "nodlopen" ||
451          s == "noexecstack" || s == "nognustack" ||
452          s == "nokeep-text-section-prefix" || s == "norelro" ||
453          s == "noseparate-code" || s == "nostart-stop-gc" || s == "notext" ||
454          s == "now" || s == "origin" || s == "pac-plt" || s == "rel" ||
455          s == "rela" || s == "relro" || s == "retpolineplt" ||
456          s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" ||
457          s == "wxneeded" || s.startswith("common-page-size=") ||
458          s.startswith("dead-reloc-in-nonalloc=") ||
459          s.startswith("max-page-size=") || s.startswith("stack-size=") ||
460          s.startswith("start-stop-visibility=");
461 }
462 
463 // Report a warning for an unknown -z option.
464 static void checkZOptions(opt::InputArgList &args) {
465   for (auto *arg : args.filtered(OPT_z))
466     if (!isKnownZFlag(arg->getValue()))
467       warn("unknown -z value: " + StringRef(arg->getValue()));
468 }
469 
470 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
471   ELFOptTable parser;
472   opt::InputArgList args = parser.parse(argsArr.slice(1));
473 
474   // Interpret the flags early because error()/warn() depend on them.
475   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
476   errorHandler().fatalWarnings =
477       args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
478   checkZOptions(args);
479 
480   // Handle -help
481   if (args.hasArg(OPT_help)) {
482     printHelp();
483     return;
484   }
485 
486   // Handle -v or -version.
487   //
488   // A note about "compatible with GNU linkers" message: this is a hack for
489   // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
490   // a GNU compatible linker. See
491   // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
492   //
493   // This is somewhat ugly hack, but in reality, we had no choice other
494   // than doing this. Considering the very long release cycle of Libtool,
495   // it is not easy to improve it to recognize LLD as a GNU compatible
496   // linker in a timely manner. Even if we can make it, there are still a
497   // lot of "configure" scripts out there that are generated by old version
498   // of Libtool. We cannot convince every software developer to migrate to
499   // the latest version and re-generate scripts. So we have this hack.
500   if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
501     message(getLLDVersion() + " (compatible with GNU linkers)");
502 
503   if (const char *path = getReproduceOption(args)) {
504     // Note that --reproduce is a debug option so you can ignore it
505     // if you are trying to understand the whole picture of the code.
506     Expected<std::unique_ptr<TarWriter>> errOrWriter =
507         TarWriter::create(path, path::stem(path));
508     if (errOrWriter) {
509       tar = std::move(*errOrWriter);
510       tar->append("response.txt", createResponseFile(args));
511       tar->append("version.txt", getLLDVersion() + "\n");
512       StringRef ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
513       if (!ltoSampleProfile.empty())
514         readFile(ltoSampleProfile);
515     } else {
516       error("--reproduce: " + toString(errOrWriter.takeError()));
517     }
518   }
519 
520   readConfigs(args);
521 
522   // The behavior of -v or --version is a bit strange, but this is
523   // needed for compatibility with GNU linkers.
524   if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT))
525     return;
526   if (args.hasArg(OPT_version))
527     return;
528 
529   // Initialize time trace profiler.
530   if (config->timeTraceEnabled)
531     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
532 
533   {
534     llvm::TimeTraceScope timeScope("ExecuteLinker");
535 
536     initLLVM();
537     createFiles(args);
538     if (errorCount())
539       return;
540 
541     inferMachineType();
542     setConfigs(args);
543     checkOptions();
544     if (errorCount())
545       return;
546 
547     // The Target instance handles target-specific stuff, such as applying
548     // relocations or writing a PLT section. It also contains target-dependent
549     // values such as a default image base address.
550     target = getTarget();
551 
552     switch (config->ekind) {
553     case ELF32LEKind:
554       link<ELF32LE>(args);
555       break;
556     case ELF32BEKind:
557       link<ELF32BE>(args);
558       break;
559     case ELF64LEKind:
560       link<ELF64LE>(args);
561       break;
562     case ELF64BEKind:
563       link<ELF64BE>(args);
564       break;
565     default:
566       llvm_unreachable("unknown Config->EKind");
567     }
568   }
569 
570   if (config->timeTraceEnabled) {
571     checkError(timeTraceProfilerWrite(
572         args.getLastArgValue(OPT_time_trace_file_eq).str(),
573         config->outputFile));
574     timeTraceProfilerCleanup();
575   }
576 }
577 
578 static std::string getRpath(opt::InputArgList &args) {
579   std::vector<StringRef> v = args::getStrings(args, OPT_rpath);
580   return llvm::join(v.begin(), v.end(), ":");
581 }
582 
583 // Determines what we should do if there are remaining unresolved
584 // symbols after the name resolution.
585 static void setUnresolvedSymbolPolicy(opt::InputArgList &args) {
586   UnresolvedPolicy errorOrWarn = args.hasFlag(OPT_error_unresolved_symbols,
587                                               OPT_warn_unresolved_symbols, true)
588                                      ? UnresolvedPolicy::ReportError
589                                      : UnresolvedPolicy::Warn;
590   // -shared implies --unresolved-symbols=ignore-all because missing
591   // symbols are likely to be resolved at runtime.
592   bool diagRegular = !config->shared, diagShlib = !config->shared;
593 
594   for (const opt::Arg *arg : args) {
595     switch (arg->getOption().getID()) {
596     case OPT_unresolved_symbols: {
597       StringRef s = arg->getValue();
598       if (s == "ignore-all") {
599         diagRegular = false;
600         diagShlib = false;
601       } else if (s == "ignore-in-object-files") {
602         diagRegular = false;
603         diagShlib = true;
604       } else if (s == "ignore-in-shared-libs") {
605         diagRegular = true;
606         diagShlib = false;
607       } else if (s == "report-all") {
608         diagRegular = true;
609         diagShlib = true;
610       } else {
611         error("unknown --unresolved-symbols value: " + s);
612       }
613       break;
614     }
615     case OPT_no_undefined:
616       diagRegular = true;
617       break;
618     case OPT_z:
619       if (StringRef(arg->getValue()) == "defs")
620         diagRegular = true;
621       else if (StringRef(arg->getValue()) == "undefs")
622         diagRegular = false;
623       break;
624     case OPT_allow_shlib_undefined:
625       diagShlib = false;
626       break;
627     case OPT_no_allow_shlib_undefined:
628       diagShlib = true;
629       break;
630     }
631   }
632 
633   config->unresolvedSymbols =
634       diagRegular ? errorOrWarn : UnresolvedPolicy::Ignore;
635   config->unresolvedSymbolsInShlib =
636       diagShlib ? errorOrWarn : UnresolvedPolicy::Ignore;
637 }
638 
639 static Target2Policy getTarget2(opt::InputArgList &args) {
640   StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
641   if (s == "rel")
642     return Target2Policy::Rel;
643   if (s == "abs")
644     return Target2Policy::Abs;
645   if (s == "got-rel")
646     return Target2Policy::GotRel;
647   error("unknown --target2 option: " + s);
648   return Target2Policy::GotRel;
649 }
650 
651 static bool isOutputFormatBinary(opt::InputArgList &args) {
652   StringRef s = args.getLastArgValue(OPT_oformat, "elf");
653   if (s == "binary")
654     return true;
655   if (!s.startswith("elf"))
656     error("unknown --oformat value: " + s);
657   return false;
658 }
659 
660 static DiscardPolicy getDiscard(opt::InputArgList &args) {
661   auto *arg =
662       args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
663   if (!arg)
664     return DiscardPolicy::Default;
665   if (arg->getOption().getID() == OPT_discard_all)
666     return DiscardPolicy::All;
667   if (arg->getOption().getID() == OPT_discard_locals)
668     return DiscardPolicy::Locals;
669   return DiscardPolicy::None;
670 }
671 
672 static StringRef getDynamicLinker(opt::InputArgList &args) {
673   auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
674   if (!arg)
675     return "";
676   if (arg->getOption().getID() == OPT_no_dynamic_linker) {
677     // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
678     config->noDynamicLinker = true;
679     return "";
680   }
681   return arg->getValue();
682 }
683 
684 static ICFLevel getICF(opt::InputArgList &args) {
685   auto *arg = args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
686   if (!arg || arg->getOption().getID() == OPT_icf_none)
687     return ICFLevel::None;
688   if (arg->getOption().getID() == OPT_icf_safe)
689     return ICFLevel::Safe;
690   return ICFLevel::All;
691 }
692 
693 static StripPolicy getStrip(opt::InputArgList &args) {
694   if (args.hasArg(OPT_relocatable))
695     return StripPolicy::None;
696 
697   auto *arg = args.getLastArg(OPT_strip_all, OPT_strip_debug);
698   if (!arg)
699     return StripPolicy::None;
700   if (arg->getOption().getID() == OPT_strip_all)
701     return StripPolicy::All;
702   return StripPolicy::Debug;
703 }
704 
705 static uint64_t parseSectionAddress(StringRef s, opt::InputArgList &args,
706                                     const opt::Arg &arg) {
707   uint64_t va = 0;
708   if (s.startswith("0x"))
709     s = s.drop_front(2);
710   if (!to_integer(s, va, 16))
711     error("invalid argument: " + arg.getAsString(args));
712   return va;
713 }
714 
715 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &args) {
716   StringMap<uint64_t> ret;
717   for (auto *arg : args.filtered(OPT_section_start)) {
718     StringRef name;
719     StringRef addr;
720     std::tie(name, addr) = StringRef(arg->getValue()).split('=');
721     ret[name] = parseSectionAddress(addr, args, *arg);
722   }
723 
724   if (auto *arg = args.getLastArg(OPT_Ttext))
725     ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
726   if (auto *arg = args.getLastArg(OPT_Tdata))
727     ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
728   if (auto *arg = args.getLastArg(OPT_Tbss))
729     ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
730   return ret;
731 }
732 
733 static SortSectionPolicy getSortSection(opt::InputArgList &args) {
734   StringRef s = args.getLastArgValue(OPT_sort_section);
735   if (s == "alignment")
736     return SortSectionPolicy::Alignment;
737   if (s == "name")
738     return SortSectionPolicy::Name;
739   if (!s.empty())
740     error("unknown --sort-section rule: " + s);
741   return SortSectionPolicy::Default;
742 }
743 
744 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &args) {
745   StringRef s = args.getLastArgValue(OPT_orphan_handling, "place");
746   if (s == "warn")
747     return OrphanHandlingPolicy::Warn;
748   if (s == "error")
749     return OrphanHandlingPolicy::Error;
750   if (s != "place")
751     error("unknown --orphan-handling mode: " + s);
752   return OrphanHandlingPolicy::Place;
753 }
754 
755 // Parse --build-id or --build-id=<style>. We handle "tree" as a
756 // synonym for "sha1" because all our hash functions including
757 // --build-id=sha1 are actually tree hashes for performance reasons.
758 static std::pair<BuildIdKind, std::vector<uint8_t>>
759 getBuildId(opt::InputArgList &args) {
760   auto *arg = args.getLastArg(OPT_build_id, OPT_build_id_eq);
761   if (!arg)
762     return {BuildIdKind::None, {}};
763 
764   if (arg->getOption().getID() == OPT_build_id)
765     return {BuildIdKind::Fast, {}};
766 
767   StringRef s = arg->getValue();
768   if (s == "fast")
769     return {BuildIdKind::Fast, {}};
770   if (s == "md5")
771     return {BuildIdKind::Md5, {}};
772   if (s == "sha1" || s == "tree")
773     return {BuildIdKind::Sha1, {}};
774   if (s == "uuid")
775     return {BuildIdKind::Uuid, {}};
776   if (s.startswith("0x"))
777     return {BuildIdKind::Hexstring, parseHex(s.substr(2))};
778 
779   if (s != "none")
780     error("unknown --build-id style: " + s);
781   return {BuildIdKind::None, {}};
782 }
783 
784 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &args) {
785   StringRef s = args.getLastArgValue(OPT_pack_dyn_relocs, "none");
786   if (s == "android")
787     return {true, false};
788   if (s == "relr")
789     return {false, true};
790   if (s == "android+relr")
791     return {true, true};
792 
793   if (s != "none")
794     error("unknown --pack-dyn-relocs format: " + s);
795   return {false, false};
796 }
797 
798 static void readCallGraph(MemoryBufferRef mb) {
799   // Build a map from symbol name to section
800   DenseMap<StringRef, Symbol *> map;
801   for (InputFile *file : objectFiles)
802     for (Symbol *sym : file->getSymbols())
803       map[sym->getName()] = sym;
804 
805   auto findSection = [&](StringRef name) -> InputSectionBase * {
806     Symbol *sym = map.lookup(name);
807     if (!sym) {
808       if (config->warnSymbolOrdering)
809         warn(mb.getBufferIdentifier() + ": no such symbol: " + name);
810       return nullptr;
811     }
812     maybeWarnUnorderableSymbol(sym);
813 
814     if (Defined *dr = dyn_cast_or_null<Defined>(sym))
815       return dyn_cast_or_null<InputSectionBase>(dr->section);
816     return nullptr;
817   };
818 
819   for (StringRef line : args::getLines(mb)) {
820     SmallVector<StringRef, 3> fields;
821     line.split(fields, ' ');
822     uint64_t count;
823 
824     if (fields.size() != 3 || !to_integer(fields[2], count)) {
825       error(mb.getBufferIdentifier() + ": parse error");
826       return;
827     }
828 
829     if (InputSectionBase *from = findSection(fields[0]))
830       if (InputSectionBase *to = findSection(fields[1]))
831         config->callGraphProfile[std::make_pair(from, to)] += count;
832   }
833 }
834 
835 // If SHT_LLVM_CALL_GRAPH_PROFILE and its relocation section exist, returns
836 // true and populates cgProfile and symbolIndices.
837 template <class ELFT>
838 static bool
839 processCallGraphRelocations(SmallVector<uint32_t, 32> &symbolIndices,
840                             ArrayRef<typename ELFT::CGProfile> &cgProfile,
841                             ObjFile<ELFT> *inputObj) {
842   symbolIndices.clear();
843   const ELFFile<ELFT> &obj = inputObj->getObj();
844   ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
845       CHECK(obj.sections(), "could not retrieve object sections");
846 
847   if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
848     return false;
849 
850   cgProfile =
851       check(obj.template getSectionContentsAsArray<typename ELFT::CGProfile>(
852           objSections[inputObj->cgProfileSectionIndex]));
853 
854   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
855     const Elf_Shdr_Impl<ELFT> &sec = objSections[i];
856     if (sec.sh_info == inputObj->cgProfileSectionIndex) {
857       if (sec.sh_type == SHT_RELA) {
858         ArrayRef<typename ELFT::Rela> relas =
859             CHECK(obj.relas(sec), "could not retrieve cg profile rela section");
860         for (const typename ELFT::Rela &rel : relas)
861           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
862         break;
863       }
864       if (sec.sh_type == SHT_REL) {
865         ArrayRef<typename ELFT::Rel> rels =
866             CHECK(obj.rels(sec), "could not retrieve cg profile rel section");
867         for (const typename ELFT::Rel &rel : rels)
868           symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
869         break;
870       }
871     }
872   }
873   if (symbolIndices.empty())
874     warn("SHT_LLVM_CALL_GRAPH_PROFILE exists, but relocation section doesn't");
875   return !symbolIndices.empty();
876 }
877 
878 template <class ELFT> static void readCallGraphsFromObjectFiles() {
879   SmallVector<uint32_t, 32> symbolIndices;
880   ArrayRef<typename ELFT::CGProfile> cgProfile;
881   for (auto file : objectFiles) {
882     auto *obj = cast<ObjFile<ELFT>>(file);
883     if (!processCallGraphRelocations(symbolIndices, cgProfile, obj))
884       continue;
885 
886     if (symbolIndices.size() != cgProfile.size() * 2)
887       fatal("number of relocations doesn't match Weights");
888 
889     for (uint32_t i = 0, size = cgProfile.size(); i < size; ++i) {
890       const Elf_CGProfile_Impl<ELFT> &cgpe = cgProfile[i];
891       uint32_t fromIndex = symbolIndices[i * 2];
892       uint32_t toIndex = symbolIndices[i * 2 + 1];
893       auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
894       auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
895       if (!fromSym || !toSym)
896         continue;
897 
898       auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
899       auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
900       if (from && to)
901         config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
902     }
903   }
904 }
905 
906 static bool getCompressDebugSections(opt::InputArgList &args) {
907   StringRef s = args.getLastArgValue(OPT_compress_debug_sections, "none");
908   if (s == "none")
909     return false;
910   if (s != "zlib")
911     error("unknown --compress-debug-sections value: " + s);
912   if (!zlib::isAvailable())
913     error("--compress-debug-sections: zlib is not available");
914   return true;
915 }
916 
917 static StringRef getAliasSpelling(opt::Arg *arg) {
918   if (const opt::Arg *alias = arg->getAlias())
919     return alias->getSpelling();
920   return arg->getSpelling();
921 }
922 
923 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
924                                                         unsigned id) {
925   auto *arg = args.getLastArg(id);
926   if (!arg)
927     return {"", ""};
928 
929   StringRef s = arg->getValue();
930   std::pair<StringRef, StringRef> ret = s.split(';');
931   if (ret.second.empty())
932     error(getAliasSpelling(arg) + " expects 'old;new' format, but got " + s);
933   return ret;
934 }
935 
936 // Parse the symbol ordering file and warn for any duplicate entries.
937 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef mb) {
938   SetVector<StringRef> names;
939   for (StringRef s : args::getLines(mb))
940     if (!names.insert(s) && config->warnSymbolOrdering)
941       warn(mb.getBufferIdentifier() + ": duplicate ordered symbol: " + s);
942 
943   return names.takeVector();
944 }
945 
946 static bool getIsRela(opt::InputArgList &args) {
947   // If -z rel or -z rela is specified, use the last option.
948   for (auto *arg : args.filtered_reverse(OPT_z)) {
949     StringRef s(arg->getValue());
950     if (s == "rel")
951       return false;
952     if (s == "rela")
953       return true;
954   }
955 
956   // Otherwise use the psABI defined relocation entry format.
957   uint16_t m = config->emachine;
958   return m == EM_AARCH64 || m == EM_AMDGPU || m == EM_HEXAGON || m == EM_PPC ||
959          m == EM_PPC64 || m == EM_RISCV || m == EM_X86_64;
960 }
961 
962 static void parseClangOption(StringRef opt, const Twine &msg) {
963   std::string err;
964   raw_string_ostream os(err);
965 
966   const char *argv[] = {config->progName.data(), opt.data()};
967   if (cl::ParseCommandLineOptions(2, argv, "", &os))
968     return;
969   os.flush();
970   error(msg + ": " + StringRef(err).trim());
971 }
972 
973 // Initializes Config members by the command line options.
974 static void readConfigs(opt::InputArgList &args) {
975   errorHandler().verbose = args.hasArg(OPT_verbose);
976   errorHandler().vsDiagnostics =
977       args.hasArg(OPT_visual_studio_diagnostics_format, false);
978 
979   config->allowMultipleDefinition =
980       args.hasFlag(OPT_allow_multiple_definition,
981                    OPT_no_allow_multiple_definition, false) ||
982       hasZOption(args, "muldefs");
983   config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
984   if (opt::Arg *arg =
985           args.getLastArg(OPT_Bno_symbolic, OPT_Bsymbolic_non_weak_functions,
986                           OPT_Bsymbolic_functions, OPT_Bsymbolic)) {
987     if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
988       config->bsymbolic = BsymbolicKind::NonWeakFunctions;
989     else if (arg->getOption().matches(OPT_Bsymbolic_functions))
990       config->bsymbolic = BsymbolicKind::Functions;
991     else if (arg->getOption().matches(OPT_Bsymbolic))
992       config->bsymbolic = BsymbolicKind::All;
993   }
994   config->checkSections =
995       args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
996   config->chroot = args.getLastArgValue(OPT_chroot);
997   config->compressDebugSections = getCompressDebugSections(args);
998   config->cref = args.hasArg(OPT_cref);
999   config->defineCommon = args.hasFlag(OPT_define_common, OPT_no_define_common,
1000                                       !args.hasArg(OPT_relocatable));
1001   config->optimizeBBJumps =
1002       args.hasFlag(OPT_optimize_bb_jumps, OPT_no_optimize_bb_jumps, false);
1003   config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
1004   config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
1005   config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
1006   config->disableVerify = args.hasArg(OPT_disable_verify);
1007   config->discard = getDiscard(args);
1008   config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
1009   config->dynamicLinker = getDynamicLinker(args);
1010   config->ehFrameHdr =
1011       args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
1012   config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
1013   config->emitRelocs = args.hasArg(OPT_emit_relocs);
1014   config->callGraphProfileSort = args.hasFlag(
1015       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
1016   config->enableNewDtags =
1017       args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
1018   config->entry = args.getLastArgValue(OPT_entry);
1019 
1020   errorHandler().errorHandlingScript =
1021       args.getLastArgValue(OPT_error_handling_script);
1022 
1023   config->executeOnly =
1024       args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
1025   config->exportDynamic =
1026       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
1027   config->filterList = args::getStrings(args, OPT_filter);
1028   config->fini = args.getLastArgValue(OPT_fini, "_fini");
1029   config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
1030                                      !args.hasArg(OPT_relocatable);
1031   config->fixCortexA8 =
1032       args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
1033   config->fortranCommon =
1034       args.hasFlag(OPT_fortran_common, OPT_no_fortran_common, true);
1035   config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
1036   config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
1037   config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
1038   config->icf = getICF(args);
1039   config->ignoreDataAddressEquality =
1040       args.hasArg(OPT_ignore_data_address_equality);
1041   config->ignoreFunctionAddressEquality =
1042       args.hasArg(OPT_ignore_function_address_equality);
1043   config->init = args.getLastArgValue(OPT_init, "_init");
1044   config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
1045   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1046   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1047   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1048                                             OPT_no_lto_pgo_warn_mismatch, true);
1049   config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
1050   config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
1051   config->ltoNewPassManager =
1052       args.hasFlag(OPT_no_lto_legacy_pass_manager, OPT_lto_legacy_pass_manager,
1053                    LLVM_ENABLE_NEW_PASS_MANAGER);
1054   config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
1055   config->ltoWholeProgramVisibility =
1056       args.hasFlag(OPT_lto_whole_program_visibility,
1057                    OPT_no_lto_whole_program_visibility, false);
1058   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
1059   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
1060   config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
1061   config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
1062   config->ltoBasicBlockSections =
1063       args.getLastArgValue(OPT_lto_basic_block_sections);
1064   config->ltoUniqueBasicBlockSectionNames =
1065       args.hasFlag(OPT_lto_unique_basic_block_section_names,
1066                    OPT_no_lto_unique_basic_block_section_names, false);
1067   config->mapFile = args.getLastArgValue(OPT_Map);
1068   config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
1069   config->mergeArmExidx =
1070       args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
1071   config->mmapOutputFile =
1072       args.hasFlag(OPT_mmap_output_file, OPT_no_mmap_output_file, true);
1073   config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
1074   config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
1075   config->nostdlib = args.hasArg(OPT_nostdlib);
1076   config->oFormatBinary = isOutputFormatBinary(args);
1077   config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
1078   config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
1079 
1080   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1081   if (auto *arg = args.getLastArg(OPT_opt_remarks_hotness_threshold)) {
1082     auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());
1083     if (!resultOrErr)
1084       error(arg->getSpelling() + ": invalid argument '" + arg->getValue() +
1085             "', only integer or 'auto' is supported");
1086     else
1087       config->optRemarksHotnessThreshold = *resultOrErr;
1088   }
1089 
1090   config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
1091   config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
1092   config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
1093   config->optimize = args::getInteger(args, OPT_O, 1);
1094   config->orphanHandling = getOrphanHandling(args);
1095   config->outputFile = args.getLastArgValue(OPT_o);
1096   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
1097   config->printIcfSections =
1098       args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
1099   config->printGcSections =
1100       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
1101   config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
1102   config->printSymbolOrder =
1103       args.getLastArgValue(OPT_print_symbol_order);
1104   config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true);
1105   config->rpath = getRpath(args);
1106   config->relocatable = args.hasArg(OPT_relocatable);
1107   config->saveTemps = args.hasArg(OPT_save_temps);
1108   config->searchPaths = args::getStrings(args, OPT_library_path);
1109   config->sectionStartMap = getSectionStartMap(args);
1110   config->shared = args.hasArg(OPT_shared);
1111   config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
1112   config->soName = args.getLastArgValue(OPT_soname);
1113   config->sortSection = getSortSection(args);
1114   config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
1115   config->strip = getStrip(args);
1116   config->sysroot = args.getLastArgValue(OPT_sysroot);
1117   config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
1118   config->target2 = getTarget2(args);
1119   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
1120   config->thinLTOCachePolicy = CHECK(
1121       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
1122       "--thinlto-cache-policy: invalid cache policy");
1123   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1124   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1125                              args.hasArg(OPT_thinlto_index_only_eq);
1126   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1127   config->thinLTOObjectSuffixReplace =
1128       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
1129   config->thinLTOPrefixReplace =
1130       getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
1131   config->thinLTOModulesToCompile =
1132       args::getStrings(args, OPT_thinlto_single_module_eq);
1133   config->timeTraceEnabled = args.hasArg(OPT_time_trace);
1134   config->timeTraceGranularity =
1135       args::getInteger(args, OPT_time_trace_granularity, 500);
1136   config->trace = args.hasArg(OPT_trace);
1137   config->undefined = args::getStrings(args, OPT_undefined);
1138   config->undefinedVersion =
1139       args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
1140   config->unique = args.hasArg(OPT_unique);
1141   config->useAndroidRelrTags = args.hasFlag(
1142       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
1143   config->warnBackrefs =
1144       args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
1145   config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
1146   config->warnSymbolOrdering =
1147       args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1148   config->whyExtract = args.getLastArgValue(OPT_why_extract);
1149   config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
1150   config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
1151   config->zForceBti = hasZOption(args, "force-bti");
1152   config->zForceIbt = hasZOption(args, "force-ibt");
1153   config->zGlobal = hasZOption(args, "global");
1154   config->zGnustack = getZGnuStack(args);
1155   config->zHazardplt = hasZOption(args, "hazardplt");
1156   config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
1157   config->zInitfirst = hasZOption(args, "initfirst");
1158   config->zInterpose = hasZOption(args, "interpose");
1159   config->zKeepTextSectionPrefix = getZFlag(
1160       args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
1161   config->zNodefaultlib = hasZOption(args, "nodefaultlib");
1162   config->zNodelete = hasZOption(args, "nodelete");
1163   config->zNodlopen = hasZOption(args, "nodlopen");
1164   config->zNow = getZFlag(args, "now", "lazy", false);
1165   config->zOrigin = hasZOption(args, "origin");
1166   config->zPacPlt = hasZOption(args, "pac-plt");
1167   config->zRelro = getZFlag(args, "relro", "norelro", true);
1168   config->zRetpolineplt = hasZOption(args, "retpolineplt");
1169   config->zRodynamic = hasZOption(args, "rodynamic");
1170   config->zSeparate = getZSeparate(args);
1171   config->zShstk = hasZOption(args, "shstk");
1172   config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1173   config->zStartStopGC =
1174       getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);
1175   config->zStartStopVisibility = getZStartStopVisibility(args);
1176   config->zText = getZFlag(args, "text", "notext", true);
1177   config->zWxneeded = hasZOption(args, "wxneeded");
1178   setUnresolvedSymbolPolicy(args);
1179   config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";
1180 
1181   if (opt::Arg *arg = args.getLastArg(OPT_eb, OPT_el)) {
1182     if (arg->getOption().matches(OPT_eb))
1183       config->optEB = true;
1184     else
1185       config->optEL = true;
1186   }
1187 
1188   for (opt::Arg *arg : args.filtered(OPT_shuffle_sections)) {
1189     constexpr StringRef errPrefix = "--shuffle-sections=: ";
1190     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
1191     if (kv.first.empty() || kv.second.empty()) {
1192       error(errPrefix + "expected <section_glob>=<seed>, but got '" +
1193             arg->getValue() + "'");
1194       continue;
1195     }
1196     // Signed so that <section_glob>=-1 is allowed.
1197     int64_t v;
1198     if (!to_integer(kv.second, v))
1199       error(errPrefix + "expected an integer, but got '" + kv.second + "'");
1200     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1201       config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v));
1202     else
1203       error(errPrefix + toString(pat.takeError()));
1204   }
1205 
1206   for (opt::Arg *arg : args.filtered(OPT_z)) {
1207     std::pair<StringRef, StringRef> option =
1208         StringRef(arg->getValue()).split('=');
1209     if (option.first != "dead-reloc-in-nonalloc")
1210       continue;
1211     constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
1212     std::pair<StringRef, StringRef> kv = option.second.split('=');
1213     if (kv.first.empty() || kv.second.empty()) {
1214       error(errPrefix + "expected <section_glob>=<value>");
1215       continue;
1216     }
1217     uint64_t v;
1218     if (!to_integer(kv.second, v))
1219       error(errPrefix + "expected a non-negative integer, but got '" +
1220             kv.second + "'");
1221     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1222       config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
1223     else
1224       error(errPrefix + toString(pat.takeError()));
1225   }
1226 
1227   cl::ResetAllOptionOccurrences();
1228 
1229   // Parse LTO options.
1230   if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
1231     parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
1232                      arg->getSpelling());
1233 
1234   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
1235     parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
1236 
1237   // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1238   // relative path. Just ignore. If not ended with "lto-wrapper", consider it an
1239   // unsupported LLVMgold.so option and error.
1240   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq))
1241     if (!StringRef(arg->getValue()).endswith("lto-wrapper"))
1242       error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
1243             "'");
1244 
1245   // Parse -mllvm options.
1246   for (auto *arg : args.filtered(OPT_mllvm))
1247     parseClangOption(arg->getValue(), arg->getSpelling());
1248 
1249   // --threads= takes a positive integer and provides the default value for
1250   // --thinlto-jobs=.
1251   if (auto *arg = args.getLastArg(OPT_threads)) {
1252     StringRef v(arg->getValue());
1253     unsigned threads = 0;
1254     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1255       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1256             arg->getValue() + "'");
1257     parallel::strategy = hardware_concurrency(threads);
1258     config->thinLTOJobs = v;
1259   }
1260   if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
1261     config->thinLTOJobs = arg->getValue();
1262 
1263   if (config->ltoo > 3)
1264     error("invalid optimization level for LTO: " + Twine(config->ltoo));
1265   if (config->ltoPartitions == 0)
1266     error("--lto-partitions: number of threads must be > 0");
1267   if (!get_threadpool_strategy(config->thinLTOJobs))
1268     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1269 
1270   if (config->splitStackAdjustSize < 0)
1271     error("--split-stack-adjust-size: size must be >= 0");
1272 
1273   // The text segment is traditionally the first segment, whose address equals
1274   // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1275   // is an old-fashioned option that does not play well with lld's layout.
1276   // Suggest --image-base as a likely alternative.
1277   if (args.hasArg(OPT_Ttext_segment))
1278     error("-Ttext-segment is not supported. Use --image-base if you "
1279           "intend to set the base address");
1280 
1281   // Parse ELF{32,64}{LE,BE} and CPU type.
1282   if (auto *arg = args.getLastArg(OPT_m)) {
1283     StringRef s = arg->getValue();
1284     std::tie(config->ekind, config->emachine, config->osabi) =
1285         parseEmulation(s);
1286     config->mipsN32Abi =
1287         (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
1288     config->emulation = s;
1289   }
1290 
1291   // Parse --hash-style={sysv,gnu,both}.
1292   if (auto *arg = args.getLastArg(OPT_hash_style)) {
1293     StringRef s = arg->getValue();
1294     if (s == "sysv")
1295       config->sysvHash = true;
1296     else if (s == "gnu")
1297       config->gnuHash = true;
1298     else if (s == "both")
1299       config->sysvHash = config->gnuHash = true;
1300     else
1301       error("unknown --hash-style: " + s);
1302   }
1303 
1304   if (args.hasArg(OPT_print_map))
1305     config->mapFile = "-";
1306 
1307   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1308   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1309   // it.
1310   if (config->nmagic || config->omagic)
1311     config->zRelro = false;
1312 
1313   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1314 
1315   std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1316       getPackDynRelocs(args);
1317 
1318   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1319     if (args.hasArg(OPT_call_graph_ordering_file))
1320       error("--symbol-ordering-file and --call-graph-order-file "
1321             "may not be used together");
1322     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1323       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1324       // Also need to disable CallGraphProfileSort to prevent
1325       // LLD order symbols with CGProfile
1326       config->callGraphProfileSort = false;
1327     }
1328   }
1329 
1330   assert(config->versionDefinitions.empty());
1331   config->versionDefinitions.push_back(
1332       {"local", (uint16_t)VER_NDX_LOCAL, {}, {}});
1333   config->versionDefinitions.push_back(
1334       {"global", (uint16_t)VER_NDX_GLOBAL, {}, {}});
1335 
1336   // If --retain-symbol-file is used, we'll keep only the symbols listed in
1337   // the file and discard all others.
1338   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1339     config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
1340         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1341     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1342       for (StringRef s : args::getLines(*buffer))
1343         config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
1344             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1345   }
1346 
1347   for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
1348     StringRef pattern(arg->getValue());
1349     if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
1350       config->warnBackrefsExclude.push_back(std::move(*pat));
1351     else
1352       error(arg->getSpelling() + ": " + toString(pat.takeError()));
1353   }
1354 
1355   // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1356   // which should be exported. For -shared, references to matched non-local
1357   // STV_DEFAULT symbols are not bound to definitions within the shared object,
1358   // even if other options express a symbolic intention: -Bsymbolic,
1359   // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1360   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1361     config->dynamicList.push_back(
1362         {arg->getValue(), /*isExternCpp=*/false,
1363          /*hasWildcard=*/hasWildcard(arg->getValue())});
1364 
1365   // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1366   // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1367   // like semantics.
1368   config->symbolic =
1369       config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1370   for (auto *arg :
1371        args.filtered(OPT_dynamic_list, OPT_export_dynamic_symbol_list))
1372     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1373       readDynamicList(*buffer);
1374 
1375   for (auto *arg : args.filtered(OPT_version_script))
1376     if (Optional<std::string> path = searchScript(arg->getValue())) {
1377       if (Optional<MemoryBufferRef> buffer = readFile(*path))
1378         readVersionScript(*buffer);
1379     } else {
1380       error(Twine("cannot find version script ") + arg->getValue());
1381     }
1382 }
1383 
1384 // Some Config members do not directly correspond to any particular
1385 // command line options, but computed based on other Config values.
1386 // This function initialize such members. See Config.h for the details
1387 // of these values.
1388 static void setConfigs(opt::InputArgList &args) {
1389   ELFKind k = config->ekind;
1390   uint16_t m = config->emachine;
1391 
1392   config->copyRelocs = (config->relocatable || config->emitRelocs);
1393   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1394   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1395   config->endianness = config->isLE ? endianness::little : endianness::big;
1396   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1397   config->isPic = config->pie || config->shared;
1398   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1399   config->wordsize = config->is64 ? 8 : 4;
1400 
1401   // ELF defines two different ways to store relocation addends as shown below:
1402   //
1403   //  Rel: Addends are stored to the location where relocations are applied. It
1404   //  cannot pack the full range of addend values for all relocation types, but
1405   //  this only affects relocation types that we don't support emitting as
1406   //  dynamic relocations (see getDynRel).
1407   //  Rela: Addends are stored as part of relocation entry.
1408   //
1409   // In other words, Rela makes it easy to read addends at the price of extra
1410   // 4 or 8 byte for each relocation entry.
1411   //
1412   // We pick the format for dynamic relocations according to the psABI for each
1413   // processor, but a contrary choice can be made if the dynamic loader
1414   // supports.
1415   config->isRela = getIsRela(args);
1416 
1417   // If the output uses REL relocations we must store the dynamic relocation
1418   // addends to the output sections. We also store addends for RELA relocations
1419   // if --apply-dynamic-relocs is used.
1420   // We default to not writing the addends when using RELA relocations since
1421   // any standard conforming tool can find it in r_addend.
1422   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1423                                       OPT_no_apply_dynamic_relocs, false) ||
1424                          !config->isRela;
1425   // Validation of dynamic relocation addends is on by default for assertions
1426   // builds (for supported targets) and disabled otherwise. Ideally we would
1427   // enable the debug checks for all targets, but currently not all targets
1428   // have support for reading Elf_Rel addends, so we only enable for a subset.
1429 #ifndef NDEBUG
1430   bool checkDynamicRelocsDefault = m == EM_ARM || m == EM_386 || m == EM_MIPS ||
1431                                    m == EM_X86_64 || m == EM_RISCV;
1432 #else
1433   bool checkDynamicRelocsDefault = false;
1434 #endif
1435   config->checkDynamicRelocs =
1436       args.hasFlag(OPT_check_dynamic_relocations,
1437                    OPT_no_check_dynamic_relocations, checkDynamicRelocsDefault);
1438   config->tocOptimize =
1439       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1440   config->pcRelOptimize =
1441       args.hasFlag(OPT_pcrel_optimize, OPT_no_pcrel_optimize, m == EM_PPC64);
1442 }
1443 
1444 static bool isFormatBinary(StringRef s) {
1445   if (s == "binary")
1446     return true;
1447   if (s == "elf" || s == "default")
1448     return false;
1449   error("unknown --format value: " + s +
1450         " (supported formats: elf, default, binary)");
1451   return false;
1452 }
1453 
1454 void LinkerDriver::createFiles(opt::InputArgList &args) {
1455   llvm::TimeTraceScope timeScope("Load input files");
1456   // For --{push,pop}-state.
1457   std::vector<std::tuple<bool, bool, bool>> stack;
1458 
1459   // Iterate over argv to process input files and positional arguments.
1460   InputFile::isInGroup = false;
1461   for (auto *arg : args) {
1462     switch (arg->getOption().getID()) {
1463     case OPT_library:
1464       addLibrary(arg->getValue());
1465       break;
1466     case OPT_INPUT:
1467       addFile(arg->getValue(), /*withLOption=*/false);
1468       break;
1469     case OPT_defsym: {
1470       StringRef from;
1471       StringRef to;
1472       std::tie(from, to) = StringRef(arg->getValue()).split('=');
1473       if (from.empty() || to.empty())
1474         error("--defsym: syntax error: " + StringRef(arg->getValue()));
1475       else
1476         readDefsym(from, MemoryBufferRef(to, "--defsym"));
1477       break;
1478     }
1479     case OPT_script:
1480       if (Optional<std::string> path = searchScript(arg->getValue())) {
1481         if (Optional<MemoryBufferRef> mb = readFile(*path))
1482           readLinkerScript(*mb);
1483         break;
1484       }
1485       error(Twine("cannot find linker script ") + arg->getValue());
1486       break;
1487     case OPT_as_needed:
1488       config->asNeeded = true;
1489       break;
1490     case OPT_format:
1491       config->formatBinary = isFormatBinary(arg->getValue());
1492       break;
1493     case OPT_no_as_needed:
1494       config->asNeeded = false;
1495       break;
1496     case OPT_Bstatic:
1497     case OPT_omagic:
1498     case OPT_nmagic:
1499       config->isStatic = true;
1500       break;
1501     case OPT_Bdynamic:
1502       config->isStatic = false;
1503       break;
1504     case OPT_whole_archive:
1505       inWholeArchive = true;
1506       break;
1507     case OPT_no_whole_archive:
1508       inWholeArchive = false;
1509       break;
1510     case OPT_just_symbols:
1511       if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1512         files.push_back(createObjectFile(*mb));
1513         files.back()->justSymbols = true;
1514       }
1515       break;
1516     case OPT_start_group:
1517       if (InputFile::isInGroup)
1518         error("nested --start-group");
1519       InputFile::isInGroup = true;
1520       break;
1521     case OPT_end_group:
1522       if (!InputFile::isInGroup)
1523         error("stray --end-group");
1524       InputFile::isInGroup = false;
1525       ++InputFile::nextGroupId;
1526       break;
1527     case OPT_start_lib:
1528       if (inLib)
1529         error("nested --start-lib");
1530       if (InputFile::isInGroup)
1531         error("may not nest --start-lib in --start-group");
1532       inLib = true;
1533       InputFile::isInGroup = true;
1534       break;
1535     case OPT_end_lib:
1536       if (!inLib)
1537         error("stray --end-lib");
1538       inLib = false;
1539       InputFile::isInGroup = false;
1540       ++InputFile::nextGroupId;
1541       break;
1542     case OPT_push_state:
1543       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1544       break;
1545     case OPT_pop_state:
1546       if (stack.empty()) {
1547         error("unbalanced --push-state/--pop-state");
1548         break;
1549       }
1550       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1551       stack.pop_back();
1552       break;
1553     }
1554   }
1555 
1556   if (files.empty() && errorCount() == 0)
1557     error("no input files");
1558 }
1559 
1560 // If -m <machine_type> was not given, infer it from object files.
1561 void LinkerDriver::inferMachineType() {
1562   if (config->ekind != ELFNoneKind)
1563     return;
1564 
1565   for (InputFile *f : files) {
1566     if (f->ekind == ELFNoneKind)
1567       continue;
1568     config->ekind = f->ekind;
1569     config->emachine = f->emachine;
1570     config->osabi = f->osabi;
1571     config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1572     return;
1573   }
1574   error("target emulation unknown: -m or at least one .o file required");
1575 }
1576 
1577 // Parse -z max-page-size=<value>. The default value is defined by
1578 // each target.
1579 static uint64_t getMaxPageSize(opt::InputArgList &args) {
1580   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1581                                        target->defaultMaxPageSize);
1582   if (!isPowerOf2_64(val))
1583     error("max-page-size: value isn't a power of 2");
1584   if (config->nmagic || config->omagic) {
1585     if (val != target->defaultMaxPageSize)
1586       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1587     return 1;
1588   }
1589   return val;
1590 }
1591 
1592 // Parse -z common-page-size=<value>. The default value is defined by
1593 // each target.
1594 static uint64_t getCommonPageSize(opt::InputArgList &args) {
1595   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1596                                        target->defaultCommonPageSize);
1597   if (!isPowerOf2_64(val))
1598     error("common-page-size: value isn't a power of 2");
1599   if (config->nmagic || config->omagic) {
1600     if (val != target->defaultCommonPageSize)
1601       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1602     return 1;
1603   }
1604   // commonPageSize can't be larger than maxPageSize.
1605   if (val > config->maxPageSize)
1606     val = config->maxPageSize;
1607   return val;
1608 }
1609 
1610 // Parses --image-base option.
1611 static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1612   // Because we are using "Config->maxPageSize" here, this function has to be
1613   // called after the variable is initialized.
1614   auto *arg = args.getLastArg(OPT_image_base);
1615   if (!arg)
1616     return None;
1617 
1618   StringRef s = arg->getValue();
1619   uint64_t v;
1620   if (!to_integer(s, v)) {
1621     error("--image-base: number expected, but got " + s);
1622     return 0;
1623   }
1624   if ((v % config->maxPageSize) != 0)
1625     warn("--image-base: address isn't multiple of page size: " + s);
1626   return v;
1627 }
1628 
1629 // Parses `--exclude-libs=lib,lib,...`.
1630 // The library names may be delimited by commas or colons.
1631 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1632   DenseSet<StringRef> ret;
1633   for (auto *arg : args.filtered(OPT_exclude_libs)) {
1634     StringRef s = arg->getValue();
1635     for (;;) {
1636       size_t pos = s.find_first_of(",:");
1637       if (pos == StringRef::npos)
1638         break;
1639       ret.insert(s.substr(0, pos));
1640       s = s.substr(pos + 1);
1641     }
1642     ret.insert(s);
1643   }
1644   return ret;
1645 }
1646 
1647 // Handles the --exclude-libs option. If a static library file is specified
1648 // by the --exclude-libs option, all public symbols from the archive become
1649 // private unless otherwise specified by version scripts or something.
1650 // A special library name "ALL" means all archive files.
1651 //
1652 // This is not a popular option, but some programs such as bionic libc use it.
1653 static void excludeLibs(opt::InputArgList &args) {
1654   DenseSet<StringRef> libs = getExcludeLibs(args);
1655   bool all = libs.count("ALL");
1656 
1657   auto visit = [&](InputFile *file) {
1658     if (!file->archiveName.empty())
1659       if (all || libs.count(path::filename(file->archiveName)))
1660         for (Symbol *sym : file->getSymbols())
1661           if (!sym->isUndefined() && !sym->isLocal() && sym->file == file)
1662             sym->versionId = VER_NDX_LOCAL;
1663   };
1664 
1665   for (InputFile *file : objectFiles)
1666     visit(file);
1667 
1668   for (BitcodeFile *file : bitcodeFiles)
1669     visit(file);
1670 }
1671 
1672 // Force Sym to be entered in the output.
1673 static void handleUndefined(Symbol *sym, const char *option) {
1674   // Since a symbol may not be used inside the program, LTO may
1675   // eliminate it. Mark the symbol as "used" to prevent it.
1676   sym->isUsedInRegularObj = true;
1677 
1678   if (!sym->isLazy())
1679     return;
1680   sym->extract();
1681   if (!config->whyExtract.empty())
1682     whyExtract.emplace_back(option, sym->file, *sym);
1683 }
1684 
1685 // As an extension to GNU linkers, lld supports a variant of `-u`
1686 // which accepts wildcard patterns. All symbols that match a given
1687 // pattern are handled as if they were given by `-u`.
1688 static void handleUndefinedGlob(StringRef arg) {
1689   Expected<GlobPattern> pat = GlobPattern::create(arg);
1690   if (!pat) {
1691     error("--undefined-glob: " + toString(pat.takeError()));
1692     return;
1693   }
1694 
1695   // Calling sym->extract() in the loop is not safe because it may add new
1696   // symbols to the symbol table, invalidating the current iterator.
1697   std::vector<Symbol *> syms;
1698   for (Symbol *sym : symtab->symbols())
1699     if (pat->match(sym->getName()))
1700       syms.push_back(sym);
1701 
1702   for (Symbol *sym : syms)
1703     handleUndefined(sym, "--undefined-glob");
1704 }
1705 
1706 static void handleLibcall(StringRef name) {
1707   Symbol *sym = symtab->find(name);
1708   if (!sym || !sym->isLazy())
1709     return;
1710 
1711   MemoryBufferRef mb;
1712   if (auto *lo = dyn_cast<LazyObject>(sym))
1713     mb = lo->file->mb;
1714   else
1715     mb = cast<LazyArchive>(sym)->getMemberBuffer();
1716 
1717   if (isBitcode(mb))
1718     sym->extract();
1719 }
1720 
1721 // Handle --dependency-file=<path>. If that option is given, lld creates a
1722 // file at a given path with the following contents:
1723 //
1724 //   <output-file>: <input-file> ...
1725 //
1726 //   <input-file>:
1727 //
1728 // where <output-file> is a pathname of an output file and <input-file>
1729 // ... is a list of pathnames of all input files. `make` command can read a
1730 // file in the above format and interpret it as a dependency info. We write
1731 // phony targets for every <input-file> to avoid an error when that file is
1732 // removed.
1733 //
1734 // This option is useful if you want to make your final executable to depend
1735 // on all input files including system libraries. Here is why.
1736 //
1737 // When you write a Makefile, you usually write it so that the final
1738 // executable depends on all user-generated object files. Normally, you
1739 // don't make your executable to depend on system libraries (such as libc)
1740 // because you don't know the exact paths of libraries, even though system
1741 // libraries that are linked to your executable statically are technically a
1742 // part of your program. By using --dependency-file option, you can make
1743 // lld to dump dependency info so that you can maintain exact dependencies
1744 // easily.
1745 static void writeDependencyFile() {
1746   std::error_code ec;
1747   raw_fd_ostream os(config->dependencyFile, ec, sys::fs::OF_None);
1748   if (ec) {
1749     error("cannot open " + config->dependencyFile + ": " + ec.message());
1750     return;
1751   }
1752 
1753   // We use the same escape rules as Clang/GCC which are accepted by Make/Ninja:
1754   // * A space is escaped by a backslash which itself must be escaped.
1755   // * A hash sign is escaped by a single backslash.
1756   // * $ is escapes as $$.
1757   auto printFilename = [](raw_fd_ostream &os, StringRef filename) {
1758     llvm::SmallString<256> nativePath;
1759     llvm::sys::path::native(filename.str(), nativePath);
1760     llvm::sys::path::remove_dots(nativePath, /*remove_dot_dot=*/true);
1761     for (unsigned i = 0, e = nativePath.size(); i != e; ++i) {
1762       if (nativePath[i] == '#') {
1763         os << '\\';
1764       } else if (nativePath[i] == ' ') {
1765         os << '\\';
1766         unsigned j = i;
1767         while (j > 0 && nativePath[--j] == '\\')
1768           os << '\\';
1769       } else if (nativePath[i] == '$') {
1770         os << '$';
1771       }
1772       os << nativePath[i];
1773     }
1774   };
1775 
1776   os << config->outputFile << ":";
1777   for (StringRef path : config->dependencyFiles) {
1778     os << " \\\n ";
1779     printFilename(os, path);
1780   }
1781   os << "\n";
1782 
1783   for (StringRef path : config->dependencyFiles) {
1784     os << "\n";
1785     printFilename(os, path);
1786     os << ":\n";
1787   }
1788 }
1789 
1790 // Replaces common symbols with defined symbols reside in .bss sections.
1791 // This function is called after all symbol names are resolved. As a
1792 // result, the passes after the symbol resolution won't see any
1793 // symbols of type CommonSymbol.
1794 static void replaceCommonSymbols() {
1795   llvm::TimeTraceScope timeScope("Replace common symbols");
1796   for (Symbol *sym : symtab->symbols()) {
1797     auto *s = dyn_cast<CommonSymbol>(sym);
1798     if (!s)
1799       continue;
1800 
1801     auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1802     bss->file = s->file;
1803     bss->markDead();
1804     inputSections.push_back(bss);
1805     s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
1806                        /*value=*/0, s->size, bss});
1807   }
1808 }
1809 
1810 // If all references to a DSO happen to be weak, the DSO is not added
1811 // to DT_NEEDED. If that happens, we need to eliminate shared symbols
1812 // created from the DSO. Otherwise, they become dangling references
1813 // that point to a non-existent DSO.
1814 static void demoteSharedSymbols() {
1815   llvm::TimeTraceScope timeScope("Demote shared symbols");
1816   for (Symbol *sym : symtab->symbols()) {
1817     auto *s = dyn_cast<SharedSymbol>(sym);
1818     if (!((s && !s->getFile().isNeeded) ||
1819           (sym->isLazy() && sym->isUsedInRegularObj)))
1820       continue;
1821 
1822     bool used = sym->used;
1823     sym->replace(
1824         Undefined{nullptr, sym->getName(), STB_WEAK, sym->stOther, sym->type});
1825     sym->used = used;
1826     sym->versionId = VER_NDX_GLOBAL;
1827   }
1828 }
1829 
1830 // The section referred to by `s` is considered address-significant. Set the
1831 // keepUnique flag on the section if appropriate.
1832 static void markAddrsig(Symbol *s) {
1833   if (auto *d = dyn_cast_or_null<Defined>(s))
1834     if (d->section)
1835       // We don't need to keep text sections unique under --icf=all even if they
1836       // are address-significant.
1837       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
1838         d->section->keepUnique = true;
1839 }
1840 
1841 // Record sections that define symbols mentioned in --keep-unique <symbol>
1842 // and symbols referred to by address-significance tables. These sections are
1843 // ineligible for ICF.
1844 template <class ELFT>
1845 static void findKeepUniqueSections(opt::InputArgList &args) {
1846   for (auto *arg : args.filtered(OPT_keep_unique)) {
1847     StringRef name = arg->getValue();
1848     auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1849     if (!d || !d->section) {
1850       warn("could not find symbol " + name + " to keep unique");
1851       continue;
1852     }
1853     d->section->keepUnique = true;
1854   }
1855 
1856   // --icf=all --ignore-data-address-equality means that we can ignore
1857   // the dynsym and address-significance tables entirely.
1858   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
1859     return;
1860 
1861   // Symbols in the dynsym could be address-significant in other executables
1862   // or DSOs, so we conservatively mark them as address-significant.
1863   for (Symbol *sym : symtab->symbols())
1864     if (sym->includeInDynsym())
1865       markAddrsig(sym);
1866 
1867   // Visit the address-significance table in each object file and mark each
1868   // referenced symbol as address-significant.
1869   for (InputFile *f : objectFiles) {
1870     auto *obj = cast<ObjFile<ELFT>>(f);
1871     ArrayRef<Symbol *> syms = obj->getSymbols();
1872     if (obj->addrsigSec) {
1873       ArrayRef<uint8_t> contents =
1874           check(obj->getObj().getSectionContents(*obj->addrsigSec));
1875       const uint8_t *cur = contents.begin();
1876       while (cur != contents.end()) {
1877         unsigned size;
1878         const char *err;
1879         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1880         if (err)
1881           fatal(toString(f) + ": could not decode addrsig section: " + err);
1882         markAddrsig(syms[symIndex]);
1883         cur += size;
1884       }
1885     } else {
1886       // If an object file does not have an address-significance table,
1887       // conservatively mark all of its symbols as address-significant.
1888       for (Symbol *s : syms)
1889         markAddrsig(s);
1890     }
1891   }
1892 }
1893 
1894 // This function reads a symbol partition specification section. These sections
1895 // are used to control which partition a symbol is allocated to. See
1896 // https://lld.llvm.org/Partitions.html for more details on partitions.
1897 template <typename ELFT>
1898 static void readSymbolPartitionSection(InputSectionBase *s) {
1899   // Read the relocation that refers to the partition's entry point symbol.
1900   Symbol *sym;
1901   const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
1902   if (rels.areRelocsRel())
1903     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.rels[0]);
1904   else
1905     sym = &s->getFile<ELFT>()->getRelocTargetSym(rels.relas[0]);
1906   if (!isa<Defined>(sym) || !sym->includeInDynsym())
1907     return;
1908 
1909   StringRef partName = reinterpret_cast<const char *>(s->data().data());
1910   for (Partition &part : partitions) {
1911     if (part.name == partName) {
1912       sym->partition = part.getNumber();
1913       return;
1914     }
1915   }
1916 
1917   // Forbid partitions from being used on incompatible targets, and forbid them
1918   // from being used together with various linker features that assume a single
1919   // set of output sections.
1920   if (script->hasSectionsCommand)
1921     error(toString(s->file) +
1922           ": partitions cannot be used with the SECTIONS command");
1923   if (script->hasPhdrsCommands())
1924     error(toString(s->file) +
1925           ": partitions cannot be used with the PHDRS command");
1926   if (!config->sectionStartMap.empty())
1927     error(toString(s->file) + ": partitions cannot be used with "
1928                               "--section-start, -Ttext, -Tdata or -Tbss");
1929   if (config->emachine == EM_MIPS)
1930     error(toString(s->file) + ": partitions cannot be used on this target");
1931 
1932   // Impose a limit of no more than 254 partitions. This limit comes from the
1933   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1934   // the amount of space devoted to the partition number in RankFlags.
1935   if (partitions.size() == 254)
1936     fatal("may not have more than 254 partitions");
1937 
1938   partitions.emplace_back();
1939   Partition &newPart = partitions.back();
1940   newPart.name = partName;
1941   sym->partition = newPart.getNumber();
1942 }
1943 
1944 static Symbol *addUndefined(StringRef name) {
1945   return symtab->addSymbol(
1946       Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
1947 }
1948 
1949 static Symbol *addUnusedUndefined(StringRef name,
1950                                   uint8_t binding = STB_GLOBAL) {
1951   Undefined sym{nullptr, name, binding, STV_DEFAULT, 0};
1952   sym.isUsedInRegularObj = false;
1953   return symtab->addSymbol(sym);
1954 }
1955 
1956 // This function is where all the optimizations of link-time
1957 // optimization takes place. When LTO is in use, some input files are
1958 // not in native object file format but in the LLVM bitcode format.
1959 // This function compiles bitcode files into a few big native files
1960 // using LLVM functions and replaces bitcode symbols with the results.
1961 // Because all bitcode files that the program consists of are passed to
1962 // the compiler at once, it can do a whole-program optimization.
1963 template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1964   llvm::TimeTraceScope timeScope("LTO");
1965   // Compile bitcode files and replace bitcode symbols.
1966   lto.reset(new BitcodeCompiler);
1967   for (BitcodeFile *file : bitcodeFiles)
1968     lto->add(*file);
1969 
1970   for (InputFile *file : lto->compile()) {
1971     auto *obj = cast<ObjFile<ELFT>>(file);
1972     obj->parse(/*ignoreComdats=*/true);
1973 
1974     // Parse '@' in symbol names for non-relocatable output.
1975     if (!config->relocatable)
1976       for (Symbol *sym : obj->getGlobalSymbols())
1977         sym->parseSymbolVersion();
1978     objectFiles.push_back(file);
1979   }
1980 }
1981 
1982 // The --wrap option is a feature to rename symbols so that you can write
1983 // wrappers for existing functions. If you pass `--wrap=foo`, all
1984 // occurrences of symbol `foo` are resolved to `__wrap_foo` (so, you are
1985 // expected to write `__wrap_foo` function as a wrapper). The original
1986 // symbol becomes accessible as `__real_foo`, so you can call that from your
1987 // wrapper.
1988 //
1989 // This data structure is instantiated for each --wrap option.
1990 struct WrappedSymbol {
1991   Symbol *sym;
1992   Symbol *real;
1993   Symbol *wrap;
1994 };
1995 
1996 // Handles --wrap option.
1997 //
1998 // This function instantiates wrapper symbols. At this point, they seem
1999 // like they are not being used at all, so we explicitly set some flags so
2000 // that LTO won't eliminate them.
2001 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
2002   std::vector<WrappedSymbol> v;
2003   DenseSet<StringRef> seen;
2004 
2005   for (auto *arg : args.filtered(OPT_wrap)) {
2006     StringRef name = arg->getValue();
2007     if (!seen.insert(name).second)
2008       continue;
2009 
2010     Symbol *sym = symtab->find(name);
2011     if (!sym)
2012       continue;
2013 
2014     Symbol *real = addUnusedUndefined(saver.save("__real_" + name));
2015     Symbol *wrap =
2016         addUnusedUndefined(saver.save("__wrap_" + name), sym->binding);
2017     v.push_back({sym, real, wrap});
2018 
2019     // We want to tell LTO not to inline symbols to be overwritten
2020     // because LTO doesn't know the final symbol contents after renaming.
2021     real->canInline = false;
2022     sym->canInline = false;
2023 
2024     // Tell LTO not to eliminate these symbols.
2025     sym->isUsedInRegularObj = true;
2026     // If sym is referenced in any object file, bitcode file or shared object,
2027     // retain wrap which is the redirection target of sym. If the object file
2028     // defining sym has sym references, we cannot easily distinguish the case
2029     // from cases where sym is not referenced. Retain wrap because we choose to
2030     // wrap sym references regardless of whether sym is defined
2031     // (https://sourceware.org/bugzilla/show_bug.cgi?id=26358).
2032     if (sym->referenced || sym->isDefined())
2033       wrap->isUsedInRegularObj = true;
2034   }
2035   return v;
2036 }
2037 
2038 // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
2039 //
2040 // When this function is executed, only InputFiles and symbol table
2041 // contain pointers to symbol objects. We visit them to replace pointers,
2042 // so that wrapped symbols are swapped as instructed by the command line.
2043 static void redirectSymbols(ArrayRef<WrappedSymbol> wrapped) {
2044   llvm::TimeTraceScope timeScope("Redirect symbols");
2045   DenseMap<Symbol *, Symbol *> map;
2046   for (const WrappedSymbol &w : wrapped) {
2047     map[w.sym] = w.wrap;
2048     map[w.real] = w.sym;
2049   }
2050   for (Symbol *sym : symtab->symbols()) {
2051     // Enumerate symbols with a non-default version (foo@v1).
2052     StringRef name = sym->getName();
2053     const char *suffix1 = sym->getVersionSuffix();
2054     if (suffix1[0] != '@' || suffix1[1] == '@')
2055       continue;
2056 
2057     // Check the existing symbol foo. We have two special cases to handle:
2058     //
2059     // * There is a definition of foo@v1 and foo@@v1.
2060     // * There is a definition of foo@v1 and foo.
2061     Defined *sym2 = dyn_cast_or_null<Defined>(symtab->find(name));
2062     if (!sym2)
2063       continue;
2064     const char *suffix2 = sym2->getVersionSuffix();
2065     if (suffix2[0] == '@' && suffix2[1] == '@' &&
2066         strcmp(suffix1 + 1, suffix2 + 2) == 0) {
2067       // foo@v1 and foo@@v1 should be merged, so redirect foo@v1 to foo@@v1.
2068       map.try_emplace(sym, sym2);
2069       // If both foo@v1 and foo@@v1 are defined and non-weak, report a duplicate
2070       // definition error.
2071       sym2->resolve(*sym);
2072       // Eliminate foo@v1 from the symbol table.
2073       sym->symbolKind = Symbol::PlaceholderKind;
2074     } else if (auto *sym1 = dyn_cast<Defined>(sym)) {
2075       if (sym2->versionId > VER_NDX_GLOBAL
2076               ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1
2077               : sym1->section == sym2->section && sym1->value == sym2->value) {
2078         // Due to an assembler design flaw, if foo is defined, .symver foo,
2079         // foo@v1 defines both foo and foo@v1. Unless foo is bound to a
2080         // different version, GNU ld makes foo@v1 canonical and eliminates foo.
2081         // Emulate its behavior, otherwise we would have foo or foo@@v1 beside
2082         // foo@v1. foo@v1 and foo combining does not apply if they are not
2083         // defined in the same place.
2084         map.try_emplace(sym2, sym);
2085         sym2->symbolKind = Symbol::PlaceholderKind;
2086       }
2087     }
2088   }
2089 
2090   if (map.empty())
2091     return;
2092 
2093   // Update pointers in input files.
2094   parallelForEach(objectFiles, [&](InputFile *file) {
2095     MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
2096     for (size_t i = 0, e = syms.size(); i != e; ++i)
2097       if (Symbol *s = map.lookup(syms[i]))
2098         syms[i] = s;
2099   });
2100 
2101   // Update pointers in the symbol table.
2102   for (const WrappedSymbol &w : wrapped)
2103     symtab->wrap(w.sym, w.real, w.wrap);
2104 }
2105 
2106 // To enable CET (x86's hardware-assited control flow enforcement), each
2107 // source file must be compiled with -fcf-protection. Object files compiled
2108 // with the flag contain feature flags indicating that they are compatible
2109 // with CET. We enable the feature only when all object files are compatible
2110 // with CET.
2111 //
2112 // This is also the case with AARCH64's BTI and PAC which use the similar
2113 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
2114 template <class ELFT> static uint32_t getAndFeatures() {
2115   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
2116       config->emachine != EM_AARCH64)
2117     return 0;
2118 
2119   uint32_t ret = -1;
2120   for (InputFile *f : objectFiles) {
2121     uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
2122     if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
2123       warn(toString(f) + ": -z force-bti: file does not have "
2124                          "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
2125       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
2126     } else if (config->zForceIbt &&
2127                !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
2128       warn(toString(f) + ": -z force-ibt: file does not have "
2129                          "GNU_PROPERTY_X86_FEATURE_1_IBT property");
2130       features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
2131     }
2132     if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
2133       warn(toString(f) + ": -z pac-plt: file does not have "
2134                          "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
2135       features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
2136     }
2137     ret &= features;
2138   }
2139 
2140   // Force enable Shadow Stack.
2141   if (config->zShstk)
2142     ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
2143 
2144   return ret;
2145 }
2146 
2147 // Do actual linking. Note that when this function is called,
2148 // all linker scripts have already been parsed.
2149 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
2150   llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
2151   // If a --hash-style option was not given, set to a default value,
2152   // which varies depending on the target.
2153   if (!args.hasArg(OPT_hash_style)) {
2154     if (config->emachine == EM_MIPS)
2155       config->sysvHash = true;
2156     else
2157       config->sysvHash = config->gnuHash = true;
2158   }
2159 
2160   // Default output filename is "a.out" by the Unix tradition.
2161   if (config->outputFile.empty())
2162     config->outputFile = "a.out";
2163 
2164   // Fail early if the output file or map file is not writable. If a user has a
2165   // long link, e.g. due to a large LTO link, they do not wish to run it and
2166   // find that it failed because there was a mistake in their command-line.
2167   {
2168     llvm::TimeTraceScope timeScope("Create output files");
2169     if (auto e = tryCreateFile(config->outputFile))
2170       error("cannot open output file " + config->outputFile + ": " +
2171             e.message());
2172     if (auto e = tryCreateFile(config->mapFile))
2173       error("cannot open map file " + config->mapFile + ": " + e.message());
2174     if (auto e = tryCreateFile(config->whyExtract))
2175       error("cannot open --why-extract= file " + config->whyExtract + ": " +
2176             e.message());
2177   }
2178   if (errorCount())
2179     return;
2180 
2181   // Use default entry point name if no name was given via the command
2182   // line nor linker scripts. For some reason, MIPS entry point name is
2183   // different from others.
2184   config->warnMissingEntry =
2185       (!config->entry.empty() || (!config->shared && !config->relocatable));
2186   if (config->entry.empty() && !config->relocatable)
2187     config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
2188 
2189   // Handle --trace-symbol.
2190   for (auto *arg : args.filtered(OPT_trace_symbol))
2191     symtab->insert(arg->getValue())->traced = true;
2192 
2193   // Handle -u/--undefined before input files. If both a.a and b.so define foo,
2194   // -u foo a.a b.so will extract a.a.
2195   for (StringRef name : config->undefined)
2196     addUnusedUndefined(name)->referenced = true;
2197 
2198   // Add all files to the symbol table. This will add almost all
2199   // symbols that we need to the symbol table. This process might
2200   // add files to the link, via autolinking, these files are always
2201   // appended to the Files vector.
2202   {
2203     llvm::TimeTraceScope timeScope("Parse input files");
2204     for (size_t i = 0; i < files.size(); ++i) {
2205       llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
2206       parseFile(files[i]);
2207     }
2208   }
2209 
2210   // Now that we have every file, we can decide if we will need a
2211   // dynamic symbol table.
2212   // We need one if we were asked to export dynamic symbols or if we are
2213   // producing a shared library.
2214   // We also need one if any shared libraries are used and for pie executables
2215   // (probably because the dynamic linker needs it).
2216   config->hasDynSymTab =
2217       !sharedFiles.empty() || config->isPic || config->exportDynamic;
2218 
2219   // Some symbols (such as __ehdr_start) are defined lazily only when there
2220   // are undefined symbols for them, so we add these to trigger that logic.
2221   for (StringRef name : script->referencedSymbols)
2222     addUndefined(name);
2223 
2224   // Prevent LTO from removing any definition referenced by -u.
2225   for (StringRef name : config->undefined)
2226     if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name)))
2227       sym->isUsedInRegularObj = true;
2228 
2229   // If an entry symbol is in a static archive, pull out that file now.
2230   if (Symbol *sym = symtab->find(config->entry))
2231     handleUndefined(sym, "--entry");
2232 
2233   // Handle the `--undefined-glob <pattern>` options.
2234   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
2235     handleUndefinedGlob(pat);
2236 
2237   // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2238   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init)))
2239     sym->isUsedInRegularObj = true;
2240   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini)))
2241     sym->isUsedInRegularObj = true;
2242 
2243   // If any of our inputs are bitcode files, the LTO code generator may create
2244   // references to certain library functions that might not be explicit in the
2245   // bitcode file's symbol table. If any of those library functions are defined
2246   // in a bitcode file in an archive member, we need to arrange to use LTO to
2247   // compile those archive members by adding them to the link beforehand.
2248   //
2249   // However, adding all libcall symbols to the link can have undesired
2250   // consequences. For example, the libgcc implementation of
2251   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
2252   // that aborts the program if the Linux kernel does not support 64-bit
2253   // atomics, which would prevent the program from running even if it does not
2254   // use 64-bit atomics.
2255   //
2256   // Therefore, we only add libcall symbols to the link before LTO if we have
2257   // to, i.e. if the symbol's definition is in bitcode. Any other required
2258   // libcall symbols will be added to the link after LTO when we add the LTO
2259   // object file to the link.
2260   if (!bitcodeFiles.empty())
2261     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2262       handleLibcall(s);
2263 
2264   // Return if there were name resolution errors.
2265   if (errorCount())
2266     return;
2267 
2268   // We want to declare linker script's symbols early,
2269   // so that we can version them.
2270   // They also might be exported if referenced by DSOs.
2271   script->declareSymbols();
2272 
2273   // Handle --exclude-libs. This is before scanVersionScript() due to a
2274   // workaround for Android ndk: for a defined versioned symbol in an archive
2275   // without a version node in the version script, Android does not expect a
2276   // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2277   // GNU ld errors in this case.
2278   if (args.hasArg(OPT_exclude_libs))
2279     excludeLibs(args);
2280 
2281   // Create elfHeader early. We need a dummy section in
2282   // addReservedSymbols to mark the created symbols as not absolute.
2283   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
2284 
2285   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
2286 
2287   // We need to create some reserved symbols such as _end. Create them.
2288   if (!config->relocatable)
2289     addReservedSymbols();
2290 
2291   // Apply version scripts.
2292   //
2293   // For a relocatable output, version scripts don't make sense, and
2294   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
2295   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2296   if (!config->relocatable) {
2297     llvm::TimeTraceScope timeScope("Process symbol versions");
2298     symtab->scanVersionScript();
2299   }
2300 
2301   // Do link-time optimization if given files are LLVM bitcode files.
2302   // This compiles bitcode files into real object files.
2303   //
2304   // With this the symbol table should be complete. After this, no new names
2305   // except a few linker-synthesized ones will be added to the symbol table.
2306   compileBitcodeFiles<ELFT>();
2307 
2308   // Handle --exclude-libs again because lto.tmp may reference additional
2309   // libcalls symbols defined in an excluded archive. This may override
2310   // versionId set by scanVersionScript().
2311   if (args.hasArg(OPT_exclude_libs))
2312     excludeLibs(args);
2313 
2314   // Symbol resolution finished. Report backward reference problems.
2315   reportBackrefs();
2316   if (errorCount())
2317     return;
2318 
2319   // If --thinlto-index-only is given, we should create only "index
2320   // files" and not object files. Index file creation is already done
2321   // in compileBitcodeFiles, so we are done if that's the case.
2322   // Likewise, --plugin-opt=emit-llvm and --plugin-opt=emit-asm are the
2323   // options to create output files in bitcode or assembly code
2324   // respectively. No object files are generated.
2325   // Also bail out here when only certain thinLTO modules are specified for
2326   // compilation. The intermediate object file are the expected output.
2327   if (config->thinLTOIndexOnly || config->emitLLVM || config->ltoEmitAsm ||
2328       !config->thinLTOModulesToCompile.empty())
2329     return;
2330 
2331   // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
2332   redirectSymbols(wrapped);
2333 
2334   {
2335     llvm::TimeTraceScope timeScope("Aggregate sections");
2336     // Now that we have a complete list of input files.
2337     // Beyond this point, no new files are added.
2338     // Aggregate all input sections into one place.
2339     for (InputFile *f : objectFiles)
2340       for (InputSectionBase *s : f->getSections())
2341         if (s && s != &InputSection::discarded)
2342           inputSections.push_back(s);
2343     for (BinaryFile *f : binaryFiles)
2344       for (InputSectionBase *s : f->getSections())
2345         inputSections.push_back(cast<InputSection>(s));
2346   }
2347 
2348   {
2349     llvm::TimeTraceScope timeScope("Strip sections");
2350     llvm::erase_if(inputSections, [](InputSectionBase *s) {
2351       if (s->type == SHT_LLVM_SYMPART) {
2352         readSymbolPartitionSection<ELFT>(s);
2353         return true;
2354       }
2355 
2356       // We do not want to emit debug sections if --strip-all
2357       // or --strip-debug are given.
2358       if (config->strip == StripPolicy::None)
2359         return false;
2360 
2361       if (isDebugSection(*s))
2362         return true;
2363       if (auto *isec = dyn_cast<InputSection>(s))
2364         if (InputSectionBase *rel = isec->getRelocatedSection())
2365           if (isDebugSection(*rel))
2366             return true;
2367 
2368       return false;
2369     });
2370   }
2371 
2372   // Since we now have a complete set of input files, we can create
2373   // a .d file to record build dependencies.
2374   if (!config->dependencyFile.empty())
2375     writeDependencyFile();
2376 
2377   // Now that the number of partitions is fixed, save a pointer to the main
2378   // partition.
2379   mainPart = &partitions[0];
2380 
2381   // Read .note.gnu.property sections from input object files which
2382   // contain a hint to tweak linker's and loader's behaviors.
2383   config->andFeatures = getAndFeatures<ELFT>();
2384 
2385   // The Target instance handles target-specific stuff, such as applying
2386   // relocations or writing a PLT section. It also contains target-dependent
2387   // values such as a default image base address.
2388   target = getTarget();
2389 
2390   config->eflags = target->calcEFlags();
2391   // maxPageSize (sometimes called abi page size) is the maximum page size that
2392   // the output can be run on. For example if the OS can use 4k or 64k page
2393   // sizes then maxPageSize must be 64k for the output to be useable on both.
2394   // All important alignment decisions must use this value.
2395   config->maxPageSize = getMaxPageSize(args);
2396   // commonPageSize is the most common page size that the output will be run on.
2397   // For example if an OS can use 4k or 64k page sizes and 4k is more common
2398   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
2399   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
2400   // is limited to writing trap instructions on the last executable segment.
2401   config->commonPageSize = getCommonPageSize(args);
2402 
2403   config->imageBase = getImageBase(args);
2404 
2405   if (config->emachine == EM_ARM) {
2406     // FIXME: These warnings can be removed when lld only uses these features
2407     // when the input objects have been compiled with an architecture that
2408     // supports them.
2409     if (config->armHasBlx == false)
2410       warn("lld uses blx instruction, no object with architecture supporting "
2411            "feature detected");
2412   }
2413 
2414   // This adds a .comment section containing a version string.
2415   if (!config->relocatable)
2416     inputSections.push_back(createCommentSection());
2417 
2418   // Replace common symbols with regular symbols.
2419   replaceCommonSymbols();
2420 
2421   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
2422   splitSections<ELFT>();
2423 
2424   // Garbage collection and removal of shared symbols from unused shared objects.
2425   markLive<ELFT>();
2426   demoteSharedSymbols();
2427 
2428   // Make copies of any input sections that need to be copied into each
2429   // partition.
2430   copySectionsIntoPartitions();
2431 
2432   // Create synthesized sections such as .got and .plt. This is called before
2433   // processSectionCommands() so that they can be placed by SECTIONS commands.
2434   createSyntheticSections<ELFT>();
2435 
2436   // Some input sections that are used for exception handling need to be moved
2437   // into synthetic sections. Do that now so that they aren't assigned to
2438   // output sections in the usual way.
2439   if (!config->relocatable)
2440     combineEhSections();
2441 
2442   {
2443     llvm::TimeTraceScope timeScope("Assign sections");
2444 
2445     // Create output sections described by SECTIONS commands.
2446     script->processSectionCommands();
2447 
2448     // Linker scripts control how input sections are assigned to output
2449     // sections. Input sections that were not handled by scripts are called
2450     // "orphans", and they are assigned to output sections by the default rule.
2451     // Process that.
2452     script->addOrphanSections();
2453   }
2454 
2455   {
2456     llvm::TimeTraceScope timeScope("Merge/finalize input sections");
2457 
2458     // Migrate InputSectionDescription::sectionBases to sections. This includes
2459     // merging MergeInputSections into a single MergeSyntheticSection. From this
2460     // point onwards InputSectionDescription::sections should be used instead of
2461     // sectionBases.
2462     for (SectionCommand *cmd : script->sectionCommands)
2463       if (auto *sec = dyn_cast<OutputSection>(cmd))
2464         sec->finalizeInputSections();
2465     llvm::erase_if(inputSections, [](InputSectionBase *s) {
2466       return isa<MergeInputSection>(s);
2467     });
2468   }
2469 
2470   // Two input sections with different output sections should not be folded.
2471   // ICF runs after processSectionCommands() so that we know the output sections.
2472   if (config->icf != ICFLevel::None) {
2473     findKeepUniqueSections<ELFT>(args);
2474     doIcf<ELFT>();
2475   }
2476 
2477   // Read the callgraph now that we know what was gced or icfed
2478   if (config->callGraphProfileSort) {
2479     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
2480       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
2481         readCallGraph(*buffer);
2482     readCallGraphsFromObjectFiles<ELFT>();
2483   }
2484 
2485   // Write the result to the file.
2486   writeResult<ELFT>();
2487 }
2488