xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 2bf7c51d)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The driver drives the entire linking process. It is responsible for
11 // parsing command line options and doing whatever it is instructed to do.
12 //
13 // One notable thing in the LLD's driver when compared to other linkers is
14 // that the LLD's driver is agnostic on the host operating system.
15 // Other linkers usually have implicit default values (such as a dynamic
16 // linker path or library paths) for each host OS.
17 //
18 // I don't think implicit default values are useful because they are
19 // usually explicitly specified by the compiler driver. They can even
20 // be harmful when you are doing cross-linking. Therefore, in LLD, we
21 // simply trust the compiler driver to pass all required options and
22 // don't try to make effort on our side.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "Driver.h"
27 #include "Config.h"
28 #include "Filesystem.h"
29 #include "ICF.h"
30 #include "InputFiles.h"
31 #include "InputSection.h"
32 #include "LinkerScript.h"
33 #include "MarkLive.h"
34 #include "OutputSections.h"
35 #include "ScriptParser.h"
36 #include "SymbolTable.h"
37 #include "Symbols.h"
38 #include "SyntheticSections.h"
39 #include "Target.h"
40 #include "Writer.h"
41 #include "lld/Common/Args.h"
42 #include "lld/Common/Driver.h"
43 #include "lld/Common/ErrorHandler.h"
44 #include "lld/Common/Memory.h"
45 #include "lld/Common/Strings.h"
46 #include "lld/Common/TargetOptionsCommandFlags.h"
47 #include "lld/Common/Threads.h"
48 #include "lld/Common/Version.h"
49 #include "llvm/ADT/SetVector.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/StringSwitch.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compression.h"
54 #include "llvm/Support/Path.h"
55 #include "llvm/Support/TarWriter.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <cstdlib>
59 #include <utility>
60 
61 using namespace llvm;
62 using namespace llvm::ELF;
63 using namespace llvm::object;
64 using namespace llvm::sys;
65 
66 using namespace lld;
67 using namespace lld::elf;
68 
69 Configuration *elf::Config;
70 LinkerDriver *elf::Driver;
71 
72 static void setConfigs(opt::InputArgList &Args);
73 
74 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
75                raw_ostream &Error) {
76   errorHandler().LogName = Args[0];
77   errorHandler().ErrorLimitExceededMsg =
78       "too many errors emitted, stopping now (use "
79       "-error-limit=0 to see all errors)";
80   errorHandler().ErrorOS = &Error;
81   errorHandler().ExitEarly = CanExitEarly;
82   errorHandler().ColorDiagnostics = Error.has_colors();
83 
84   InputSections.clear();
85   OutputSections.clear();
86   Tar = nullptr;
87   BinaryFiles.clear();
88   BitcodeFiles.clear();
89   ObjectFiles.clear();
90   SharedFiles.clear();
91 
92   Config = make<Configuration>();
93   Driver = make<LinkerDriver>();
94   Script = make<LinkerScript>();
95   Symtab = make<SymbolTable>();
96   Config->ProgName = Args[0];
97 
98   Driver->main(Args);
99 
100   // Exit immediately if we don't need to return to the caller.
101   // This saves time because the overhead of calling destructors
102   // for all globally-allocated objects is not negligible.
103   if (CanExitEarly)
104     exitLld(errorCount() ? 1 : 0);
105 
106   freeArena();
107   return !errorCount();
108 }
109 
110 // Parses a linker -m option.
111 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
112   uint8_t OSABI = 0;
113   StringRef S = Emul;
114   if (S.endswith("_fbsd")) {
115     S = S.drop_back(5);
116     OSABI = ELFOSABI_FREEBSD;
117   }
118 
119   std::pair<ELFKind, uint16_t> Ret =
120       StringSwitch<std::pair<ELFKind, uint16_t>>(S)
121           .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
122           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
123           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
124           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
125           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
126           .Case("elf32ppc", {ELF32BEKind, EM_PPC})
127           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
128           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
129           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
130           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
131           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
132           .Case("elf_i386", {ELF32LEKind, EM_386})
133           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
134           .Default({ELFNoneKind, EM_NONE});
135 
136   if (Ret.first == ELFNoneKind)
137     error("unknown emulation: " + Emul);
138   return std::make_tuple(Ret.first, Ret.second, OSABI);
139 }
140 
141 // Returns slices of MB by parsing MB as an archive file.
142 // Each slice consists of a member file in the archive.
143 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
144     MemoryBufferRef MB) {
145   std::unique_ptr<Archive> File =
146       CHECK(Archive::create(MB),
147             MB.getBufferIdentifier() + ": failed to parse archive");
148 
149   std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
150   Error Err = Error::success();
151   bool AddToTar = File->isThin() && Tar;
152   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
153     Archive::Child C =
154         CHECK(COrErr, MB.getBufferIdentifier() +
155                           ": could not get the child of the archive");
156     MemoryBufferRef MBRef =
157         CHECK(C.getMemoryBufferRef(),
158               MB.getBufferIdentifier() +
159                   ": could not get the buffer for a child of the archive");
160     if (AddToTar)
161       Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer());
162     V.push_back(std::make_pair(MBRef, C.getChildOffset()));
163   }
164   if (Err)
165     fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
166           toString(std::move(Err)));
167 
168   // Take ownership of memory buffers created for members of thin archives.
169   for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
170     make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
171 
172   return V;
173 }
174 
175 // Opens a file and create a file object. Path has to be resolved already.
176 void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
177   using namespace sys::fs;
178 
179   Optional<MemoryBufferRef> Buffer = readFile(Path);
180   if (!Buffer.hasValue())
181     return;
182   MemoryBufferRef MBRef = *Buffer;
183 
184   if (InBinary) {
185     Files.push_back(make<BinaryFile>(MBRef));
186     return;
187   }
188 
189   switch (identify_magic(MBRef.getBuffer())) {
190   case file_magic::unknown:
191     readLinkerScript(MBRef);
192     return;
193   case file_magic::archive: {
194     // Handle -whole-archive.
195     if (InWholeArchive) {
196       for (const auto &P : getArchiveMembers(MBRef))
197         Files.push_back(createObjectFile(P.first, Path, P.second));
198       return;
199     }
200 
201     std::unique_ptr<Archive> File =
202         CHECK(Archive::create(MBRef), Path + ": failed to parse archive");
203 
204     // If an archive file has no symbol table, it is likely that a user
205     // is attempting LTO and using a default ar command that doesn't
206     // understand the LLVM bitcode file. It is a pretty common error, so
207     // we'll handle it as if it had a symbol table.
208     if (!File->isEmpty() && !File->hasSymbolTable()) {
209       for (const auto &P : getArchiveMembers(MBRef))
210         Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
211       return;
212     }
213 
214     // Handle the regular case.
215     Files.push_back(make<ArchiveFile>(std::move(File)));
216     return;
217   }
218   case file_magic::elf_shared_object:
219     if (Config->Relocatable) {
220       error("attempted static link of dynamic object " + Path);
221       return;
222     }
223 
224     // DSOs usually have DT_SONAME tags in their ELF headers, and the
225     // sonames are used to identify DSOs. But if they are missing,
226     // they are identified by filenames. We don't know whether the new
227     // file has a DT_SONAME or not because we haven't parsed it yet.
228     // Here, we set the default soname for the file because we might
229     // need it later.
230     //
231     // If a file was specified by -lfoo, the directory part is not
232     // significant, as a user did not specify it. This behavior is
233     // compatible with GNU.
234     Files.push_back(
235         createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path));
236     return;
237   case file_magic::bitcode:
238   case file_magic::elf_relocatable:
239     if (InLib)
240       Files.push_back(make<LazyObjFile>(MBRef, "", 0));
241     else
242       Files.push_back(createObjectFile(MBRef));
243     break;
244   default:
245     error(Path + ": unknown file type");
246   }
247 }
248 
249 // Add a given library by searching it from input search paths.
250 void LinkerDriver::addLibrary(StringRef Name) {
251   if (Optional<std::string> Path = searchLibrary(Name))
252     addFile(*Path, /*WithLOption=*/true);
253   else
254     error("unable to find library -l" + Name);
255 }
256 
257 // This function is called on startup. We need this for LTO since
258 // LTO calls LLVM functions to compile bitcode files to native code.
259 // Technically this can be delayed until we read bitcode files, but
260 // we don't bother to do lazily because the initialization is fast.
261 static void initLLVM() {
262   InitializeAllTargets();
263   InitializeAllTargetMCs();
264   InitializeAllAsmPrinters();
265   InitializeAllAsmParsers();
266 }
267 
268 // Some command line options or some combinations of them are not allowed.
269 // This function checks for such errors.
270 static void checkOptions(opt::InputArgList &Args) {
271   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
272   // table which is a relatively new feature.
273   if (Config->EMachine == EM_MIPS && Config->GnuHash)
274     error("the .gnu.hash section is not compatible with the MIPS target.");
275 
276   if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64)
277     error("--fix-cortex-a53-843419 is only supported on AArch64 targets.");
278 
279   if (Config->Pie && Config->Shared)
280     error("-shared and -pie may not be used together");
281 
282   if (!Config->Shared && !Config->FilterList.empty())
283     error("-F may not be used without -shared");
284 
285   if (!Config->Shared && !Config->AuxiliaryList.empty())
286     error("-f may not be used without -shared");
287 
288   if (!Config->Relocatable && !Config->DefineCommon)
289     error("-no-define-common not supported in non relocatable output");
290 
291   if (Config->Relocatable) {
292     if (Config->Shared)
293       error("-r and -shared may not be used together");
294     if (Config->GcSections)
295       error("-r and --gc-sections may not be used together");
296     if (Config->ICF)
297       error("-r and --icf may not be used together");
298     if (Config->Pie)
299       error("-r and -pie may not be used together");
300   }
301 }
302 
303 static const char *getReproduceOption(opt::InputArgList &Args) {
304   if (auto *Arg = Args.getLastArg(OPT_reproduce))
305     return Arg->getValue();
306   return getenv("LLD_REPRODUCE");
307 }
308 
309 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
310   for (auto *Arg : Args.filtered(OPT_z))
311     if (Key == Arg->getValue())
312       return true;
313   return false;
314 }
315 
316 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
317   ELFOptTable Parser;
318   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
319 
320   // Interpret this flag early because error() depends on them.
321   errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
322 
323   // Handle -help
324   if (Args.hasArg(OPT_help)) {
325     printHelp();
326     return;
327   }
328 
329   // Handle -v or -version.
330   //
331   // A note about "compatible with GNU linkers" message: this is a hack for
332   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
333   // still the newest version in March 2017) or earlier to recognize LLD as
334   // a GNU compatible linker. As long as an output for the -v option
335   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
336   //
337   // This is somewhat ugly hack, but in reality, we had no choice other
338   // than doing this. Considering the very long release cycle of Libtool,
339   // it is not easy to improve it to recognize LLD as a GNU compatible
340   // linker in a timely manner. Even if we can make it, there are still a
341   // lot of "configure" scripts out there that are generated by old version
342   // of Libtool. We cannot convince every software developer to migrate to
343   // the latest version and re-generate scripts. So we have this hack.
344   if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
345     message(getLLDVersion() + " (compatible with GNU linkers)");
346 
347   // The behavior of -v or --version is a bit strange, but this is
348   // needed for compatibility with GNU linkers.
349   if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT))
350     return;
351   if (Args.hasArg(OPT_version))
352     return;
353 
354   if (const char *Path = getReproduceOption(Args)) {
355     // Note that --reproduce is a debug option so you can ignore it
356     // if you are trying to understand the whole picture of the code.
357     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
358         TarWriter::create(Path, path::stem(Path));
359     if (ErrOrWriter) {
360       Tar = ErrOrWriter->get();
361       Tar->append("response.txt", createResponseFile(Args));
362       Tar->append("version.txt", getLLDVersion() + "\n");
363       make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
364     } else {
365       error(Twine("--reproduce: failed to open ") + Path + ": " +
366             toString(ErrOrWriter.takeError()));
367     }
368   }
369 
370   readConfigs(Args);
371   initLLVM();
372   createFiles(Args);
373   inferMachineType();
374   setConfigs(Args);
375   checkOptions(Args);
376   if (errorCount())
377     return;
378 
379   switch (Config->EKind) {
380   case ELF32LEKind:
381     link<ELF32LE>(Args);
382     return;
383   case ELF32BEKind:
384     link<ELF32BE>(Args);
385     return;
386   case ELF64LEKind:
387     link<ELF64LE>(Args);
388     return;
389   case ELF64BEKind:
390     link<ELF64BE>(Args);
391     return;
392   default:
393     llvm_unreachable("unknown Config->EKind");
394   }
395 }
396 
397 static std::string getRpath(opt::InputArgList &Args) {
398   std::vector<StringRef> V = args::getStrings(Args, OPT_rpath);
399   return llvm::join(V.begin(), V.end(), ":");
400 }
401 
402 // Determines what we should do if there are remaining unresolved
403 // symbols after the name resolution.
404 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
405   if (Args.hasArg(OPT_relocatable))
406     return UnresolvedPolicy::IgnoreAll;
407 
408   UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols,
409                                               OPT_warn_unresolved_symbols, true)
410                                      ? UnresolvedPolicy::ReportError
411                                      : UnresolvedPolicy::Warn;
412 
413   // Process the last of -unresolved-symbols, -no-undefined or -z defs.
414   for (auto *Arg : llvm::reverse(Args)) {
415     switch (Arg->getOption().getID()) {
416     case OPT_unresolved_symbols: {
417       StringRef S = Arg->getValue();
418       if (S == "ignore-all" || S == "ignore-in-object-files")
419         return UnresolvedPolicy::Ignore;
420       if (S == "ignore-in-shared-libs" || S == "report-all")
421         return ErrorOrWarn;
422       error("unknown --unresolved-symbols value: " + S);
423       continue;
424     }
425     case OPT_no_undefined:
426       return ErrorOrWarn;
427     case OPT_z:
428       if (StringRef(Arg->getValue()) == "defs")
429         return ErrorOrWarn;
430       continue;
431     }
432   }
433 
434   // -shared implies -unresolved-symbols=ignore-all because missing
435   // symbols are likely to be resolved at runtime using other DSOs.
436   if (Config->Shared)
437     return UnresolvedPolicy::Ignore;
438   return ErrorOrWarn;
439 }
440 
441 static Target2Policy getTarget2(opt::InputArgList &Args) {
442   StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
443   if (S == "rel")
444     return Target2Policy::Rel;
445   if (S == "abs")
446     return Target2Policy::Abs;
447   if (S == "got-rel")
448     return Target2Policy::GotRel;
449   error("unknown --target2 option: " + S);
450   return Target2Policy::GotRel;
451 }
452 
453 static bool isOutputFormatBinary(opt::InputArgList &Args) {
454   if (auto *Arg = Args.getLastArg(OPT_oformat)) {
455     StringRef S = Arg->getValue();
456     if (S == "binary")
457       return true;
458     error("unknown --oformat value: " + S);
459   }
460   return false;
461 }
462 
463 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
464   if (Args.hasArg(OPT_relocatable))
465     return DiscardPolicy::None;
466 
467   auto *Arg =
468       Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
469   if (!Arg)
470     return DiscardPolicy::Default;
471   if (Arg->getOption().getID() == OPT_discard_all)
472     return DiscardPolicy::All;
473   if (Arg->getOption().getID() == OPT_discard_locals)
474     return DiscardPolicy::Locals;
475   return DiscardPolicy::None;
476 }
477 
478 static StringRef getDynamicLinker(opt::InputArgList &Args) {
479   auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
480   if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
481     return "";
482   return Arg->getValue();
483 }
484 
485 static StripPolicy getStrip(opt::InputArgList &Args) {
486   if (Args.hasArg(OPT_relocatable))
487     return StripPolicy::None;
488 
489   auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
490   if (!Arg)
491     return StripPolicy::None;
492   if (Arg->getOption().getID() == OPT_strip_all)
493     return StripPolicy::All;
494   return StripPolicy::Debug;
495 }
496 
497 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) {
498   uint64_t VA = 0;
499   if (S.startswith("0x"))
500     S = S.drop_front(2);
501   if (!to_integer(S, VA, 16))
502     error("invalid argument: " + toString(Arg));
503   return VA;
504 }
505 
506 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
507   StringMap<uint64_t> Ret;
508   for (auto *Arg : Args.filtered(OPT_section_start)) {
509     StringRef Name;
510     StringRef Addr;
511     std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
512     Ret[Name] = parseSectionAddress(Addr, *Arg);
513   }
514 
515   if (auto *Arg = Args.getLastArg(OPT_Ttext))
516     Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg);
517   if (auto *Arg = Args.getLastArg(OPT_Tdata))
518     Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg);
519   if (auto *Arg = Args.getLastArg(OPT_Tbss))
520     Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg);
521   return Ret;
522 }
523 
524 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
525   StringRef S = Args.getLastArgValue(OPT_sort_section);
526   if (S == "alignment")
527     return SortSectionPolicy::Alignment;
528   if (S == "name")
529     return SortSectionPolicy::Name;
530   if (!S.empty())
531     error("unknown --sort-section rule: " + S);
532   return SortSectionPolicy::Default;
533 }
534 
535 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) {
536   StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place");
537   if (S == "warn")
538     return OrphanHandlingPolicy::Warn;
539   if (S == "error")
540     return OrphanHandlingPolicy::Error;
541   if (S != "place")
542     error("unknown --orphan-handling mode: " + S);
543   return OrphanHandlingPolicy::Place;
544 }
545 
546 // Parse --build-id or --build-id=<style>. We handle "tree" as a
547 // synonym for "sha1" because all our hash functions including
548 // -build-id=sha1 are actually tree hashes for performance reasons.
549 static std::pair<BuildIdKind, std::vector<uint8_t>>
550 getBuildId(opt::InputArgList &Args) {
551   auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
552   if (!Arg)
553     return {BuildIdKind::None, {}};
554 
555   if (Arg->getOption().getID() == OPT_build_id)
556     return {BuildIdKind::Fast, {}};
557 
558   StringRef S = Arg->getValue();
559   if (S == "fast")
560     return {BuildIdKind::Fast, {}};
561   if (S == "md5")
562     return {BuildIdKind::Md5, {}};
563   if (S == "sha1" || S == "tree")
564     return {BuildIdKind::Sha1, {}};
565   if (S == "uuid")
566     return {BuildIdKind::Uuid, {}};
567   if (S.startswith("0x"))
568     return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
569 
570   if (S != "none")
571     error("unknown --build-id style: " + S);
572   return {BuildIdKind::None, {}};
573 }
574 
575 static void readCallGraph(MemoryBufferRef MB) {
576   // Build a map from symbol name to section
577   DenseMap<StringRef, const Symbol *> SymbolNameToSymbol;
578   for (InputFile *File : ObjectFiles)
579     for (Symbol *Sym : File->getSymbols())
580       SymbolNameToSymbol[Sym->getName()] = Sym;
581 
582   for (StringRef L : args::getLines(MB)) {
583     SmallVector<StringRef, 3> Fields;
584     L.split(Fields, ' ');
585     if (Fields.size() != 3)
586       fatal("parse error");
587     uint64_t Count;
588     if (!to_integer(Fields[2], Count))
589       fatal("parse error");
590     const Symbol *FromSym = SymbolNameToSymbol.lookup(Fields[0]);
591     const Symbol *ToSym = SymbolNameToSymbol.lookup(Fields[1]);
592     if (Config->WarnSymbolOrdering) {
593       if (!FromSym)
594         warn("call graph file: no such symbol: " + Fields[0]);
595       if (!ToSym)
596         warn("call graph file: no such symbol: " + Fields[1]);
597     }
598     if (!FromSym || !ToSym || Count == 0)
599       continue;
600     warnUnorderableSymbol(FromSym);
601     warnUnorderableSymbol(ToSym);
602     const Defined *FromSymD = dyn_cast<Defined>(FromSym);
603     const Defined *ToSymD = dyn_cast<Defined>(ToSym);
604     if (!FromSymD || !ToSymD)
605       continue;
606     const auto *FromSB = dyn_cast_or_null<InputSectionBase>(FromSymD->Section);
607     const auto *ToSB = dyn_cast_or_null<InputSectionBase>(ToSymD->Section);
608     if (!FromSB || !ToSB)
609       continue;
610     Config->CallGraphProfile[std::make_pair(FromSB, ToSB)] += Count;
611   }
612 }
613 
614 static bool getCompressDebugSections(opt::InputArgList &Args) {
615   StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
616   if (S == "none")
617     return false;
618   if (S != "zlib")
619     error("unknown --compress-debug-sections value: " + S);
620   if (!zlib::isAvailable())
621     error("--compress-debug-sections: zlib is not available");
622   return true;
623 }
624 
625 static int parseInt(StringRef S, opt::Arg *Arg) {
626   int V = 0;
627   if (!to_integer(S, V, 10))
628     error(Arg->getSpelling() + "=" + Arg->getValue() +
629           ": number expected, but got '" + S + "'");
630   return V;
631 }
632 
633 // Parse the symbol ordering file and warn for any duplicate entries.
634 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef MB) {
635   SetVector<StringRef> Names;
636   for (StringRef S : args::getLines(MB))
637     if (!Names.insert(S) && Config->WarnSymbolOrdering)
638       warn(MB.getBufferIdentifier() + ": duplicate ordered symbol: " + S);
639 
640   return Names.takeVector();
641 }
642 
643 static void parseClangOption(StringRef Opt, const Twine &Msg) {
644   std::string Err;
645   raw_string_ostream OS(Err);
646 
647   const char *Argv[] = {Config->ProgName.data(), Opt.data()};
648   if (cl::ParseCommandLineOptions(2, Argv, "", &OS))
649     return;
650   OS.flush();
651   error(Msg + ": " + StringRef(Err).trim());
652 }
653 
654 // Initializes Config members by the command line options.
655 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
656   errorHandler().Verbose = Args.hasArg(OPT_verbose);
657   errorHandler().FatalWarnings =
658       Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
659 
660   Config->AllowMultipleDefinition =
661       Args.hasFlag(OPT_allow_multiple_definition,
662                    OPT_no_allow_multiple_definition, false) ||
663       hasZOption(Args, "muldefs");
664   Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary);
665   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
666   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
667   Config->CheckSections =
668       Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
669   Config->Chroot = Args.getLastArgValue(OPT_chroot);
670   Config->CompressDebugSections = getCompressDebugSections(Args);
671   Config->Cref = Args.hasFlag(OPT_cref, OPT_no_cref, false);
672   Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common,
673                                       !Args.hasArg(OPT_relocatable));
674   Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
675   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
676   Config->Discard = getDiscard(Args);
677   Config->DynamicLinker = getDynamicLinker(Args);
678   Config->EhFrameHdr =
679       Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
680   Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
681   Config->EnableNewDtags =
682       Args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
683   Config->Entry = Args.getLastArgValue(OPT_entry);
684   Config->ExportDynamic =
685       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
686   Config->FilterList = args::getStrings(Args, OPT_filter);
687   Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
688   Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419);
689   Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
690   Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
691   Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
692   Config->ICF = Args.hasFlag(OPT_icf_all, OPT_icf_none, false);
693   Config->IgnoreDataAddressEquality =
694       Args.hasArg(OPT_ignore_data_address_equality);
695   Config->IgnoreFunctionAddressEquality =
696       Args.hasArg(OPT_ignore_function_address_equality);
697   Config->Init = Args.getLastArgValue(OPT_init, "_init");
698   Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
699   Config->LTODebugPassManager = Args.hasArg(OPT_lto_debug_pass_manager);
700   Config->LTONewPassManager = Args.hasArg(OPT_lto_new_pass_manager);
701   Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
702   Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
703   Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
704   Config->LTOSampleProfile = Args.getLastArgValue(OPT_lto_sample_profile);
705   Config->MapFile = Args.getLastArgValue(OPT_Map);
706   Config->MergeArmExidx =
707       Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
708   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
709   Config->Nostdlib = Args.hasArg(OPT_nostdlib);
710   Config->OFormatBinary = isOutputFormatBinary(Args);
711   Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false);
712   Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
713   Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
714   Config->Optimize = args::getInteger(Args, OPT_O, 1);
715   Config->OrphanHandling = getOrphanHandling(Args);
716   Config->OutputFile = Args.getLastArgValue(OPT_o);
717   Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false);
718   Config->PrintIcfSections =
719       Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
720   Config->PrintGcSections =
721       Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
722   Config->Rpath = getRpath(Args);
723   Config->Relocatable = Args.hasArg(OPT_relocatable);
724   Config->SaveTemps = Args.hasArg(OPT_save_temps);
725   Config->SearchPaths = args::getStrings(Args, OPT_library_path);
726   Config->SectionStartMap = getSectionStartMap(Args);
727   Config->Shared = Args.hasArg(OPT_shared);
728   Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
729   Config->SoName = Args.getLastArgValue(OPT_soname);
730   Config->SortSection = getSortSection(Args);
731   Config->Strip = getStrip(Args);
732   Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
733   Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
734   Config->Target2 = getTarget2(Args);
735   Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
736   Config->ThinLTOCachePolicy = CHECK(
737       parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
738       "--thinlto-cache-policy: invalid cache policy");
739   Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
740   ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
741   Config->Trace = Args.hasArg(OPT_trace);
742   Config->Undefined = args::getStrings(Args, OPT_undefined);
743   Config->UndefinedVersion =
744       Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
745   Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
746   Config->WarnBackrefs =
747       Args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
748   Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
749   Config->WarnSymbolOrdering =
750       Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
751   Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
752   Config->ZExecstack = hasZOption(Args, "execstack");
753   Config->ZHazardplt = hasZOption(Args, "hazardplt");
754   Config->ZNocopyreloc = hasZOption(Args, "nocopyreloc");
755   Config->ZNodelete = hasZOption(Args, "nodelete");
756   Config->ZNodlopen = hasZOption(Args, "nodlopen");
757   Config->ZNow = hasZOption(Args, "now");
758   Config->ZOrigin = hasZOption(Args, "origin");
759   Config->ZRelro = !hasZOption(Args, "norelro");
760   Config->ZRetpolineplt = hasZOption(Args, "retpolineplt");
761   Config->ZRodynamic = hasZOption(Args, "rodynamic");
762   Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
763   Config->ZText = !hasZOption(Args, "notext");
764   Config->ZWxneeded = hasZOption(Args, "wxneeded");
765 
766   // Parse LTO plugin-related options for compatibility with gold.
767   for (auto *Arg : Args.filtered(OPT_plugin_opt)) {
768     StringRef S = Arg->getValue();
769     if (S == "disable-verify")
770       Config->DisableVerify = true;
771     else if (S == "save-temps")
772       Config->SaveTemps = true;
773     else if (S.startswith("O"))
774       Config->LTOO = parseInt(S.substr(1), Arg);
775     else if (S.startswith("lto-partitions="))
776       Config->LTOPartitions = parseInt(S.substr(15), Arg);
777     else if (S.startswith("jobs="))
778       Config->ThinLTOJobs = parseInt(S.substr(5), Arg);
779     else if (S.startswith("mcpu="))
780       parseClangOption(Saver.save("-" + S), Arg->getSpelling());
781     else if (S == "new-pass-manager")
782       Config->LTONewPassManager = true;
783     else if (S == "debug-pass-manager")
784       Config->LTODebugPassManager = true;
785     else if (S.startswith("sample-profile="))
786       Config->LTOSampleProfile = S.substr(strlen("sample-profile="));
787     else if (!S.startswith("/") && !S.startswith("-fresolution=") &&
788              !S.startswith("-pass-through=") && !S.startswith("thinlto"))
789       parseClangOption(S, Arg->getSpelling());
790   }
791 
792   // Parse -mllvm options.
793   for (auto *Arg : Args.filtered(OPT_mllvm))
794     parseClangOption(Arg->getValue(), Arg->getSpelling());
795 
796   if (Config->LTOO > 3)
797     error("invalid optimization level for LTO: " + Twine(Config->LTOO));
798   if (Config->LTOPartitions == 0)
799     error("--lto-partitions: number of threads must be > 0");
800   if (Config->ThinLTOJobs == 0)
801     error("--thinlto-jobs: number of threads must be > 0");
802 
803   // Parse ELF{32,64}{LE,BE} and CPU type.
804   if (auto *Arg = Args.getLastArg(OPT_m)) {
805     StringRef S = Arg->getValue();
806     std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
807         parseEmulation(S);
808     Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
809     Config->Emulation = S;
810   }
811 
812   // Parse -hash-style={sysv,gnu,both}.
813   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
814     StringRef S = Arg->getValue();
815     if (S == "sysv")
816       Config->SysvHash = true;
817     else if (S == "gnu")
818       Config->GnuHash = true;
819     else if (S == "both")
820       Config->SysvHash = Config->GnuHash = true;
821     else
822       error("unknown -hash-style: " + S);
823   }
824 
825   if (Args.hasArg(OPT_print_map))
826     Config->MapFile = "-";
827 
828   // --omagic is an option to create old-fashioned executables in which
829   // .text segments are writable. Today, the option is still in use to
830   // create special-purpose programs such as boot loaders. It doesn't
831   // make sense to create PT_GNU_RELRO for such executables.
832   if (Config->Omagic)
833     Config->ZRelro = false;
834 
835   std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
836 
837   if (auto *Arg = Args.getLastArg(OPT_pack_dyn_relocs)) {
838     StringRef S = Arg->getValue();
839     if (S == "android")
840       Config->AndroidPackDynRelocs = true;
841     else if (S != "none")
842       error("unknown -pack-dyn-relocs format: " + S);
843   }
844 
845   if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
846     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
847       Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer);
848 
849   // If --retain-symbol-file is used, we'll keep only the symbols listed in
850   // the file and discard all others.
851   if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
852     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
853     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
854       for (StringRef S : args::getLines(*Buffer))
855         Config->VersionScriptGlobals.push_back(
856             {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
857   }
858 
859   bool HasExportDynamic =
860       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
861 
862   // Parses -dynamic-list and -export-dynamic-symbol. They make some
863   // symbols private. Note that -export-dynamic takes precedence over them
864   // as it says all symbols should be exported.
865   if (!HasExportDynamic) {
866     for (auto *Arg : Args.filtered(OPT_dynamic_list))
867       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
868         readDynamicList(*Buffer);
869 
870     for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
871       Config->DynamicList.push_back(
872           {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
873   }
874 
875   // If --export-dynamic-symbol=foo is given and symbol foo is defined in
876   // an object file in an archive file, that object file should be pulled
877   // out and linked. (It doesn't have to behave like that from technical
878   // point of view, but this is needed for compatibility with GNU.)
879   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
880     Config->Undefined.push_back(Arg->getValue());
881 
882   for (auto *Arg : Args.filtered(OPT_version_script))
883     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
884       readVersionScript(*Buffer);
885 }
886 
887 // Some Config members do not directly correspond to any particular
888 // command line options, but computed based on other Config values.
889 // This function initialize such members. See Config.h for the details
890 // of these values.
891 static void setConfigs(opt::InputArgList &Args) {
892   ELFKind Kind = Config->EKind;
893   uint16_t Machine = Config->EMachine;
894 
895   // There is an ILP32 ABI for x86-64, although it's not very popular.
896   // It is called the x32 ABI.
897   bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64);
898 
899   Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
900   Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind);
901   Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind);
902   Config->Endianness =
903       Config->IsLE ? support::endianness::little : support::endianness::big;
904   Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS);
905   Config->IsRela =
906       (Config->Is64 || IsX32 || Machine == EM_PPC) && Machine != EM_MIPS;
907   Config->Pic = Config->Pie || Config->Shared;
908   Config->Wordsize = Config->Is64 ? 8 : 4;
909   // If the output uses REL relocations we must store the dynamic relocation
910   // addends to the output sections. We also store addends for RELA relocations
911   // if --apply-dynamic-relocs is used.
912   // We default to not writing the addends when using RELA relocations since
913   // any standard conforming tool can find it in r_addend.
914   Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs,
915                                       OPT_no_apply_dynamic_relocs, false) ||
916                          !Config->IsRela;
917 }
918 
919 // Returns a value of "-format" option.
920 static bool getBinaryOption(StringRef S) {
921   if (S == "binary")
922     return true;
923   if (S == "elf" || S == "default")
924     return false;
925   error("unknown -format value: " + S +
926         " (supported formats: elf, default, binary)");
927   return false;
928 }
929 
930 void LinkerDriver::createFiles(opt::InputArgList &Args) {
931   for (auto *Arg : Args) {
932     switch (Arg->getOption().getUnaliasedOption().getID()) {
933     case OPT_library:
934       addLibrary(Arg->getValue());
935       break;
936     case OPT_INPUT:
937       addFile(Arg->getValue(), /*WithLOption=*/false);
938       break;
939     case OPT_defsym: {
940       StringRef From;
941       StringRef To;
942       std::tie(From, To) = StringRef(Arg->getValue()).split('=');
943       readDefsym(From, MemoryBufferRef(To, "-defsym"));
944       break;
945     }
946     case OPT_script:
947       if (Optional<std::string> Path = searchLinkerScript(Arg->getValue())) {
948         if (Optional<MemoryBufferRef> MB = readFile(*Path))
949           readLinkerScript(*MB);
950         break;
951       }
952       error(Twine("cannot find linker script ") + Arg->getValue());
953       break;
954     case OPT_as_needed:
955       Config->AsNeeded = true;
956       break;
957     case OPT_format:
958       InBinary = getBinaryOption(Arg->getValue());
959       break;
960     case OPT_no_as_needed:
961       Config->AsNeeded = false;
962       break;
963     case OPT_Bstatic:
964       Config->Static = true;
965       break;
966     case OPT_Bdynamic:
967       Config->Static = false;
968       break;
969     case OPT_whole_archive:
970       InWholeArchive = true;
971       break;
972     case OPT_no_whole_archive:
973       InWholeArchive = false;
974       break;
975     case OPT_just_symbols:
976       if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue())) {
977         Files.push_back(createObjectFile(*MB));
978         Files.back()->JustSymbols = true;
979       }
980       break;
981     case OPT_start_group:
982       if (InputFile::IsInGroup)
983         error("nested --start-group");
984       InputFile::IsInGroup = true;
985       break;
986     case OPT_end_group:
987       if (!InputFile::IsInGroup)
988         error("stray --end-group");
989       InputFile::IsInGroup = false;
990       ++InputFile::NextGroupId;
991       break;
992     case OPT_start_lib:
993       InLib = true;
994       break;
995     case OPT_end_lib:
996       InLib = false;
997       break;
998     }
999   }
1000 
1001   if (Files.empty() && errorCount() == 0)
1002     error("no input files");
1003 }
1004 
1005 // If -m <machine_type> was not given, infer it from object files.
1006 void LinkerDriver::inferMachineType() {
1007   if (Config->EKind != ELFNoneKind)
1008     return;
1009 
1010   for (InputFile *F : Files) {
1011     if (F->EKind == ELFNoneKind)
1012       continue;
1013     Config->EKind = F->EKind;
1014     Config->EMachine = F->EMachine;
1015     Config->OSABI = F->OSABI;
1016     Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
1017     return;
1018   }
1019   error("target emulation unknown: -m or at least one .o file required");
1020 }
1021 
1022 // Parse -z max-page-size=<value>. The default value is defined by
1023 // each target.
1024 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
1025   uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
1026                                        Target->DefaultMaxPageSize);
1027   if (!isPowerOf2_64(Val))
1028     error("max-page-size: value isn't a power of 2");
1029   return Val;
1030 }
1031 
1032 // Parses -image-base option.
1033 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
1034   // Because we are using "Config->MaxPageSize" here, this function has to be
1035   // called after the variable is initialized.
1036   auto *Arg = Args.getLastArg(OPT_image_base);
1037   if (!Arg)
1038     return None;
1039 
1040   StringRef S = Arg->getValue();
1041   uint64_t V;
1042   if (!to_integer(S, V)) {
1043     error("-image-base: number expected, but got " + S);
1044     return 0;
1045   }
1046   if ((V % Config->MaxPageSize) != 0)
1047     warn("-image-base: address isn't multiple of page size: " + S);
1048   return V;
1049 }
1050 
1051 // Parses `--exclude-libs=lib,lib,...`.
1052 // The library names may be delimited by commas or colons.
1053 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
1054   DenseSet<StringRef> Ret;
1055   for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
1056     StringRef S = Arg->getValue();
1057     for (;;) {
1058       size_t Pos = S.find_first_of(",:");
1059       if (Pos == StringRef::npos)
1060         break;
1061       Ret.insert(S.substr(0, Pos));
1062       S = S.substr(Pos + 1);
1063     }
1064     Ret.insert(S);
1065   }
1066   return Ret;
1067 }
1068 
1069 // Handles the -exclude-libs option. If a static library file is specified
1070 // by the -exclude-libs option, all public symbols from the archive become
1071 // private unless otherwise specified by version scripts or something.
1072 // A special library name "ALL" means all archive files.
1073 //
1074 // This is not a popular option, but some programs such as bionic libc use it.
1075 template <class ELFT>
1076 static void excludeLibs(opt::InputArgList &Args) {
1077   DenseSet<StringRef> Libs = getExcludeLibs(Args);
1078   bool All = Libs.count("ALL");
1079 
1080   for (InputFile *File : ObjectFiles)
1081     if (!File->ArchiveName.empty())
1082       if (All || Libs.count(path::filename(File->ArchiveName)))
1083         for (Symbol *Sym : File->getSymbols())
1084           if (!Sym->isLocal() && Sym->File == File)
1085             Sym->VersionId = VER_NDX_LOCAL;
1086 }
1087 
1088 // Force Sym to be entered in the output. Used for -u or equivalent.
1089 template <class ELFT> static void handleUndefined(StringRef Name) {
1090   Symbol *Sym = Symtab->find(Name);
1091   if (!Sym)
1092     return;
1093 
1094   // Since symbol S may not be used inside the program, LTO may
1095   // eliminate it. Mark the symbol as "used" to prevent it.
1096   Sym->IsUsedInRegularObj = true;
1097 
1098   if (Sym->isLazy())
1099     Symtab->fetchLazy<ELFT>(Sym);
1100 }
1101 
1102 // Do actual linking. Note that when this function is called,
1103 // all linker scripts have already been parsed.
1104 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1105   Target = getTarget();
1106 
1107   Config->MaxPageSize = getMaxPageSize(Args);
1108   Config->ImageBase = getImageBase(Args);
1109 
1110   // If a -hash-style option was not given, set to a default value,
1111   // which varies depending on the target.
1112   if (!Args.hasArg(OPT_hash_style)) {
1113     if (Config->EMachine == EM_MIPS)
1114       Config->SysvHash = true;
1115     else
1116       Config->SysvHash = Config->GnuHash = true;
1117   }
1118 
1119   // Default output filename is "a.out" by the Unix tradition.
1120   if (Config->OutputFile.empty())
1121     Config->OutputFile = "a.out";
1122 
1123   // Fail early if the output file or map file is not writable. If a user has a
1124   // long link, e.g. due to a large LTO link, they do not wish to run it and
1125   // find that it failed because there was a mistake in their command-line.
1126   if (auto E = tryCreateFile(Config->OutputFile))
1127     error("cannot open output file " + Config->OutputFile + ": " + E.message());
1128   if (auto E = tryCreateFile(Config->MapFile))
1129     error("cannot open map file " + Config->MapFile + ": " + E.message());
1130   if (errorCount())
1131     return;
1132 
1133   // Use default entry point name if no name was given via the command
1134   // line nor linker scripts. For some reason, MIPS entry point name is
1135   // different from others.
1136   Config->WarnMissingEntry =
1137       (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
1138   if (Config->Entry.empty() && !Config->Relocatable)
1139     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
1140 
1141   // Handle --trace-symbol.
1142   for (auto *Arg : Args.filtered(OPT_trace_symbol))
1143     Symtab->trace(Arg->getValue());
1144 
1145   // Add all files to the symbol table. This will add almost all
1146   // symbols that we need to the symbol table.
1147   for (InputFile *F : Files)
1148     Symtab->addFile<ELFT>(F);
1149 
1150   // Now that we have every file, we can decide if we will need a
1151   // dynamic symbol table.
1152   // We need one if we were asked to export dynamic symbols or if we are
1153   // producing a shared library.
1154   // We also need one if any shared libraries are used and for pie executables
1155   // (probably because the dynamic linker needs it).
1156   Config->HasDynSymTab =
1157       !SharedFiles.empty() || Config->Pic || Config->ExportDynamic;
1158 
1159   // Some symbols (such as __ehdr_start) are defined lazily only when there
1160   // are undefined symbols for them, so we add these to trigger that logic.
1161   for (StringRef Sym : Script->ReferencedSymbols)
1162     Symtab->addUndefined<ELFT>(Sym);
1163 
1164   // Handle the `--undefined <sym>` options.
1165   for (StringRef S : Config->Undefined)
1166     handleUndefined<ELFT>(S);
1167 
1168   // If an entry symbol is in a static archive, pull out that file now
1169   // to complete the symbol table. After this, no new names except a
1170   // few linker-synthesized ones will be added to the symbol table.
1171   handleUndefined<ELFT>(Config->Entry);
1172 
1173   // Return if there were name resolution errors.
1174   if (errorCount())
1175     return;
1176 
1177   // Now when we read all script files, we want to finalize order of linker
1178   // script commands, which can be not yet final because of INSERT commands.
1179   Script->processInsertCommands();
1180 
1181   // We want to declare linker script's symbols early,
1182   // so that we can version them.
1183   // They also might be exported if referenced by DSOs.
1184   Script->declareSymbols();
1185 
1186   // Handle the -exclude-libs option.
1187   if (Args.hasArg(OPT_exclude_libs))
1188     excludeLibs<ELFT>(Args);
1189 
1190   // Create ElfHeader early. We need a dummy section in
1191   // addReservedSymbols to mark the created symbols as not absolute.
1192   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1193   Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1194 
1195   // We need to create some reserved symbols such as _end. Create them.
1196   if (!Config->Relocatable)
1197     addReservedSymbols();
1198 
1199   // Apply version scripts.
1200   //
1201   // For a relocatable output, version scripts don't make sense, and
1202   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1203   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1204   if (!Config->Relocatable)
1205     Symtab->scanVersionScript();
1206 
1207   // Create wrapped symbols for -wrap option.
1208   for (auto *Arg : Args.filtered(OPT_wrap))
1209     Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1210 
1211   Symtab->addCombinedLTOObject<ELFT>();
1212   if (errorCount())
1213     return;
1214 
1215   // Apply symbol renames for -wrap.
1216   Symtab->applySymbolWrap();
1217 
1218   // Now that we have a complete list of input files.
1219   // Beyond this point, no new files are added.
1220   // Aggregate all input sections into one place.
1221   for (InputFile *F : ObjectFiles)
1222     for (InputSectionBase *S : F->getSections())
1223       if (S && S != &InputSection::Discarded)
1224         InputSections.push_back(S);
1225   for (BinaryFile *F : BinaryFiles)
1226     for (InputSectionBase *S : F->getSections())
1227       InputSections.push_back(cast<InputSection>(S));
1228 
1229   // We do not want to emit debug sections if --strip-all
1230   // or -strip-debug are given.
1231   if (Config->Strip != StripPolicy::None)
1232     llvm::erase_if(InputSections, [](InputSectionBase *S) {
1233       return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1234     });
1235 
1236   Config->EFlags = Target->calcEFlags();
1237 
1238   if (Config->EMachine == EM_ARM) {
1239     // FIXME: These warnings can be removed when lld only uses these features
1240     // when the input objects have been compiled with an architecture that
1241     // supports them.
1242     if (Config->ARMHasBlx == false)
1243       warn("lld uses blx instruction, no object with architecture supporting "
1244            "feature detected.");
1245     if (Config->ARMJ1J2BranchEncoding == false)
1246       warn("lld uses extended branch encoding, no object with architecture "
1247            "supporting feature detected.");
1248     if (Config->ARMHasMovtMovw == false)
1249       warn("lld may use movt/movw, no object with architecture supporting "
1250            "feature detected.");
1251   }
1252 
1253   // This adds a .comment section containing a version string. We have to add it
1254   // before decompressAndMergeSections because the .comment section is a
1255   // mergeable section.
1256   if (!Config->Relocatable)
1257     InputSections.push_back(createCommentSection());
1258 
1259   // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1260   // and identical code folding.
1261   markLive<ELFT>();
1262   decompressSections();
1263   mergeSections();
1264   if (Config->ICF)
1265     doIcf<ELFT>();
1266 
1267   // Read the callgraph now that we know what was gced or icfed
1268   if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1269     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1270       readCallGraph(*Buffer);
1271 
1272   // Write the result to the file.
1273   writeResult<ELFT>();
1274 }
1275