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