xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 61329522)
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 "Strings.h"
37 #include "SymbolTable.h"
38 #include "Target.h"
39 #include "Threads.h"
40 #include "Writer.h"
41 #include "lld/Config/Version.h"
42 #include "lld/Driver/Driver.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/ADT/StringSwitch.h"
45 #include "llvm/Object/Decompressor.h"
46 #include "llvm/Support/CommandLine.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   Script = make<LinkerScript>();
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   // Handle -v or -version.
304   //
305   // A note about "compatible with GNU linkers" message: this is a hack for
306   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
307   // still the newest version in March 2017) or earlier to recognize LLD as
308   // a GNU compatible linker. As long as an output for the -v option
309   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
310   //
311   // This is somewhat ugly hack, but in reality, we had no choice other
312   // than doing this. Considering the very long release cycle of Libtool,
313   // it is not easy to improve it to recognize LLD as a GNU compatible
314   // linker in a timely manner. Even if we can make it, there are still a
315   // lot of "configure" scripts out there that are generated by old version
316   // of Libtool. We cannot convince every software developer to migrate to
317   // the latest version and re-generate scripts. So we have this hack.
318   if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
319     message(getLLDVersion() + " (compatible with GNU linkers)");
320 
321   // ld.bfd always exits after printing out the version string.
322   // ld.gold proceeds if a given option is -v. Because gold's behavior
323   // is more permissive than ld.bfd, we chose what gold does here.
324   if (Args.hasArg(OPT_version))
325     return;
326 
327   Config->ExitEarly = CanExitEarly && !Args.hasArg(OPT_full_shutdown);
328 
329   if (const char *Path = getReproduceOption(Args)) {
330     // Note that --reproduce is a debug option so you can ignore it
331     // if you are trying to understand the whole picture of the code.
332     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
333         TarWriter::create(Path, path::stem(Path));
334     if (ErrOrWriter) {
335       Tar = ErrOrWriter->get();
336       Tar->append("response.txt", createResponseFile(Args));
337       Tar->append("version.txt", getLLDVersion() + "\n");
338       make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
339     } else {
340       error(Twine("--reproduce: failed to open ") + Path + ": " +
341             toString(ErrOrWriter.takeError()));
342     }
343   }
344 
345   readConfigs(Args);
346   initLLVM(Args);
347   createFiles(Args);
348   inferMachineType();
349   setConfigs();
350   checkOptions(Args);
351   if (ErrorCount)
352     return;
353 
354   switch (Config->EKind) {
355   case ELF32LEKind:
356     link<ELF32LE>(Args);
357     return;
358   case ELF32BEKind:
359     link<ELF32BE>(Args);
360     return;
361   case ELF64LEKind:
362     link<ELF64LE>(Args);
363     return;
364   case ELF64BEKind:
365     link<ELF64BE>(Args);
366     return;
367   default:
368     llvm_unreachable("unknown Config->EKind");
369   }
370 }
371 
372 static bool getArg(opt::InputArgList &Args, unsigned K1, unsigned K2,
373                    bool Default) {
374   if (auto *Arg = Args.getLastArg(K1, K2))
375     return Arg->getOption().getID() == K1;
376   return Default;
377 }
378 
379 static std::vector<StringRef> getArgs(opt::InputArgList &Args, int Id) {
380   std::vector<StringRef> V;
381   for (auto *Arg : Args.filtered(Id))
382     V.push_back(Arg->getValue());
383   return V;
384 }
385 
386 static std::string getRPath(opt::InputArgList &Args) {
387   std::vector<StringRef> V = getArgs(Args, OPT_rpath);
388   return llvm::join(V.begin(), V.end(), ":");
389 }
390 
391 // Determines what we should do if there are remaining unresolved
392 // symbols after the name resolution.
393 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
394   // -noinhibit-exec or -r imply some default values.
395   if (Args.hasArg(OPT_noinhibit_exec))
396     return UnresolvedPolicy::WarnAll;
397   if (Args.hasArg(OPT_relocatable))
398     return UnresolvedPolicy::IgnoreAll;
399 
400   UnresolvedPolicy ErrorOrWarn = getArg(Args, OPT_error_unresolved_symbols,
401                                         OPT_warn_unresolved_symbols, true)
402                                      ? UnresolvedPolicy::ReportError
403                                      : UnresolvedPolicy::Warn;
404 
405   // Process the last of -unresolved-symbols, -no-undefined or -z defs.
406   for (auto *Arg : llvm::reverse(Args)) {
407     switch (Arg->getOption().getID()) {
408     case OPT_unresolved_symbols: {
409       StringRef S = Arg->getValue();
410       if (S == "ignore-all" || S == "ignore-in-object-files")
411         return UnresolvedPolicy::Ignore;
412       if (S == "ignore-in-shared-libs" || S == "report-all")
413         return ErrorOrWarn;
414       error("unknown --unresolved-symbols value: " + S);
415       continue;
416     }
417     case OPT_no_undefined:
418       return ErrorOrWarn;
419     case OPT_z:
420       if (StringRef(Arg->getValue()) == "defs")
421         return ErrorOrWarn;
422       continue;
423     }
424   }
425 
426   // -shared implies -unresolved-symbols=ignore-all because missing
427   // symbols are likely to be resolved at runtime using other DSOs.
428   if (Config->Shared)
429     return UnresolvedPolicy::Ignore;
430   return ErrorOrWarn;
431 }
432 
433 static Target2Policy getTarget2(opt::InputArgList &Args) {
434   if (auto *Arg = Args.getLastArg(OPT_target2)) {
435     StringRef S = Arg->getValue();
436     if (S == "rel")
437       return Target2Policy::Rel;
438     if (S == "abs")
439       return Target2Policy::Abs;
440     if (S == "got-rel")
441       return Target2Policy::GotRel;
442     error("unknown --target2 option: " + S);
443   }
444   return Target2Policy::GotRel;
445 }
446 
447 static bool isOutputFormatBinary(opt::InputArgList &Args) {
448   if (auto *Arg = Args.getLastArg(OPT_oformat)) {
449     StringRef S = Arg->getValue();
450     if (S == "binary")
451       return true;
452     error("unknown --oformat value: " + S);
453   }
454   return false;
455 }
456 
457 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
458   if (Args.hasArg(OPT_relocatable))
459     return DiscardPolicy::None;
460 
461   auto *Arg =
462       Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
463   if (!Arg)
464     return DiscardPolicy::Default;
465   if (Arg->getOption().getID() == OPT_discard_all)
466     return DiscardPolicy::All;
467   if (Arg->getOption().getID() == OPT_discard_locals)
468     return DiscardPolicy::Locals;
469   return DiscardPolicy::None;
470 }
471 
472 static StringRef getDynamicLinker(opt::InputArgList &Args) {
473   auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
474   if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
475     return "";
476   return Arg->getValue();
477 }
478 
479 static StripPolicy getStrip(opt::InputArgList &Args) {
480   if (Args.hasArg(OPT_relocatable))
481     return StripPolicy::None;
482 
483   auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
484   if (!Arg)
485     return StripPolicy::None;
486   if (Arg->getOption().getID() == OPT_strip_all)
487     return StripPolicy::All;
488   return StripPolicy::Debug;
489 }
490 
491 static uint64_t parseSectionAddress(StringRef S, opt::Arg *Arg) {
492   uint64_t VA = 0;
493   if (S.startswith("0x"))
494     S = S.drop_front(2);
495   if (S.getAsInteger(16, VA))
496     error("invalid argument: " + toString(Arg));
497   return VA;
498 }
499 
500 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
501   StringMap<uint64_t> Ret;
502   for (auto *Arg : Args.filtered(OPT_section_start)) {
503     StringRef Name;
504     StringRef Addr;
505     std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
506     Ret[Name] = parseSectionAddress(Addr, Arg);
507   }
508 
509   if (auto *Arg = Args.getLastArg(OPT_Ttext))
510     Ret[".text"] = parseSectionAddress(Arg->getValue(), Arg);
511   if (auto *Arg = Args.getLastArg(OPT_Tdata))
512     Ret[".data"] = parseSectionAddress(Arg->getValue(), Arg);
513   if (auto *Arg = Args.getLastArg(OPT_Tbss))
514     Ret[".bss"] = parseSectionAddress(Arg->getValue(), Arg);
515   return Ret;
516 }
517 
518 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
519   StringRef S = getString(Args, OPT_sort_section);
520   if (S == "alignment")
521     return SortSectionPolicy::Alignment;
522   if (S == "name")
523     return SortSectionPolicy::Name;
524   if (!S.empty())
525     error("unknown --sort-section rule: " + S);
526   return SortSectionPolicy::Default;
527 }
528 
529 static std::pair<bool, bool> getHashStyle(opt::InputArgList &Args) {
530   StringRef S = getString(Args, OPT_hash_style, "sysv");
531   if (S == "sysv")
532     return {true, false};
533   if (S == "gnu")
534     return {false, true};
535   if (S != "both")
536     error("unknown -hash-style: " + S);
537   return {true, true};
538 }
539 
540 static std::vector<StringRef> getLines(MemoryBufferRef MB) {
541   SmallVector<StringRef, 0> Arr;
542   MB.getBuffer().split(Arr, '\n');
543 
544   std::vector<StringRef> Ret;
545   for (StringRef S : Arr) {
546     S = S.trim();
547     if (!S.empty())
548       Ret.push_back(S);
549   }
550   return Ret;
551 }
552 
553 // Initializes Config members by the command line options.
554 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
555   Config->AllowMultipleDefinition = Args.hasArg(OPT_allow_multiple_definition);
556   Config->AuxiliaryList = getArgs(Args, OPT_auxiliary);
557   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
558   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
559   Config->DefineCommon = getArg(Args, OPT_define_common, OPT_no_define_common,
560                                 !Args.hasArg(OPT_relocatable));
561   Config->Demangle = getArg(Args, OPT_demangle, OPT_no_demangle, true);
562   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
563   Config->Discard = getDiscard(Args);
564   Config->DynamicLinker = getDynamicLinker(Args);
565   Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
566   Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
567   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
568   Config->Entry = getString(Args, OPT_entry);
569   Config->ExportDynamic =
570       getArg(Args, OPT_export_dynamic, OPT_no_export_dynamic, false);
571   Config->FatalWarnings =
572       getArg(Args, OPT_fatal_warnings, OPT_no_fatal_warnings, false);
573   Config->Fini = getString(Args, OPT_fini, "_fini");
574   Config->GcSections = getArg(Args, OPT_gc_sections, OPT_no_gc_sections, false);
575   Config->GdbIndex = Args.hasArg(OPT_gdb_index);
576   Config->ICF = Args.hasArg(OPT_icf);
577   Config->Init = getString(Args, OPT_init, "_init");
578   Config->LTOAAPipeline = getString(Args, OPT_lto_aa_pipeline);
579   Config->LTONewPmPasses = getString(Args, OPT_lto_newpm_passes);
580   Config->LTOO = getInteger(Args, OPT_lto_O, 2);
581   Config->LTOPartitions = getInteger(Args, OPT_lto_partitions, 1);
582   Config->MapFile = getString(Args, OPT_Map);
583   Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
584   Config->NoUndefinedVersion = Args.hasArg(OPT_no_undefined_version);
585   Config->Nostdlib = Args.hasArg(OPT_nostdlib);
586   Config->OFormatBinary = isOutputFormatBinary(Args);
587   Config->Omagic = Args.hasArg(OPT_omagic);
588   Config->OptRemarksFilename = getString(Args, OPT_opt_remarks_filename);
589   Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
590   Config->Optimize = getInteger(Args, OPT_O, 1);
591   Config->OutputFile = getString(Args, OPT_o);
592   Config->Pie = getArg(Args, OPT_pie, OPT_nopie, false);
593   Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
594   Config->RPath = getRPath(Args);
595   Config->Relocatable = Args.hasArg(OPT_relocatable);
596   Config->SaveTemps = Args.hasArg(OPT_save_temps);
597   Config->SearchPaths = getArgs(Args, OPT_L);
598   Config->SectionStartMap = getSectionStartMap(Args);
599   Config->Shared = Args.hasArg(OPT_shared);
600   Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
601   Config->SoName = getString(Args, OPT_soname);
602   Config->SortSection = getSortSection(Args);
603   Config->Strip = getStrip(Args);
604   Config->Sysroot = getString(Args, OPT_sysroot);
605   Config->Target1Rel = getArg(Args, OPT_target1_rel, OPT_target1_abs, false);
606   Config->Target2 = getTarget2(Args);
607   Config->ThinLTOCacheDir = getString(Args, OPT_thinlto_cache_dir);
608   Config->ThinLTOCachePolicy =
609       check(parseCachePruningPolicy(getString(Args, OPT_thinlto_cache_policy)),
610             "--thinlto-cache-policy: invalid cache policy");
611   Config->ThinLTOJobs = getInteger(Args, OPT_thinlto_jobs, -1u);
612   Config->Threads = getArg(Args, OPT_threads, OPT_no_threads, true);
613   Config->Trace = Args.hasArg(OPT_trace);
614   Config->Undefined = getArgs(Args, OPT_undefined);
615   Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
616   Config->Verbose = Args.hasArg(OPT_verbose);
617   Config->WarnCommon = Args.hasArg(OPT_warn_common);
618   Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
619   Config->ZExecstack = hasZOption(Args, "execstack");
620   Config->ZNocopyreloc = hasZOption(Args, "nocopyreloc");
621   Config->ZNodelete = hasZOption(Args, "nodelete");
622   Config->ZNodlopen = hasZOption(Args, "nodlopen");
623   Config->ZNow = hasZOption(Args, "now");
624   Config->ZOrigin = hasZOption(Args, "origin");
625   Config->ZRelro = !hasZOption(Args, "norelro");
626   Config->ZStackSize = getZOptionValue(Args, "stack-size", 0);
627   Config->ZText = !hasZOption(Args, "notext");
628   Config->ZWxneeded = hasZOption(Args, "wxneeded");
629 
630   if (Config->LTOO > 3)
631     error("invalid optimization level for LTO: " + getString(Args, OPT_lto_O));
632   if (Config->LTOPartitions == 0)
633     error("--lto-partitions: number of threads must be > 0");
634   if (Config->ThinLTOJobs == 0)
635     error("--thinlto-jobs: number of threads must be > 0");
636 
637   if (auto *Arg = Args.getLastArg(OPT_m)) {
638     // Parse ELF{32,64}{LE,BE} and CPU type.
639     StringRef S = Arg->getValue();
640     std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
641         parseEmulation(S);
642     Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
643     Config->Emulation = S;
644   }
645 
646   if (Args.hasArg(OPT_print_map))
647     Config->MapFile = "-";
648 
649   // --omagic is an option to create old-fashioned executables in which
650   // .text segments are writable. Today, the option is still in use to
651   // create special-purpose programs such as boot loaders. It doesn't
652   // make sense to create PT_GNU_RELRO for such executables.
653   if (Config->Omagic)
654     Config->ZRelro = false;
655 
656   std::tie(Config->SysvHash, Config->GnuHash) = getHashStyle(Args);
657 
658   // Parse --build-id or --build-id=<style>. We handle "tree" as a
659   // synonym for "sha1" because all of our hash functions including
660   // -build-id=sha1 are tree hashes for performance reasons.
661   if (Args.hasArg(OPT_build_id))
662     Config->BuildId = BuildIdKind::Fast;
663   if (auto *Arg = Args.getLastArg(OPT_build_id_eq)) {
664     StringRef S = Arg->getValue();
665     if (S == "md5") {
666       Config->BuildId = BuildIdKind::Md5;
667     } else if (S == "sha1" || S == "tree") {
668       Config->BuildId = BuildIdKind::Sha1;
669     } else if (S == "uuid") {
670       Config->BuildId = BuildIdKind::Uuid;
671     } else if (S == "none") {
672       Config->BuildId = BuildIdKind::None;
673     } else if (S.startswith("0x")) {
674       Config->BuildId = BuildIdKind::Hexstring;
675       Config->BuildIdVector = parseHex(S.substr(2));
676     } else {
677       error("unknown --build-id style: " + S);
678     }
679   }
680 
681   if (!Config->Shared && !Config->AuxiliaryList.empty())
682     error("-f may not be used without -shared");
683 
684   for (auto *Arg : Args.filtered(OPT_dynamic_list))
685     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
686       readDynamicList(*Buffer);
687 
688   if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
689     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
690       Config->SymbolOrderingFile = getLines(*Buffer);
691 
692   // If --retain-symbol-file is used, we'll keep only the symbols listed in
693   // the file and discard all others.
694   if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
695     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
696     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
697       for (StringRef S : getLines(*Buffer))
698         Config->VersionScriptGlobals.push_back(
699             {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
700   }
701 
702   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
703     Config->VersionScriptGlobals.push_back(
704         {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
705 
706   // Dynamic lists are a simplified linker script that doesn't need the
707   // "global:" and implicitly ends with a "local:*". Set the variables needed to
708   // simulate that.
709   if (Args.hasArg(OPT_dynamic_list) || Args.hasArg(OPT_export_dynamic_symbol)) {
710     Config->ExportDynamic = true;
711     if (!Config->Shared)
712       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
713   }
714 
715   if (auto *Arg = Args.getLastArg(OPT_version_script))
716     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
717       readVersionScript(*Buffer);
718 }
719 
720 // Some Config members do not directly correspond to any particular
721 // command line options, but computed based on other Config values.
722 // This function initialize such members. See Config.h for the details
723 // of these values.
724 static void setConfigs() {
725   ELFKind Kind = Config->EKind;
726   uint16_t Machine = Config->EMachine;
727 
728   // There is an ILP32 ABI for x86-64, although it's not very popular.
729   // It is called the x32 ABI.
730   bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64);
731 
732   Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
733   Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind);
734   Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind);
735   Config->Endianness =
736       Config->IsLE ? support::endianness::little : support::endianness::big;
737   Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS);
738   Config->IsRela = Config->Is64 || IsX32 || Config->MipsN32Abi;
739   Config->Pic = Config->Pie || Config->Shared;
740   Config->Wordsize = Config->Is64 ? 8 : 4;
741 }
742 
743 // Returns a value of "-format" option.
744 static bool getBinaryOption(StringRef S) {
745   if (S == "binary")
746     return true;
747   if (S == "elf" || S == "default")
748     return false;
749   error("unknown -format value: " + S +
750         " (supported formats: elf, default, binary)");
751   return false;
752 }
753 
754 void LinkerDriver::createFiles(opt::InputArgList &Args) {
755   for (auto *Arg : Args) {
756     switch (Arg->getOption().getID()) {
757     case OPT_l:
758       addLibrary(Arg->getValue());
759       break;
760     case OPT_INPUT:
761       addFile(Arg->getValue());
762       break;
763     case OPT_alias_script_T:
764     case OPT_script:
765       if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue()))
766         readLinkerScript(*MB);
767       break;
768     case OPT_as_needed:
769       Config->AsNeeded = true;
770       break;
771     case OPT_format:
772       InBinary = getBinaryOption(Arg->getValue());
773       break;
774     case OPT_no_as_needed:
775       Config->AsNeeded = false;
776       break;
777     case OPT_Bstatic:
778       Config->Static = true;
779       break;
780     case OPT_Bdynamic:
781       Config->Static = false;
782       break;
783     case OPT_whole_archive:
784       InWholeArchive = true;
785       break;
786     case OPT_no_whole_archive:
787       InWholeArchive = false;
788       break;
789     case OPT_start_lib:
790       InLib = true;
791       break;
792     case OPT_end_lib:
793       InLib = false;
794       break;
795     }
796   }
797 
798   if (Files.empty() && ErrorCount == 0)
799     error("no input files");
800 }
801 
802 // If -m <machine_type> was not given, infer it from object files.
803 void LinkerDriver::inferMachineType() {
804   if (Config->EKind != ELFNoneKind)
805     return;
806 
807   for (InputFile *F : Files) {
808     if (F->EKind == ELFNoneKind)
809       continue;
810     Config->EKind = F->EKind;
811     Config->EMachine = F->EMachine;
812     Config->OSABI = F->OSABI;
813     Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
814     return;
815   }
816   error("target emulation unknown: -m or at least one .o file required");
817 }
818 
819 // Parse -z max-page-size=<value>. The default value is defined by
820 // each target.
821 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
822   uint64_t Val =
823       getZOptionValue(Args, "max-page-size", Target->DefaultMaxPageSize);
824   if (!isPowerOf2_64(Val))
825     error("max-page-size: value isn't a power of 2");
826   return Val;
827 }
828 
829 // Parses -image-base option.
830 static uint64_t getImageBase(opt::InputArgList &Args) {
831   // Use default if no -image-base option is given.
832   // Because we are using "Target" here, this function
833   // has to be called after the variable is initialized.
834   auto *Arg = Args.getLastArg(OPT_image_base);
835   if (!Arg)
836     return Config->Pic ? 0 : Target->DefaultImageBase;
837 
838   StringRef S = Arg->getValue();
839   uint64_t V;
840   if (S.getAsInteger(0, V)) {
841     error("-image-base: number expected, but got " + S);
842     return 0;
843   }
844   if ((V % Config->MaxPageSize) != 0)
845     warn("-image-base: address isn't multiple of page size: " + S);
846   return V;
847 }
848 
849 // Do actual linking. Note that when this function is called,
850 // all linker scripts have already been parsed.
851 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
852   SymbolTable<ELFT> Symtab;
853   elf::Symtab<ELFT>::X = &Symtab;
854   Target = createTarget();
855 
856   Config->MaxPageSize = getMaxPageSize(Args);
857   Config->ImageBase = getImageBase(Args);
858 
859   // Default output filename is "a.out" by the Unix tradition.
860   if (Config->OutputFile.empty())
861     Config->OutputFile = "a.out";
862 
863   // Fail early if the output file is not writable. If a user has a long link,
864   // e.g. due to a large LTO link, they do not wish to run it and find that it
865   // failed because there was a mistake in their command-line.
866   if (!isFileWritable(Config->OutputFile))
867     return;
868 
869   // Use default entry point name if no name was given via the command
870   // line nor linker scripts. For some reason, MIPS entry point name is
871   // different from others.
872   Config->WarnMissingEntry =
873       (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
874   if (Config->Entry.empty() && !Config->Relocatable)
875     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
876 
877   // Handle --trace-symbol.
878   for (auto *Arg : Args.filtered(OPT_trace_symbol))
879     Symtab.trace(Arg->getValue());
880 
881   // Add all files to the symbol table. This will add almost all
882   // symbols that we need to the symbol table.
883   for (InputFile *F : Files)
884     Symtab.addFile(F);
885 
886   // If an entry symbol is in a static archive, pull out that file now
887   // to complete the symbol table. After this, no new names except a
888   // few linker-synthesized ones will be added to the symbol table.
889   if (Symtab.find(Config->Entry))
890     Symtab.addUndefined(Config->Entry);
891 
892   // Return if there were name resolution errors.
893   if (ErrorCount)
894     return;
895 
896   Symtab.scanUndefinedFlags();
897   Symtab.scanShlibUndefined();
898   Symtab.scanVersionScript();
899 
900   Symtab.addCombinedLTOObject();
901   if (ErrorCount)
902     return;
903 
904   // Some symbols (such as __ehdr_start) are defined lazily only when there
905   // are undefined symbols for them, so we add these to trigger that logic.
906   for (StringRef Sym : Script->Opt.UndefinedSymbols)
907     Symtab.addUndefined(Sym);
908 
909   for (auto *Arg : Args.filtered(OPT_wrap))
910     Symtab.wrap(Arg->getValue());
911 
912   // Now that we have a complete list of input files.
913   // Beyond this point, no new files are added.
914   // Aggregate all input sections into one place.
915   for (elf::ObjectFile<ELFT> *F : Symtab.getObjectFiles())
916     for (InputSectionBase *S : F->getSections())
917       if (S && S != &InputSection::Discarded)
918         InputSections.push_back(S);
919   for (BinaryFile *F : Symtab.getBinaryFiles())
920     for (InputSectionBase *S : F->getSections())
921       InputSections.push_back(cast<InputSection>(S));
922 
923   // Do size optimizations: garbage collection and identical code folding.
924   if (Config->GcSections)
925     markLive<ELFT>();
926   if (Config->ICF)
927     doIcf<ELFT>();
928 
929   // MergeInputSection::splitIntoPieces needs to be called before
930   // any call of MergeInputSection::getOffset. Do that.
931   parallelForEach(InputSections.begin(), InputSections.end(),
932                   [](InputSectionBase *S) {
933                     if (!S->Live)
934                       return;
935                     if (Decompressor::isCompressedELFSection(S->Flags, S->Name))
936                       S->uncompress();
937                     if (auto *MS = dyn_cast<MergeInputSection>(S))
938                       MS->splitIntoPieces();
939                   });
940 
941   // Write the result to the file.
942   writeResult<ELFT>();
943 }
944