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