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