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