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