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