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