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