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