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