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