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