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