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