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