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