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