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