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