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