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