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