xref: /openbsd/gnu/llvm/lld/ELF/Driver.cpp (revision 771fbea0)
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->gcSections)
334       error("-r and --gc-sections may not be used together");
335     if (config->gdbIndex)
336       error("-r and --gdb-index may not be used together");
337     if (config->icf != ICFLevel::None)
338       error("-r and --icf may not be used together");
339     if (config->pie)
340       error("-r and -pie may not be used together");
341     if (config->exportDynamic)
342       error("-r and --export-dynamic may not be used together");
343   }
344 
345   if (config->executeOnly) {
346     if (config->emachine != EM_AARCH64)
347       error("-execute-only is only supported on AArch64 targets");
348 
349     if (config->singleRoRx && !script->hasSectionsCommand)
350       error("-execute-only and -no-rosegment cannot be used together");
351   }
352 
353   if (config->zRetpolineplt && config->zForceIbt)
354     error("-z force-ibt may not be used with -z retpolineplt");
355 
356   if (config->emachine != EM_AARCH64) {
357     if (config->zPacPlt)
358       error("-z pac-plt only supported on AArch64");
359     if (config->zForceBti)
360       error("-z force-bti only supported on AArch64");
361   }
362 }
363 
364 static const char *getReproduceOption(opt::InputArgList &args) {
365   if (auto *arg = args.getLastArg(OPT_reproduce))
366     return arg->getValue();
367   return getenv("LLD_REPRODUCE");
368 }
369 
370 static bool hasZOption(opt::InputArgList &args, StringRef key) {
371   for (auto *arg : args.filtered(OPT_z))
372     if (key == arg->getValue())
373       return true;
374   return false;
375 }
376 
377 static bool getZFlag(opt::InputArgList &args, StringRef k1, StringRef k2,
378                      bool Default) {
379   for (auto *arg : args.filtered_reverse(OPT_z)) {
380     if (k1 == arg->getValue())
381       return true;
382     if (k2 == arg->getValue())
383       return false;
384   }
385   return Default;
386 }
387 
388 static SeparateSegmentKind getZSeparate(opt::InputArgList &args) {
389   for (auto *arg : args.filtered_reverse(OPT_z)) {
390     StringRef v = arg->getValue();
391     if (v == "noseparate-code")
392       return SeparateSegmentKind::None;
393     if (v == "separate-code")
394       return SeparateSegmentKind::Code;
395     if (v == "separate-loadable-segments")
396       return SeparateSegmentKind::Loadable;
397   }
398   return SeparateSegmentKind::None;
399 }
400 
401 static GnuStackKind getZGnuStack(opt::InputArgList &args) {
402   for (auto *arg : args.filtered_reverse(OPT_z)) {
403     if (StringRef("execstack") == arg->getValue())
404       return GnuStackKind::Exec;
405     if (StringRef("noexecstack") == arg->getValue())
406       return GnuStackKind::NoExec;
407     if (StringRef("nognustack") == arg->getValue())
408       return GnuStackKind::None;
409   }
410 
411   return GnuStackKind::NoExec;
412 }
413 
414 static uint8_t getZStartStopVisibility(opt::InputArgList &args) {
415   for (auto *arg : args.filtered_reverse(OPT_z)) {
416     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
417     if (kv.first == "start-stop-visibility") {
418       if (kv.second == "default")
419         return STV_DEFAULT;
420       else if (kv.second == "internal")
421         return STV_INTERNAL;
422       else if (kv.second == "hidden")
423         return STV_HIDDEN;
424       else if (kv.second == "protected")
425         return STV_PROTECTED;
426       error("unknown -z start-stop-visibility= value: " + StringRef(kv.second));
427     }
428   }
429   return STV_PROTECTED;
430 }
431 
432 static bool isKnownZFlag(StringRef s) {
433   return s == "combreloc" || s == "copyreloc" || s == "defs" ||
434          s == "execstack" || s == "force-bti" || s == "force-ibt" ||
435          s == "global" || s == "hazardplt" || s == "ifunc-noplt" ||
436          s == "initfirst" || s == "interpose" ||
437          s == "keep-text-section-prefix" || s == "lazy" || s == "muldefs" ||
438          s == "separate-code" || s == "separate-loadable-segments" ||
439          s == "nocombreloc" || s == "nocopyreloc" || s == "nodefaultlib" ||
440          s == "nodelete" || s == "nodlopen" || s == "noexecstack" ||
441          s == "nognustack" || s == "nokeep-text-section-prefix" ||
442          s == "norelro" || s == "noretpolineplt" ||
443          s == "noseparate-code" || s == "notext" ||
444          s == "now" || s == "origin" || s == "pac-plt" || s == "rel" ||
445          s == "rela" || s == "relro" || s == "retpolineplt" ||
446          s == "rodynamic" || s == "shstk" || s == "text" || s == "undefs" ||
447          s == "wxneeded" || s.startswith("common-page-size=") ||
448          s.startswith("dead-reloc-in-nonalloc=") ||
449          s.startswith("max-page-size=") || s.startswith("stack-size=") ||
450          s.startswith("start-stop-visibility=");
451 }
452 
453 // Report an error for an unknown -z option.
454 static void checkZOptions(opt::InputArgList &args) {
455   for (auto *arg : args.filtered(OPT_z))
456     if (!isKnownZFlag(arg->getValue()))
457       error("unknown -z value: " + StringRef(arg->getValue()));
458 }
459 
460 void LinkerDriver::main(ArrayRef<const char *> argsArr) {
461   ELFOptTable parser;
462   opt::InputArgList args = parser.parse(argsArr.slice(1));
463 
464   // Interpret this flag early because error() depends on them.
465   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
466   checkZOptions(args);
467 
468   // Handle -help
469   if (args.hasArg(OPT_help)) {
470     printHelp();
471     return;
472   }
473 
474   // Handle -v or -version.
475   //
476   // A note about "compatible with GNU linkers" message: this is a hack for
477   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
478   // still the newest version in March 2017) or earlier to recognize LLD as
479   // a GNU compatible linker. As long as an output for the -v option
480   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
481   //
482   // This is somewhat ugly hack, but in reality, we had no choice other
483   // than doing this. Considering the very long release cycle of Libtool,
484   // it is not easy to improve it to recognize LLD as a GNU compatible
485   // linker in a timely manner. Even if we can make it, there are still a
486   // lot of "configure" scripts out there that are generated by old version
487   // of Libtool. We cannot convince every software developer to migrate to
488   // the latest version and re-generate scripts. So we have this hack.
489   if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
490     message(getLLDVersion() + " (compatible with GNU linkers)");
491 
492   if (const char *path = getReproduceOption(args)) {
493     // Note that --reproduce is a debug option so you can ignore it
494     // if you are trying to understand the whole picture of the code.
495     Expected<std::unique_ptr<TarWriter>> errOrWriter =
496         TarWriter::create(path, path::stem(path));
497     if (errOrWriter) {
498       tar = std::move(*errOrWriter);
499       tar->append("response.txt", createResponseFile(args));
500       tar->append("version.txt", getLLDVersion() + "\n");
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->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
922   config->disableVerify = args.hasArg(OPT_disable_verify);
923   config->discard = getDiscard(args);
924   config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
925   config->dynamicLinker = getDynamicLinker(args);
926   config->ehFrameHdr =
927       args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
928   config->emitLLVM = args.hasArg(OPT_plugin_opt_emit_llvm, false);
929   config->emitRelocs = args.hasArg(OPT_emit_relocs);
930   config->callGraphProfileSort = args.hasFlag(
931       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
932   config->enableNewDtags =
933       args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
934   config->entry = args.getLastArgValue(OPT_entry);
935   config->executeOnly =
936       args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
937   config->exportDynamic =
938       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
939   config->filterList = args::getStrings(args, OPT_filter);
940   config->fini = args.getLastArgValue(OPT_fini, "_fini");
941   config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
942                                      !args.hasArg(OPT_relocatable);
943   config->fixCortexA8 =
944       args.hasArg(OPT_fix_cortex_a8) && !args.hasArg(OPT_relocatable);
945   config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
946   config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
947   config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
948   config->icf = getICF(args);
949   config->ignoreDataAddressEquality =
950       args.hasArg(OPT_ignore_data_address_equality);
951   config->ignoreFunctionAddressEquality =
952       args.hasFlag(OPT_ignore_function_address_equality,
953       OPT_no_ignore_function_address_equality, true);
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_basicblock_sections);
970   config->ltoUniqueBasicBlockSectionNames =
971       args.hasFlag(OPT_lto_unique_bb_section_names,
972                    OPT_no_lto_unique_bb_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 #ifdef __OpenBSD__
992   config->pie = args.hasFlag(OPT_pie, OPT_no_pie,
993       !args.hasArg(OPT_shared) && !args.hasArg(OPT_relocatable));
994 #else
995   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
996 #endif
997   config->printIcfSections =
998       args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
999   config->printGcSections =
1000       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
1001   config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
1002   config->printSymbolOrder =
1003       args.getLastArgValue(OPT_print_symbol_order);
1004   config->rpath = getRpath(args);
1005   config->relocatable = args.hasArg(OPT_relocatable);
1006   config->saveTemps = args.hasArg(OPT_save_temps);
1007   if (args.hasArg(OPT_shuffle_sections))
1008     config->shuffleSectionSeed = args::getInteger(args, OPT_shuffle_sections, 0);
1009   config->searchPaths = args::getStrings(args, OPT_library_path);
1010   config->sectionStartMap = getSectionStartMap(args);
1011   config->shared = args.hasArg(OPT_shared);
1012   config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
1013   config->soName = args.getLastArgValue(OPT_soname);
1014   config->sortSection = getSortSection(args);
1015   config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
1016   config->strip = getStrip(args);
1017   config->sysroot = args.getLastArgValue(OPT_sysroot);
1018   config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
1019   config->target2 = getTarget2(args);
1020   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
1021   config->thinLTOCachePolicy = CHECK(
1022       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
1023       "--thinlto-cache-policy: invalid cache policy");
1024   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1025   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1026                              args.hasArg(OPT_thinlto_index_only_eq);
1027   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1028   config->thinLTOObjectSuffixReplace =
1029       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
1030   config->thinLTOPrefixReplace =
1031       getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
1032   config->thinLTOModulesToCompile =
1033       args::getStrings(args, OPT_thinlto_single_module_eq);
1034   config->timeTraceEnabled = args.hasArg(OPT_time_trace);
1035   config->timeTraceGranularity =
1036       args::getInteger(args, OPT_time_trace_granularity, 500);
1037   config->trace = args.hasArg(OPT_trace);
1038   config->undefined = args::getStrings(args, OPT_undefined);
1039   config->undefinedVersion =
1040       args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
1041   config->unique = args.hasArg(OPT_unique);
1042   config->useAndroidRelrTags = args.hasFlag(
1043       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
1044   config->unresolvedSymbols = getUnresolvedSymbolPolicy(args);
1045   config->warnBackrefs =
1046       args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
1047   config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
1048   config->warnIfuncTextrel =
1049       args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
1050   config->warnSymbolOrdering =
1051       args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1052   config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
1053   config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
1054   config->zForceBti = hasZOption(args, "force-bti");
1055   config->zForceIbt = hasZOption(args, "force-ibt");
1056   config->zGlobal = hasZOption(args, "global");
1057   config->zGnustack = getZGnuStack(args);
1058   config->zHazardplt = hasZOption(args, "hazardplt");
1059   config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
1060   config->zInitfirst = hasZOption(args, "initfirst");
1061   config->zInterpose = hasZOption(args, "interpose");
1062   config->zKeepTextSectionPrefix = getZFlag(
1063       args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
1064   config->zNodefaultlib = hasZOption(args, "nodefaultlib");
1065   config->zNodelete = hasZOption(args, "nodelete");
1066   config->zNodlopen = hasZOption(args, "nodlopen");
1067   config->zNow = getZFlag(args, "now", "lazy", false);
1068   config->zOrigin = hasZOption(args, "origin");
1069   config->zPacPlt = hasZOption(args, "pac-plt");
1070   config->zRelro = getZFlag(args, "relro", "norelro", true);
1071 #ifndef __OpenBSD__
1072   config->zRetpolineplt = getZFlag(args, "retpolineplt", "noretpolineplt", false);
1073 #else
1074   config->zRetpolineplt = getZFlag(args, "retpolineplt", "noretpolineplt", true);
1075 #endif
1076   config->zRodynamic = hasZOption(args, "rodynamic");
1077   config->zSeparate = getZSeparate(args);
1078   config->zShstk = hasZOption(args, "shstk");
1079   config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1080   config->zStartStopVisibility = getZStartStopVisibility(args);
1081   config->zText = getZFlag(args, "text", "notext", true);
1082   config->zWxneeded = hasZOption(args, "wxneeded");
1083 
1084   for (opt::Arg *arg : args.filtered(OPT_z)) {
1085     std::pair<StringRef, StringRef> option =
1086         StringRef(arg->getValue()).split('=');
1087     if (option.first != "dead-reloc-in-nonalloc")
1088       continue;
1089     constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
1090     std::pair<StringRef, StringRef> kv = option.second.split('=');
1091     if (kv.first.empty() || kv.second.empty()) {
1092       error(errPrefix + "expected <section_glob>=<value>");
1093       continue;
1094     }
1095     uint64_t v;
1096     if (!to_integer(kv.second, v))
1097       error(errPrefix + "expected a non-negative integer, but got '" +
1098             kv.second + "'");
1099     else if (Expected<GlobPattern> pat = GlobPattern::create(kv.first))
1100       config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
1101     else
1102       error(errPrefix + toString(pat.takeError()));
1103   }
1104 
1105   // Parse LTO options.
1106   if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
1107     parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
1108                      arg->getSpelling());
1109 
1110   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
1111     parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
1112 
1113   // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1114   // relative path. Just ignore. If not ended with "lto-wrapper", consider it an
1115   // unsupported LLVMgold.so option and error.
1116   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq))
1117     if (!StringRef(arg->getValue()).endswith("lto-wrapper"))
1118       error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
1119             "'");
1120 
1121   // Parse -mllvm options.
1122   for (auto *arg : args.filtered(OPT_mllvm))
1123     parseClangOption(arg->getValue(), arg->getSpelling());
1124 
1125   // --threads= takes a positive integer and provides the default value for
1126   // --thinlto-jobs=.
1127   if (auto *arg = args.getLastArg(OPT_threads)) {
1128     StringRef v(arg->getValue());
1129     unsigned threads = 0;
1130     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1131       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1132             arg->getValue() + "'");
1133     parallel::strategy = hardware_concurrency(threads);
1134     config->thinLTOJobs = v;
1135   }
1136   if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
1137     config->thinLTOJobs = arg->getValue();
1138 
1139   if (config->ltoo > 3)
1140     error("invalid optimization level for LTO: " + Twine(config->ltoo));
1141   if (config->ltoPartitions == 0)
1142     error("--lto-partitions: number of threads must be > 0");
1143   if (!get_threadpool_strategy(config->thinLTOJobs))
1144     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1145 
1146   if (config->splitStackAdjustSize < 0)
1147     error("--split-stack-adjust-size: size must be >= 0");
1148 
1149   // The text segment is traditionally the first segment, whose address equals
1150   // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1151   // is an old-fashioned option that does not play well with lld's layout.
1152   // Suggest --image-base as a likely alternative.
1153   if (args.hasArg(OPT_Ttext_segment))
1154     error("-Ttext-segment is not supported. Use --image-base if you "
1155           "intend to set the base address");
1156 
1157   // Parse ELF{32,64}{LE,BE} and CPU type.
1158   if (auto *arg = args.getLastArg(OPT_m)) {
1159     StringRef s = arg->getValue();
1160     std::tie(config->ekind, config->emachine, config->osabi) =
1161         parseEmulation(s);
1162     config->mipsN32Abi =
1163         (s.startswith("elf32btsmipn32") || s.startswith("elf32ltsmipn32"));
1164     config->emulation = s;
1165   }
1166 
1167   // Parse -hash-style={sysv,gnu,both}.
1168   if (auto *arg = args.getLastArg(OPT_hash_style)) {
1169     StringRef s = arg->getValue();
1170     if (s == "sysv")
1171       config->sysvHash = true;
1172     else if (s == "gnu")
1173       config->gnuHash = true;
1174     else if (s == "both")
1175       config->sysvHash = config->gnuHash = true;
1176     else
1177       error("unknown -hash-style: " + s);
1178   }
1179 
1180   if (args.hasArg(OPT_print_map))
1181     config->mapFile = "-";
1182 
1183   // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1184   // As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
1185   // it.
1186   if (config->nmagic || config->omagic)
1187     config->zRelro = false;
1188 
1189   std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1190 
1191   std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1192       getPackDynRelocs(args);
1193 
1194   if (auto *arg = args.getLastArg(OPT_symbol_ordering_file)){
1195     if (args.hasArg(OPT_call_graph_ordering_file))
1196       error("--symbol-ordering-file and --call-graph-order-file "
1197             "may not be used together");
1198     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue())){
1199       config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1200       // Also need to disable CallGraphProfileSort to prevent
1201       // LLD order symbols with CGProfile
1202       config->callGraphProfileSort = false;
1203     }
1204   }
1205 
1206   assert(config->versionDefinitions.empty());
1207   config->versionDefinitions.push_back({"local", (uint16_t)VER_NDX_LOCAL, {}});
1208   config->versionDefinitions.push_back(
1209       {"global", (uint16_t)VER_NDX_GLOBAL, {}});
1210 
1211   // If --retain-symbol-file is used, we'll keep only the symbols listed in
1212   // the file and discard all others.
1213   if (auto *arg = args.getLastArg(OPT_retain_symbols_file)) {
1214     config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(
1215         {"*", /*isExternCpp=*/false, /*hasWildcard=*/true});
1216     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1217       for (StringRef s : args::getLines(*buffer))
1218         config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back(
1219             {s, /*isExternCpp=*/false, /*hasWildcard=*/false});
1220   }
1221 
1222   for (opt::Arg *arg : args.filtered(OPT_warn_backrefs_exclude)) {
1223     StringRef pattern(arg->getValue());
1224     if (Expected<GlobPattern> pat = GlobPattern::create(pattern))
1225       config->warnBackrefsExclude.push_back(std::move(*pat));
1226     else
1227       error(arg->getSpelling() + ": " + toString(pat.takeError()));
1228   }
1229 
1230   // When producing an executable, --dynamic-list specifies non-local defined
1231   // symbols whith are required to be exported. When producing a shared object,
1232   // symbols not specified by --dynamic-list are non-preemptible.
1233   config->symbolic =
1234       args.hasArg(OPT_Bsymbolic) || args.hasArg(OPT_dynamic_list);
1235   for (auto *arg : args.filtered(OPT_dynamic_list))
1236     if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1237       readDynamicList(*buffer);
1238 
1239   // --export-dynamic-symbol specifies additional --dynamic-list symbols if any
1240   // other option expresses a symbolic intention: -no-pie, -pie, -Bsymbolic,
1241   // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1242   for (auto *arg : args.filtered(OPT_export_dynamic_symbol))
1243     config->dynamicList.push_back(
1244         {arg->getValue(), /*isExternCpp=*/false,
1245          /*hasWildcard=*/hasWildcard(arg->getValue())});
1246 
1247   for (auto *arg : args.filtered(OPT_version_script))
1248     if (Optional<std::string> path = searchScript(arg->getValue())) {
1249       if (Optional<MemoryBufferRef> buffer = readFile(*path))
1250         readVersionScript(*buffer);
1251     } else {
1252       error(Twine("cannot find version script ") + arg->getValue());
1253     }
1254 }
1255 
1256 // Some Config members do not directly correspond to any particular
1257 // command line options, but computed based on other Config values.
1258 // This function initialize such members. See Config.h for the details
1259 // of these values.
1260 static void setConfigs(opt::InputArgList &args) {
1261   ELFKind k = config->ekind;
1262   uint16_t m = config->emachine;
1263 
1264   config->copyRelocs = (config->relocatable || config->emitRelocs);
1265   config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1266   config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1267   config->endianness = config->isLE ? endianness::little : endianness::big;
1268   config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1269   config->isPic = config->pie || config->shared;
1270   config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1271   config->wordsize = config->is64 ? 8 : 4;
1272 
1273   // ELF defines two different ways to store relocation addends as shown below:
1274   //
1275   //  Rel: Addends are stored to the location where relocations are applied. It
1276   //  cannot pack the full range of addend values for all relocation types, but
1277   //  this only affects relocation types that we don't support emitting as
1278   //  dynamic relocations (see getDynRel).
1279   //  Rela: Addends are stored as part of relocation entry.
1280   //
1281   // In other words, Rela makes it easy to read addends at the price of extra
1282   // 4 or 8 byte for each relocation entry.
1283   //
1284   // We pick the format for dynamic relocations according to the psABI for each
1285   // processor, but a contrary choice can be made if the dynamic loader
1286   // supports.
1287   config->isRela = getIsRela(args);
1288 
1289   // If the output uses REL relocations we must store the dynamic relocation
1290   // addends to the output sections. We also store addends for RELA relocations
1291   // if --apply-dynamic-relocs is used.
1292   // We default to not writing the addends when using RELA relocations since
1293   // any standard conforming tool can find it in r_addend.
1294   config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1295                                       OPT_no_apply_dynamic_relocs, false) ||
1296                          !config->isRela;
1297 
1298   config->tocOptimize =
1299       args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, m == EM_PPC64);
1300 }
1301 
1302 // Returns a value of "-format" option.
1303 static bool isFormatBinary(StringRef s) {
1304   if (s == "binary")
1305     return true;
1306   if (s == "elf" || s == "default")
1307     return false;
1308   error("unknown -format value: " + s +
1309         " (supported formats: elf, default, binary)");
1310   return false;
1311 }
1312 
1313 void LinkerDriver::createFiles(opt::InputArgList &args) {
1314   // For --{push,pop}-state.
1315   std::vector<std::tuple<bool, bool, bool>> stack;
1316 
1317   // Iterate over argv to process input files and positional arguments.
1318   for (auto *arg : args) {
1319     switch (arg->getOption().getID()) {
1320     case OPT_library:
1321       addLibrary(arg->getValue());
1322       break;
1323     case OPT_INPUT:
1324       addFile(arg->getValue(), /*withLOption=*/false);
1325       break;
1326     case OPT_defsym: {
1327       StringRef from;
1328       StringRef to;
1329       std::tie(from, to) = StringRef(arg->getValue()).split('=');
1330       if (from.empty() || to.empty())
1331         error("-defsym: syntax error: " + StringRef(arg->getValue()));
1332       else
1333         readDefsym(from, MemoryBufferRef(to, "-defsym"));
1334       break;
1335     }
1336     case OPT_script:
1337       if (Optional<std::string> path = searchScript(arg->getValue())) {
1338         if (Optional<MemoryBufferRef> mb = readFile(*path))
1339           readLinkerScript(*mb);
1340         break;
1341       }
1342       error(Twine("cannot find linker script ") + arg->getValue());
1343       break;
1344     case OPT_as_needed:
1345       config->asNeeded = true;
1346       break;
1347     case OPT_format:
1348       config->formatBinary = isFormatBinary(arg->getValue());
1349       break;
1350     case OPT_no_as_needed:
1351       config->asNeeded = false;
1352       break;
1353     case OPT_Bstatic:
1354     case OPT_omagic:
1355     case OPT_nmagic:
1356       config->isStatic = true;
1357       break;
1358     case OPT_Bdynamic:
1359       config->isStatic = false;
1360       break;
1361     case OPT_whole_archive:
1362       inWholeArchive = true;
1363       break;
1364     case OPT_no_whole_archive:
1365       inWholeArchive = false;
1366       break;
1367     case OPT_just_symbols:
1368       if (Optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1369         files.push_back(createObjectFile(*mb));
1370         files.back()->justSymbols = true;
1371       }
1372       break;
1373     case OPT_start_group:
1374       if (InputFile::isInGroup)
1375         error("nested --start-group");
1376       InputFile::isInGroup = true;
1377       break;
1378     case OPT_end_group:
1379       if (!InputFile::isInGroup)
1380         error("stray --end-group");
1381       InputFile::isInGroup = false;
1382       ++InputFile::nextGroupId;
1383       break;
1384     case OPT_start_lib:
1385       if (inLib)
1386         error("nested --start-lib");
1387       if (InputFile::isInGroup)
1388         error("may not nest --start-lib in --start-group");
1389       inLib = true;
1390       InputFile::isInGroup = true;
1391       break;
1392     case OPT_end_lib:
1393       if (!inLib)
1394         error("stray --end-lib");
1395       inLib = false;
1396       InputFile::isInGroup = false;
1397       ++InputFile::nextGroupId;
1398       break;
1399     case OPT_push_state:
1400       stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
1401       break;
1402     case OPT_pop_state:
1403       if (stack.empty()) {
1404         error("unbalanced --push-state/--pop-state");
1405         break;
1406       }
1407       std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
1408       stack.pop_back();
1409       break;
1410     }
1411   }
1412 
1413   if (files.empty() && errorCount() == 0)
1414     error("no input files");
1415 }
1416 
1417 // If -m <machine_type> was not given, infer it from object files.
1418 void LinkerDriver::inferMachineType() {
1419   if (config->ekind != ELFNoneKind)
1420     return;
1421 
1422   for (InputFile *f : files) {
1423     if (f->ekind == ELFNoneKind)
1424       continue;
1425     config->ekind = f->ekind;
1426     config->emachine = f->emachine;
1427     config->osabi = f->osabi;
1428     config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
1429     return;
1430   }
1431   error("target emulation unknown: -m or at least one .o file required");
1432 }
1433 
1434 // Parse -z max-page-size=<value>. The default value is defined by
1435 // each target. Is set to 1 if given nmagic or omagic.
1436 static uint64_t getMaxPageSize(opt::InputArgList &args) {
1437   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1438                                        target->defaultMaxPageSize);
1439   if (!isPowerOf2_64(val))
1440     error("max-page-size: value isn't a power of 2");
1441   if (config->nmagic || config->omagic) {
1442     if (val != target->defaultMaxPageSize)
1443       warn("-z max-page-size set, but paging disabled by omagic or nmagic");
1444     return 1;
1445   }
1446   return val;
1447 }
1448 
1449 // Parse -z common-page-size=<value>. The default value is defined by
1450 // each target. Is set to 1 if given nmagic or omagic.
1451 static uint64_t getCommonPageSize(opt::InputArgList &args) {
1452   uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
1453                                        target->defaultCommonPageSize);
1454   if (!isPowerOf2_64(val))
1455     error("common-page-size: value isn't a power of 2");
1456   if (config->nmagic || config->omagic) {
1457     if (val != target->defaultCommonPageSize)
1458       warn("-z common-page-size set, but paging disabled by omagic or nmagic");
1459     return 1;
1460   }
1461   // commonPageSize can't be larger than maxPageSize.
1462   if (val > config->maxPageSize)
1463     val = config->maxPageSize;
1464   return val;
1465 }
1466 
1467 // Parse -z max-page-size=<value>. The default value is defined by
1468 // each target.
1469 static uint64_t getRealMaxPageSize(opt::InputArgList &args) {
1470   uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
1471                                        target->defaultMaxPageSize);
1472   if (!isPowerOf2_64(val))
1473     error("max-page-size: value isn't a power of 2");
1474   return val;
1475 }
1476 
1477 // Parses -image-base option.
1478 static Optional<uint64_t> getImageBase(opt::InputArgList &args) {
1479   // Because we are using "Config->maxPageSize" here, this function has to be
1480   // called after the variable is initialized.
1481   auto *arg = args.getLastArg(OPT_image_base);
1482   if (!arg)
1483     return None;
1484 
1485   StringRef s = arg->getValue();
1486   uint64_t v;
1487   if (!to_integer(s, v)) {
1488     error("-image-base: number expected, but got " + s);
1489     return 0;
1490   }
1491   if ((v % config->maxPageSize) != 0)
1492     warn("-image-base: address isn't multiple of page size: " + s);
1493   return v;
1494 }
1495 
1496 // Parses `--exclude-libs=lib,lib,...`.
1497 // The library names may be delimited by commas or colons.
1498 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &args) {
1499   DenseSet<StringRef> ret;
1500   for (auto *arg : args.filtered(OPT_exclude_libs)) {
1501     StringRef s = arg->getValue();
1502     for (;;) {
1503       size_t pos = s.find_first_of(",:");
1504       if (pos == StringRef::npos)
1505         break;
1506       ret.insert(s.substr(0, pos));
1507       s = s.substr(pos + 1);
1508     }
1509     ret.insert(s);
1510   }
1511   return ret;
1512 }
1513 
1514 // Handles the -exclude-libs option. If a static library file is specified
1515 // by the -exclude-libs option, all public symbols from the archive become
1516 // private unless otherwise specified by version scripts or something.
1517 // A special library name "ALL" means all archive files.
1518 //
1519 // This is not a popular option, but some programs such as bionic libc use it.
1520 static void excludeLibs(opt::InputArgList &args) {
1521   DenseSet<StringRef> libs = getExcludeLibs(args);
1522   bool all = libs.count("ALL");
1523 
1524   auto visit = [&](InputFile *file) {
1525     if (!file->archiveName.empty())
1526       if (all || libs.count(path::filename(file->archiveName)))
1527         for (Symbol *sym : file->getSymbols())
1528           if (!sym->isUndefined() && !sym->isLocal() && sym->file == file)
1529             sym->versionId = VER_NDX_LOCAL;
1530   };
1531 
1532   for (InputFile *file : objectFiles)
1533     visit(file);
1534 
1535   for (BitcodeFile *file : bitcodeFiles)
1536     visit(file);
1537 }
1538 
1539 // Force Sym to be entered in the output.
1540 static void handleUndefined(Symbol *sym) {
1541   // Since a symbol may not be used inside the program, LTO may
1542   // eliminate it. Mark the symbol as "used" to prevent it.
1543   sym->isUsedInRegularObj = true;
1544 
1545   if (sym->isLazy())
1546     sym->fetch();
1547 }
1548 
1549 // As an extension to GNU linkers, lld supports a variant of `-u`
1550 // which accepts wildcard patterns. All symbols that match a given
1551 // pattern are handled as if they were given by `-u`.
1552 static void handleUndefinedGlob(StringRef arg) {
1553   Expected<GlobPattern> pat = GlobPattern::create(arg);
1554   if (!pat) {
1555     error("--undefined-glob: " + toString(pat.takeError()));
1556     return;
1557   }
1558 
1559   std::vector<Symbol *> syms;
1560   for (Symbol *sym : symtab->symbols()) {
1561     // Calling Sym->fetch() from here is not safe because it may
1562     // add new symbols to the symbol table, invalidating the
1563     // current iterator. So we just keep a note.
1564     if (pat->match(sym->getName()))
1565       syms.push_back(sym);
1566   }
1567 
1568   for (Symbol *sym : syms)
1569     handleUndefined(sym);
1570 }
1571 
1572 static void handleLibcall(StringRef name) {
1573   Symbol *sym = symtab->find(name);
1574   if (!sym || !sym->isLazy())
1575     return;
1576 
1577   MemoryBufferRef mb;
1578   if (auto *lo = dyn_cast<LazyObject>(sym))
1579     mb = lo->file->mb;
1580   else
1581     mb = cast<LazyArchive>(sym)->getMemberBuffer();
1582 
1583   if (isBitcode(mb))
1584     sym->fetch();
1585 }
1586 
1587 // Replaces common symbols with defined symbols reside in .bss sections.
1588 // This function is called after all symbol names are resolved. As a
1589 // result, the passes after the symbol resolution won't see any
1590 // symbols of type CommonSymbol.
1591 static void replaceCommonSymbols() {
1592   for (Symbol *sym : symtab->symbols()) {
1593     auto *s = dyn_cast<CommonSymbol>(sym);
1594     if (!s)
1595       continue;
1596 
1597     auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
1598     bss->file = s->file;
1599     bss->markDead();
1600     inputSections.push_back(bss);
1601     s->replace(Defined{s->file, s->getName(), s->binding, s->stOther, s->type,
1602                        /*value=*/0, s->size, bss});
1603   }
1604 }
1605 
1606 // If all references to a DSO happen to be weak, the DSO is not added
1607 // to DT_NEEDED. If that happens, we need to eliminate shared symbols
1608 // created from the DSO. Otherwise, they become dangling references
1609 // that point to a non-existent DSO.
1610 static void demoteSharedSymbols() {
1611   for (Symbol *sym : symtab->symbols()) {
1612     auto *s = dyn_cast<SharedSymbol>(sym);
1613     if (!s || s->getFile().isNeeded)
1614       continue;
1615 
1616     bool used = s->used;
1617     s->replace(Undefined{nullptr, s->getName(), STB_WEAK, s->stOther, s->type});
1618     s->used = used;
1619   }
1620 }
1621 
1622 // The section referred to by `s` is considered address-significant. Set the
1623 // keepUnique flag on the section if appropriate.
1624 static void markAddrsig(Symbol *s) {
1625   if (auto *d = dyn_cast_or_null<Defined>(s))
1626     if (d->section)
1627       // We don't need to keep text sections unique under --icf=all even if they
1628       // are address-significant.
1629       if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
1630         d->section->keepUnique = true;
1631 }
1632 
1633 // Record sections that define symbols mentioned in --keep-unique <symbol>
1634 // and symbols referred to by address-significance tables. These sections are
1635 // ineligible for ICF.
1636 template <class ELFT>
1637 static void findKeepUniqueSections(opt::InputArgList &args) {
1638   for (auto *arg : args.filtered(OPT_keep_unique)) {
1639     StringRef name = arg->getValue();
1640     auto *d = dyn_cast_or_null<Defined>(symtab->find(name));
1641     if (!d || !d->section) {
1642       warn("could not find symbol " + name + " to keep unique");
1643       continue;
1644     }
1645     d->section->keepUnique = true;
1646   }
1647 
1648   // --icf=all --ignore-data-address-equality means that we can ignore
1649   // the dynsym and address-significance tables entirely.
1650   if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
1651     return;
1652 
1653   // Symbols in the dynsym could be address-significant in other executables
1654   // or DSOs, so we conservatively mark them as address-significant.
1655   for (Symbol *sym : symtab->symbols())
1656     if (sym->includeInDynsym())
1657       markAddrsig(sym);
1658 
1659   // Visit the address-significance table in each object file and mark each
1660   // referenced symbol as address-significant.
1661   for (InputFile *f : objectFiles) {
1662     auto *obj = cast<ObjFile<ELFT>>(f);
1663     ArrayRef<Symbol *> syms = obj->getSymbols();
1664     if (obj->addrsigSec) {
1665       ArrayRef<uint8_t> contents =
1666           check(obj->getObj().getSectionContents(obj->addrsigSec));
1667       const uint8_t *cur = contents.begin();
1668       while (cur != contents.end()) {
1669         unsigned size;
1670         const char *err;
1671         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1672         if (err)
1673           fatal(toString(f) + ": could not decode addrsig section: " + err);
1674         markAddrsig(syms[symIndex]);
1675         cur += size;
1676       }
1677     } else {
1678       // If an object file does not have an address-significance table,
1679       // conservatively mark all of its symbols as address-significant.
1680       for (Symbol *s : syms)
1681         markAddrsig(s);
1682     }
1683   }
1684 }
1685 
1686 // This function reads a symbol partition specification section. These sections
1687 // are used to control which partition a symbol is allocated to. See
1688 // https://lld.llvm.org/Partitions.html for more details on partitions.
1689 template <typename ELFT>
1690 static void readSymbolPartitionSection(InputSectionBase *s) {
1691   // Read the relocation that refers to the partition's entry point symbol.
1692   Symbol *sym;
1693   if (s->areRelocsRela)
1694     sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template relas<ELFT>()[0]);
1695   else
1696     sym = &s->getFile<ELFT>()->getRelocTargetSym(s->template rels<ELFT>()[0]);
1697   if (!isa<Defined>(sym) || !sym->includeInDynsym())
1698     return;
1699 
1700   StringRef partName = reinterpret_cast<const char *>(s->data().data());
1701   for (Partition &part : partitions) {
1702     if (part.name == partName) {
1703       sym->partition = part.getNumber();
1704       return;
1705     }
1706   }
1707 
1708   // Forbid partitions from being used on incompatible targets, and forbid them
1709   // from being used together with various linker features that assume a single
1710   // set of output sections.
1711   if (script->hasSectionsCommand)
1712     error(toString(s->file) +
1713           ": partitions cannot be used with the SECTIONS command");
1714   if (script->hasPhdrsCommands())
1715     error(toString(s->file) +
1716           ": partitions cannot be used with the PHDRS command");
1717   if (!config->sectionStartMap.empty())
1718     error(toString(s->file) + ": partitions cannot be used with "
1719                               "--section-start, -Ttext, -Tdata or -Tbss");
1720   if (config->emachine == EM_MIPS)
1721     error(toString(s->file) + ": partitions cannot be used on this target");
1722 
1723   // Impose a limit of no more than 254 partitions. This limit comes from the
1724   // sizes of the Partition fields in InputSectionBase and Symbol, as well as
1725   // the amount of space devoted to the partition number in RankFlags.
1726   if (partitions.size() == 254)
1727     fatal("may not have more than 254 partitions");
1728 
1729   partitions.emplace_back();
1730   Partition &newPart = partitions.back();
1731   newPart.name = partName;
1732   sym->partition = newPart.getNumber();
1733 }
1734 
1735 static Symbol *addUndefined(StringRef name) {
1736   return symtab->addSymbol(
1737       Undefined{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0});
1738 }
1739 
1740 static Symbol *addUnusedUndefined(StringRef name) {
1741   Undefined sym{nullptr, name, STB_GLOBAL, STV_DEFAULT, 0};
1742   sym.isUsedInRegularObj = false;
1743   return symtab->addSymbol(sym);
1744 }
1745 
1746 // This function is where all the optimizations of link-time
1747 // optimization takes place. When LTO is in use, some input files are
1748 // not in native object file format but in the LLVM bitcode format.
1749 // This function compiles bitcode files into a few big native files
1750 // using LLVM functions and replaces bitcode symbols with the results.
1751 // Because all bitcode files that the program consists of are passed to
1752 // the compiler at once, it can do a whole-program optimization.
1753 template <class ELFT> void LinkerDriver::compileBitcodeFiles() {
1754   llvm::TimeTraceScope timeScope("LTO");
1755   // Compile bitcode files and replace bitcode symbols.
1756   lto.reset(new BitcodeCompiler);
1757   for (BitcodeFile *file : bitcodeFiles)
1758     lto->add(*file);
1759 
1760   for (InputFile *file : lto->compile()) {
1761     auto *obj = cast<ObjFile<ELFT>>(file);
1762     obj->parse(/*ignoreComdats=*/true);
1763 
1764     // Parse '@' in symbol names for non-relocatable output.
1765     if (!config->relocatable)
1766       for (Symbol *sym : obj->getGlobalSymbols())
1767         sym->parseSymbolVersion();
1768     objectFiles.push_back(file);
1769   }
1770 }
1771 
1772 // The --wrap option is a feature to rename symbols so that you can write
1773 // wrappers for existing functions. If you pass `-wrap=foo`, all
1774 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1775 // expected to write `wrap_foo` function as a wrapper). The original
1776 // symbol becomes accessible as `real_foo`, so you can call that from your
1777 // wrapper.
1778 //
1779 // This data structure is instantiated for each -wrap option.
1780 struct WrappedSymbol {
1781   Symbol *sym;
1782   Symbol *real;
1783   Symbol *wrap;
1784 };
1785 
1786 // Handles -wrap option.
1787 //
1788 // This function instantiates wrapper symbols. At this point, they seem
1789 // like they are not being used at all, so we explicitly set some flags so
1790 // that LTO won't eliminate them.
1791 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
1792   std::vector<WrappedSymbol> v;
1793   DenseSet<StringRef> seen;
1794 
1795   for (auto *arg : args.filtered(OPT_wrap)) {
1796     StringRef name = arg->getValue();
1797     if (!seen.insert(name).second)
1798       continue;
1799 
1800     Symbol *sym = symtab->find(name);
1801     if (!sym)
1802       continue;
1803 
1804     Symbol *real = addUndefined(saver.save("__real_" + name));
1805     Symbol *wrap = addUndefined(saver.save("__wrap_" + name));
1806     v.push_back({sym, real, wrap});
1807 
1808     // We want to tell LTO not to inline symbols to be overwritten
1809     // because LTO doesn't know the final symbol contents after renaming.
1810     real->canInline = false;
1811     sym->canInline = false;
1812 
1813     // Tell LTO not to eliminate these symbols.
1814     sym->isUsedInRegularObj = true;
1815     wrap->isUsedInRegularObj = true;
1816   }
1817   return v;
1818 }
1819 
1820 // Do renaming for -wrap by updating pointers to symbols.
1821 //
1822 // When this function is executed, only InputFiles and symbol table
1823 // contain pointers to symbol objects. We visit them to replace pointers,
1824 // so that wrapped symbols are swapped as instructed by the command line.
1825 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
1826   DenseMap<Symbol *, Symbol *> map;
1827   for (const WrappedSymbol &w : wrapped) {
1828     map[w.sym] = w.wrap;
1829     map[w.real] = w.sym;
1830   }
1831 
1832   // Update pointers in input files.
1833   parallelForEach(objectFiles, [&](InputFile *file) {
1834     MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
1835     for (size_t i = 0, e = syms.size(); i != e; ++i)
1836       if (Symbol *s = map.lookup(syms[i]))
1837         syms[i] = s;
1838   });
1839 
1840   // Update pointers in the symbol table.
1841   for (const WrappedSymbol &w : wrapped)
1842     symtab->wrap(w.sym, w.real, w.wrap);
1843 }
1844 
1845 // To enable CET (x86's hardware-assited control flow enforcement), each
1846 // source file must be compiled with -fcf-protection. Object files compiled
1847 // with the flag contain feature flags indicating that they are compatible
1848 // with CET. We enable the feature only when all object files are compatible
1849 // with CET.
1850 //
1851 // This is also the case with AARCH64's BTI and PAC which use the similar
1852 // GNU_PROPERTY_AARCH64_FEATURE_1_AND mechanism.
1853 template <class ELFT> static uint32_t getAndFeatures() {
1854   if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
1855       config->emachine != EM_AARCH64)
1856     return 0;
1857 
1858   uint32_t ret = -1;
1859   for (InputFile *f : objectFiles) {
1860     uint32_t features = cast<ObjFile<ELFT>>(f)->andFeatures;
1861     if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
1862       warn(toString(f) + ": -z force-bti: file does not have "
1863                          "GNU_PROPERTY_AARCH64_FEATURE_1_BTI property");
1864       features |= GNU_PROPERTY_AARCH64_FEATURE_1_BTI;
1865     } else if (config->zForceIbt &&
1866                !(features & GNU_PROPERTY_X86_FEATURE_1_IBT)) {
1867       warn(toString(f) + ": -z force-ibt: file does not have "
1868                          "GNU_PROPERTY_X86_FEATURE_1_IBT property");
1869       features |= GNU_PROPERTY_X86_FEATURE_1_IBT;
1870     }
1871     if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
1872       warn(toString(f) + ": -z pac-plt: file does not have "
1873                          "GNU_PROPERTY_AARCH64_FEATURE_1_PAC property");
1874       features |= GNU_PROPERTY_AARCH64_FEATURE_1_PAC;
1875     }
1876     ret &= features;
1877   }
1878 
1879   // Force enable Shadow Stack.
1880   if (config->zShstk)
1881     ret |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
1882 
1883   return ret;
1884 }
1885 
1886 // Do actual linking. Note that when this function is called,
1887 // all linker scripts have already been parsed.
1888 template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
1889   llvm::TimeTraceScope timeScope("Link", StringRef("LinkerDriver::Link"));
1890   // If a -hash-style option was not given, set to a default value,
1891   // which varies depending on the target.
1892   if (!args.hasArg(OPT_hash_style)) {
1893     if (config->emachine == EM_MIPS)
1894       config->sysvHash = true;
1895     else
1896       config->sysvHash = config->gnuHash = true;
1897   }
1898 
1899   // Default output filename is "a.out" by the Unix tradition.
1900   if (config->outputFile.empty())
1901     config->outputFile = "a.out";
1902 
1903   // Fail early if the output file or map file is not writable. If a user has a
1904   // long link, e.g. due to a large LTO link, they do not wish to run it and
1905   // find that it failed because there was a mistake in their command-line.
1906   if (auto e = tryCreateFile(config->outputFile))
1907     error("cannot open output file " + config->outputFile + ": " + e.message());
1908   if (auto e = tryCreateFile(config->mapFile))
1909     error("cannot open map file " + config->mapFile + ": " + e.message());
1910   if (errorCount())
1911     return;
1912 
1913   // Use default entry point name if no name was given via the command
1914   // line nor linker scripts. For some reason, MIPS entry point name is
1915   // different from others.
1916   config->warnMissingEntry =
1917       (!config->entry.empty() || (!config->shared && !config->relocatable));
1918   if (config->entry.empty() && !config->relocatable)
1919     config->entry = (config->emachine == EM_MIPS) ? "__start" : "_start";
1920 
1921   // Handle --trace-symbol.
1922   for (auto *arg : args.filtered(OPT_trace_symbol))
1923     symtab->insert(arg->getValue())->traced = true;
1924 
1925   // Handle -u/--undefined before input files. If both a.a and b.so define foo,
1926   // -u foo a.a b.so will fetch a.a.
1927   for (StringRef name : config->undefined)
1928     addUnusedUndefined(name);
1929 
1930   // Add all files to the symbol table. This will add almost all
1931   // symbols that we need to the symbol table. This process might
1932   // add files to the link, via autolinking, these files are always
1933   // appended to the Files vector.
1934   {
1935     llvm::TimeTraceScope timeScope("Parse input files");
1936     for (size_t i = 0; i < files.size(); ++i)
1937       parseFile(files[i]);
1938   }
1939 
1940   // Now that we have every file, we can decide if we will need a
1941   // dynamic symbol table.
1942   // We need one if we were asked to export dynamic symbols or if we are
1943   // producing a shared library.
1944   // We also need one if any shared libraries are used and for pie executables
1945   // (probably because the dynamic linker needs it).
1946   config->hasDynSymTab =
1947       !sharedFiles.empty() || config->isPic || config->exportDynamic;
1948 
1949   // Some symbols (such as __ehdr_start) are defined lazily only when there
1950   // are undefined symbols for them, so we add these to trigger that logic.
1951   for (StringRef name : script->referencedSymbols)
1952     addUndefined(name);
1953 
1954   // Prevent LTO from removing any definition referenced by -u.
1955   for (StringRef name : config->undefined)
1956     if (Defined *sym = dyn_cast_or_null<Defined>(symtab->find(name)))
1957       sym->isUsedInRegularObj = true;
1958 
1959   // If an entry symbol is in a static archive, pull out that file now.
1960   if (Symbol *sym = symtab->find(config->entry))
1961     handleUndefined(sym);
1962 
1963   // Handle the `--undefined-glob <pattern>` options.
1964   for (StringRef pat : args::getStrings(args, OPT_undefined_glob))
1965     handleUndefinedGlob(pat);
1966 
1967   // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
1968   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->init)))
1969     sym->isUsedInRegularObj = true;
1970   if (Symbol *sym = dyn_cast_or_null<Defined>(symtab->find(config->fini)))
1971     sym->isUsedInRegularObj = true;
1972 
1973   // If any of our inputs are bitcode files, the LTO code generator may create
1974   // references to certain library functions that might not be explicit in the
1975   // bitcode file's symbol table. If any of those library functions are defined
1976   // in a bitcode file in an archive member, we need to arrange to use LTO to
1977   // compile those archive members by adding them to the link beforehand.
1978   //
1979   // However, adding all libcall symbols to the link can have undesired
1980   // consequences. For example, the libgcc implementation of
1981   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1982   // that aborts the program if the Linux kernel does not support 64-bit
1983   // atomics, which would prevent the program from running even if it does not
1984   // use 64-bit atomics.
1985   //
1986   // Therefore, we only add libcall symbols to the link before LTO if we have
1987   // to, i.e. if the symbol's definition is in bitcode. Any other required
1988   // libcall symbols will be added to the link after LTO when we add the LTO
1989   // object file to the link.
1990   if (!bitcodeFiles.empty())
1991     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
1992       handleLibcall(s);
1993 
1994   // Return if there were name resolution errors.
1995   if (errorCount())
1996     return;
1997 
1998   // We want to declare linker script's symbols early,
1999   // so that we can version them.
2000   // They also might be exported if referenced by DSOs.
2001   script->declareSymbols();
2002 
2003   // Handle the -exclude-libs option.
2004   if (args.hasArg(OPT_exclude_libs))
2005     excludeLibs(args);
2006 
2007   // Create elfHeader early. We need a dummy section in
2008   // addReservedSymbols to mark the created symbols as not absolute.
2009   Out::elfHeader = make<OutputSection>("", 0, SHF_ALLOC);
2010   Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
2011 
2012   // Create wrapped symbols for -wrap option.
2013   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
2014 
2015   // We need to create some reserved symbols such as _end. Create them.
2016   if (!config->relocatable)
2017     addReservedSymbols();
2018 
2019   // Apply version scripts.
2020   //
2021   // For a relocatable output, version scripts don't make sense, and
2022   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
2023   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2024   if (!config->relocatable)
2025     symtab->scanVersionScript();
2026 
2027   // Do link-time optimization if given files are LLVM bitcode files.
2028   // This compiles bitcode files into real object files.
2029   //
2030   // With this the symbol table should be complete. After this, no new names
2031   // except a few linker-synthesized ones will be added to the symbol table.
2032   compileBitcodeFiles<ELFT>();
2033 
2034   // Symbol resolution finished. Report backward reference problems.
2035   reportBackrefs();
2036   if (errorCount())
2037     return;
2038 
2039   // If -thinlto-index-only is given, we should create only "index
2040   // files" and not object files. Index file creation is already done
2041   // in addCombinedLTOObject, so we are done if that's the case.
2042   // Likewise, --plugin-opt=emit-llvm and --plugin-opt=emit-asm are the
2043   // options to create output files in bitcode or assembly code
2044   // repsectively. No object files are generated.
2045   // Also bail out here when only certain thinLTO modules are specified for
2046   // compilation. The intermediate object file are the expected output.
2047   if (config->thinLTOIndexOnly || config->emitLLVM || config->ltoEmitAsm ||
2048       !config->thinLTOModulesToCompile.empty())
2049     return;
2050 
2051   // Apply symbol renames for -wrap.
2052   if (!wrapped.empty())
2053     wrapSymbols(wrapped);
2054 
2055   // Now that we have a complete list of input files.
2056   // Beyond this point, no new files are added.
2057   // Aggregate all input sections into one place.
2058   for (InputFile *f : objectFiles)
2059     for (InputSectionBase *s : f->getSections())
2060       if (s && s != &InputSection::discarded)
2061         inputSections.push_back(s);
2062   for (BinaryFile *f : binaryFiles)
2063     for (InputSectionBase *s : f->getSections())
2064       inputSections.push_back(cast<InputSection>(s));
2065 
2066   llvm::erase_if(inputSections, [](InputSectionBase *s) {
2067     if (s->type == SHT_LLVM_SYMPART) {
2068       readSymbolPartitionSection<ELFT>(s);
2069       return true;
2070     }
2071 
2072     // We do not want to emit debug sections if --strip-all
2073     // or -strip-debug are given.
2074     if (config->strip == StripPolicy::None)
2075       return false;
2076 
2077     if (isDebugSection(*s))
2078       return true;
2079     if (auto *isec = dyn_cast<InputSection>(s))
2080       if (InputSectionBase *rel = isec->getRelocatedSection())
2081         if (isDebugSection(*rel))
2082           return true;
2083 
2084     return false;
2085   });
2086 
2087   // Now that the number of partitions is fixed, save a pointer to the main
2088   // partition.
2089   mainPart = &partitions[0];
2090 
2091   // Read .note.gnu.property sections from input object files which
2092   // contain a hint to tweak linker's and loader's behaviors.
2093   config->andFeatures = getAndFeatures<ELFT>();
2094 
2095   // The Target instance handles target-specific stuff, such as applying
2096   // relocations or writing a PLT section. It also contains target-dependent
2097   // values such as a default image base address.
2098   target = getTarget();
2099 
2100   config->eflags = target->calcEFlags();
2101   // maxPageSize (sometimes called abi page size) is the maximum page size that
2102   // the output can be run on. For example if the OS can use 4k or 64k page
2103   // sizes then maxPageSize must be 64k for the output to be useable on both.
2104   // All important alignment decisions must use this value.
2105   config->maxPageSize = getMaxPageSize(args);
2106   // commonPageSize is the most common page size that the output will be run on.
2107   // For example if an OS can use 4k or 64k page sizes and 4k is more common
2108   // than 64k then commonPageSize is set to 4k. commonPageSize can be used for
2109   // optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
2110   // is limited to writing trap instructions on the last executable segment.
2111   config->commonPageSize = getCommonPageSize(args);
2112   // textAlignPageSize is the alignment page size to use when aligning PT_LOAD
2113   // sections. This is the same as maxPageSize except under -omagic, where data
2114   // sections are non-aligned (maxPageSize set to 1) but text sections are aligned
2115   // to the target page size.
2116   config->textAlignPageSize = config->omagic ? getRealMaxPageSize(args) : config->maxPageSize;
2117 
2118   config->imageBase = getImageBase(args);
2119 
2120   if (config->emachine == EM_ARM) {
2121     // FIXME: These warnings can be removed when lld only uses these features
2122     // when the input objects have been compiled with an architecture that
2123     // supports them.
2124     if (config->armHasBlx == false)
2125       warn("lld uses blx instruction, no object with architecture supporting "
2126            "feature detected");
2127   }
2128 
2129   // This adds a .comment section containing a version string.
2130   if (!config->relocatable)
2131     inputSections.push_back(createCommentSection());
2132 
2133   // Replace common symbols with regular symbols.
2134   replaceCommonSymbols();
2135 
2136   // Split SHF_MERGE and .eh_frame sections into pieces in preparation for garbage collection.
2137   splitSections<ELFT>();
2138 
2139   // Garbage collection and removal of shared symbols from unused shared objects.
2140   markLive<ELFT>();
2141   demoteSharedSymbols();
2142 
2143   // Make copies of any input sections that need to be copied into each
2144   // partition.
2145   copySectionsIntoPartitions();
2146 
2147   // Create synthesized sections such as .got and .plt. This is called before
2148   // processSectionCommands() so that they can be placed by SECTIONS commands.
2149   createSyntheticSections<ELFT>();
2150 
2151   // Some input sections that are used for exception handling need to be moved
2152   // into synthetic sections. Do that now so that they aren't assigned to
2153   // output sections in the usual way.
2154   if (!config->relocatable)
2155     combineEhSections();
2156 
2157   // Create output sections described by SECTIONS commands.
2158   script->processSectionCommands();
2159 
2160   // Linker scripts control how input sections are assigned to output sections.
2161   // Input sections that were not handled by scripts are called "orphans", and
2162   // they are assigned to output sections by the default rule. Process that.
2163   script->addOrphanSections();
2164 
2165   // Migrate InputSectionDescription::sectionBases to sections. This includes
2166   // merging MergeInputSections into a single MergeSyntheticSection. From this
2167   // point onwards InputSectionDescription::sections should be used instead of
2168   // sectionBases.
2169   for (BaseCommand *base : script->sectionCommands)
2170     if (auto *sec = dyn_cast<OutputSection>(base))
2171       sec->finalizeInputSections();
2172   llvm::erase_if(inputSections,
2173                  [](InputSectionBase *s) { return isa<MergeInputSection>(s); });
2174 
2175   // Two input sections with different output sections should not be folded.
2176   // ICF runs after processSectionCommands() so that we know the output sections.
2177   if (config->icf != ICFLevel::None) {
2178     findKeepUniqueSections<ELFT>(args);
2179     doIcf<ELFT>();
2180   }
2181 
2182   // Read the callgraph now that we know what was gced or icfed
2183   if (config->callGraphProfileSort) {
2184     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file))
2185       if (Optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
2186         readCallGraph(*buffer);
2187     readCallGraphsFromObjectFiles<ELFT>();
2188   }
2189 
2190   // Write the result to the file.
2191   writeResult<ELFT>();
2192 }
2193