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