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