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