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