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