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