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