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