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