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