xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 867e36de)
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 // The driver drives the entire linking process. It is responsible for
11 // parsing command line options and doing whatever it is instructed to do.
12 //
13 // One notable thing in the LLD's driver when compared to other linkers is
14 // that the LLD's driver is agnostic on the host operating system.
15 // Other linkers usually have implicit default values (such as a dynamic
16 // linker path or library paths) for each host OS.
17 //
18 // I don't think implicit default values are useful because they are
19 // usually explicitly specified by the compiler driver. They can even
20 // be harmful when you are doing cross-linking. Therefore, in LLD, we
21 // simply trust the compiler driver to pass all required options and
22 // don't try to make effort on our side.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "Driver.h"
27 #include "Config.h"
28 #include "Error.h"
29 #include "Filesystem.h"
30 #include "ICF.h"
31 #include "InputFiles.h"
32 #include "InputSection.h"
33 #include "LinkerScript.h"
34 #include "Memory.h"
35 #include "OutputSections.h"
36 #include "ScriptParser.h"
37 #include "Strings.h"
38 #include "SymbolTable.h"
39 #include "SyntheticSections.h"
40 #include "Target.h"
41 #include "Threads.h"
42 #include "Writer.h"
43 #include "lld/Config/Version.h"
44 #include "lld/Driver/Driver.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/StringSwitch.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Compression.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/TarWriter.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <cstdlib>
54 #include <utility>
55 
56 using namespace llvm;
57 using namespace llvm::ELF;
58 using namespace llvm::object;
59 using namespace llvm::sys;
60 
61 using namespace lld;
62 using namespace lld::elf;
63 
64 Configuration *elf::Config;
65 LinkerDriver *elf::Driver;
66 
67 BumpPtrAllocator elf::BAlloc;
68 StringSaver elf::Saver{BAlloc};
69 std::vector<SpecificAllocBase *> elf::SpecificAllocBase::Instances;
70 
71 static void setConfigs();
72 
73 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
74                raw_ostream &Error) {
75   ErrorCount = 0;
76   ErrorOS = &Error;
77   InputSections.clear();
78   Tar = nullptr;
79 
80   Config = make<Configuration>();
81   Driver = make<LinkerDriver>();
82   Script = make<LinkerScript>();
83   Symtab = make<SymbolTable>();
84   Config->Argv = {Args.begin(), Args.end()};
85 
86   Driver->main(Args, CanExitEarly);
87   freeArena();
88   return !ErrorCount;
89 }
90 
91 // Parses a linker -m option.
92 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
93   uint8_t OSABI = 0;
94   StringRef S = Emul;
95   if (S.endswith("_fbsd")) {
96     S = S.drop_back(5);
97     OSABI = ELFOSABI_FREEBSD;
98   }
99 
100   std::pair<ELFKind, uint16_t> Ret =
101       StringSwitch<std::pair<ELFKind, uint16_t>>(S)
102           .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
103           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
104           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
105           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
106           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
107           .Case("elf32ppc", {ELF32BEKind, EM_PPC})
108           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
109           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
110           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
111           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
112           .Case("elf_i386", {ELF32LEKind, EM_386})
113           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
114           .Default({ELFNoneKind, EM_NONE});
115 
116   if (Ret.first == ELFNoneKind) {
117     if (S == "i386pe" || S == "i386pep" || S == "thumb2pe")
118       error("Windows targets are not supported on the ELF frontend: " + Emul);
119     else
120       error("unknown emulation: " + Emul);
121   }
122   return std::make_tuple(Ret.first, Ret.second, OSABI);
123 }
124 
125 // Returns slices of MB by parsing MB as an archive file.
126 // Each slice consists of a member file in the archive.
127 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
128     MemoryBufferRef MB) {
129   std::unique_ptr<Archive> File =
130       check(Archive::create(MB),
131             MB.getBufferIdentifier() + ": failed to parse archive");
132 
133   std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
134   Error Err = Error::success();
135   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
136     Archive::Child C =
137         check(COrErr, MB.getBufferIdentifier() +
138                           ": could not get the child of the archive");
139     MemoryBufferRef MBRef =
140         check(C.getMemoryBufferRef(),
141               MB.getBufferIdentifier() +
142                   ": could not get the buffer for a child of the archive");
143     V.push_back(std::make_pair(MBRef, C.getChildOffset()));
144   }
145   if (Err)
146     fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
147           toString(std::move(Err)));
148 
149   // Take ownership of memory buffers created for members of thin archives.
150   for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
151     make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
152 
153   return V;
154 }
155 
156 // Opens a file and create a file object. Path has to be resolved already.
157 void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
158   using namespace sys::fs;
159 
160   Optional<MemoryBufferRef> Buffer = readFile(Path);
161   if (!Buffer.hasValue())
162     return;
163   MemoryBufferRef MBRef = *Buffer;
164 
165   if (InBinary) {
166     Files.push_back(make<BinaryFile>(MBRef));
167     return;
168   }
169 
170   switch (identify_magic(MBRef.getBuffer())) {
171   case file_magic::unknown:
172     readLinkerScript(MBRef);
173     return;
174   case file_magic::archive: {
175     // Handle -whole-archive.
176     if (InWholeArchive) {
177       for (const auto &P : getArchiveMembers(MBRef))
178         Files.push_back(createObjectFile(P.first, Path, P.second));
179       return;
180     }
181 
182     std::unique_ptr<Archive> File =
183         check(Archive::create(MBRef), Path + ": failed to parse archive");
184 
185     // If an archive file has no symbol table, it is likely that a user
186     // is attempting LTO and using a default ar command that doesn't
187     // understand the LLVM bitcode file. It is a pretty common error, so
188     // we'll handle it as if it had a symbol table.
189     if (!File->isEmpty() && !File->hasSymbolTable()) {
190       for (const auto &P : getArchiveMembers(MBRef))
191         Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
192       return;
193     }
194 
195     // Handle the regular case.
196     Files.push_back(make<ArchiveFile>(std::move(File)));
197     return;
198   }
199   case file_magic::elf_shared_object:
200     if (Config->Relocatable) {
201       error("attempted static link of dynamic object " + Path);
202       return;
203     }
204 
205     // DSOs usually have DT_SONAME tags in their ELF headers, and the
206     // sonames are used to identify DSOs. But if they are missing,
207     // they are identified by filenames. We don't know whether the new
208     // file has a DT_SONAME or not because we haven't parsed it yet.
209     // Here, we set the default soname for the file because we might
210     // need it later.
211     //
212     // If a file was specified by -lfoo, the directory part is not
213     // significant, as a user did not specify it. This behavior is
214     // compatible with GNU.
215     Files.push_back(
216         createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path));
217     return;
218   default:
219     if (InLib)
220       Files.push_back(make<LazyObjFile>(MBRef, "", 0));
221     else
222       Files.push_back(createObjectFile(MBRef));
223   }
224 }
225 
226 // Add a given library by searching it from input search paths.
227 void LinkerDriver::addLibrary(StringRef Name) {
228   if (Optional<std::string> Path = searchLibrary(Name))
229     addFile(*Path, /*WithLOption=*/true);
230   else
231     error("unable to find library -l" + Name);
232 }
233 
234 // This function is called on startup. We need this for LTO since
235 // LTO calls LLVM functions to compile bitcode files to native code.
236 // Technically this can be delayed until we read bitcode files, but
237 // we don't bother to do lazily because the initialization is fast.
238 static void initLLVM(opt::InputArgList &Args) {
239   InitializeAllTargets();
240   InitializeAllTargetMCs();
241   InitializeAllAsmPrinters();
242   InitializeAllAsmParsers();
243 
244   // Parse and evaluate -mllvm options.
245   std::vector<const char *> V;
246   V.push_back("lld (LLVM option parsing)");
247   for (auto *Arg : Args.filtered(OPT_mllvm))
248     V.push_back(Arg->getValue());
249   cl::ParseCommandLineOptions(V.size(), V.data());
250 }
251 
252 // Some command line options or some combinations of them are not allowed.
253 // This function checks for such errors.
254 static void checkOptions(opt::InputArgList &Args) {
255   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
256   // table which is a relatively new feature.
257   if (Config->EMachine == EM_MIPS && Config->GnuHash)
258     error("the .gnu.hash section is not compatible with the MIPS target.");
259 
260   if (Config->Pie && Config->Shared)
261     error("-shared and -pie may not be used together");
262 
263   if (!Config->Shared && !Config->FilterList.empty())
264     error("-F may not be used without -shared");
265 
266   if (!Config->Shared && !Config->AuxiliaryList.empty())
267     error("-f may not be used without -shared");
268 
269   if (Config->Relocatable) {
270     if (Config->Shared)
271       error("-r and -shared may not be used together");
272     if (Config->GcSections)
273       error("-r and --gc-sections may not be used together");
274     if (Config->ICF)
275       error("-r and --icf may not be used together");
276     if (Config->Pie)
277       error("-r and -pie may not be used together");
278   }
279 }
280 
281 static int getInteger(opt::InputArgList &Args, unsigned Key, int Default) {
282   int V = Default;
283   if (auto *Arg = Args.getLastArg(Key)) {
284     StringRef S = Arg->getValue();
285     if (!to_integer(S, V, 10))
286       error(Arg->getSpelling() + ": number expected, but got '" + S + "'");
287   }
288   return V;
289 }
290 
291 static const char *getReproduceOption(opt::InputArgList &Args) {
292   if (auto *Arg = Args.getLastArg(OPT_reproduce))
293     return Arg->getValue();
294   return getenv("LLD_REPRODUCE");
295 }
296 
297 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
298   for (auto *Arg : Args.filtered(OPT_z))
299     if (Key == Arg->getValue())
300       return true;
301   return false;
302 }
303 
304 static uint64_t getZOptionValue(opt::InputArgList &Args, StringRef Key,
305                                 uint64_t Default) {
306   for (auto *Arg : Args.filtered(OPT_z)) {
307     std::pair<StringRef, StringRef> KV = StringRef(Arg->getValue()).split('=');
308     if (KV.first == Key) {
309       uint64_t Result = Default;
310       if (!to_integer(KV.second, Result))
311         error("invalid " + Key + ": " + KV.second);
312       return Result;
313     }
314   }
315   return Default;
316 }
317 
318 void LinkerDriver::main(ArrayRef<const char *> ArgsArr, bool CanExitEarly) {
319   ELFOptTable Parser;
320   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
321 
322   // Interpret this flag early because error() depends on them.
323   Config->ErrorLimit = getInteger(Args, OPT_error_limit, 20);
324 
325   // Handle -help
326   if (Args.hasArg(OPT_help)) {
327     printHelp(ArgsArr[0]);
328     return;
329   }
330 
331   // Handle -v or -version.
332   //
333   // A note about "compatible with GNU linkers" message: this is a hack for
334   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
335   // still the newest version in March 2017) or earlier to recognize LLD as
336   // a GNU compatible linker. As long as an output for the -v option
337   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
338   //
339   // This is somewhat ugly hack, but in reality, we had no choice other
340   // than doing this. Considering the very long release cycle of Libtool,
341   // it is not easy to improve it to recognize LLD as a GNU compatible
342   // linker in a timely manner. Even if we can make it, there are still a
343   // lot of "configure" scripts out there that are generated by old version
344   // of Libtool. We cannot convince every software developer to migrate to
345   // the latest version and re-generate scripts. So we have this hack.
346   if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
347     message(getLLDVersion() + " (compatible with GNU linkers)");
348 
349   // ld.bfd always exits after printing out the version string.
350   // ld.gold proceeds if a given option is -v. Because gold's behavior
351   // is more permissive than ld.bfd, we chose what gold does here.
352   if (Args.hasArg(OPT_version))
353     return;
354 
355   Config->ExitEarly = CanExitEarly && !Args.hasArg(OPT_full_shutdown);
356 
357   if (const char *Path = getReproduceOption(Args)) {
358     // Note that --reproduce is a debug option so you can ignore it
359     // if you are trying to understand the whole picture of the code.
360     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
361         TarWriter::create(Path, path::stem(Path));
362     if (ErrOrWriter) {
363       Tar = ErrOrWriter->get();
364       Tar->append("response.txt", createResponseFile(Args));
365       Tar->append("version.txt", getLLDVersion() + "\n");
366       make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
367     } else {
368       error(Twine("--reproduce: failed to open ") + Path + ": " +
369             toString(ErrOrWriter.takeError()));
370     }
371   }
372 
373   readConfigs(Args);
374   initLLVM(Args);
375   createFiles(Args);
376   inferMachineType();
377   setConfigs();
378   checkOptions(Args);
379   if (ErrorCount)
380     return;
381 
382   switch (Config->EKind) {
383   case ELF32LEKind:
384     link<ELF32LE>(Args);
385     return;
386   case ELF32BEKind:
387     link<ELF32BE>(Args);
388     return;
389   case ELF64LEKind:
390     link<ELF64LE>(Args);
391     return;
392   case ELF64BEKind:
393     link<ELF64BE>(Args);
394     return;
395   default:
396     llvm_unreachable("unknown Config->EKind");
397   }
398 }
399 
400 static bool getArg(opt::InputArgList &Args, unsigned K1, unsigned K2,
401                    bool Default) {
402   if (auto *Arg = Args.getLastArg(K1, K2))
403     return Arg->getOption().getID() == K1;
404   return Default;
405 }
406 
407 static std::vector<StringRef> getArgs(opt::InputArgList &Args, int Id) {
408   std::vector<StringRef> V;
409   for (auto *Arg : Args.filtered(Id))
410     V.push_back(Arg->getValue());
411   return V;
412 }
413 
414 static std::string getRpath(opt::InputArgList &Args) {
415   std::vector<StringRef> V = getArgs(Args, OPT_rpath);
416   return llvm::join(V.begin(), V.end(), ":");
417 }
418 
419 // Determines what we should do if there are remaining unresolved
420 // symbols after the name resolution.
421 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
422   if (Args.hasArg(OPT_relocatable))
423     return UnresolvedPolicy::IgnoreAll;
424 
425   UnresolvedPolicy ErrorOrWarn = getArg(Args, OPT_error_unresolved_symbols,
426                                         OPT_warn_unresolved_symbols, true)
427                                      ? UnresolvedPolicy::ReportError
428                                      : UnresolvedPolicy::Warn;
429 
430   // Process the last of -unresolved-symbols, -no-undefined or -z defs.
431   for (auto *Arg : llvm::reverse(Args)) {
432     switch (Arg->getOption().getID()) {
433     case OPT_unresolved_symbols: {
434       StringRef S = Arg->getValue();
435       if (S == "ignore-all" || S == "ignore-in-object-files")
436         return UnresolvedPolicy::Ignore;
437       if (S == "ignore-in-shared-libs" || S == "report-all")
438         return ErrorOrWarn;
439       error("unknown --unresolved-symbols value: " + S);
440       continue;
441     }
442     case OPT_no_undefined:
443       return ErrorOrWarn;
444     case OPT_z:
445       if (StringRef(Arg->getValue()) == "defs")
446         return ErrorOrWarn;
447       continue;
448     }
449   }
450 
451   // -shared implies -unresolved-symbols=ignore-all because missing
452   // symbols are likely to be resolved at runtime using other DSOs.
453   if (Config->Shared)
454     return UnresolvedPolicy::Ignore;
455   return ErrorOrWarn;
456 }
457 
458 static Target2Policy getTarget2(opt::InputArgList &Args) {
459   StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
460   if (S == "rel")
461     return Target2Policy::Rel;
462   if (S == "abs")
463     return Target2Policy::Abs;
464   if (S == "got-rel")
465     return Target2Policy::GotRel;
466   error("unknown --target2 option: " + S);
467   return Target2Policy::GotRel;
468 }
469 
470 static bool isOutputFormatBinary(opt::InputArgList &Args) {
471   if (auto *Arg = Args.getLastArg(OPT_oformat)) {
472     StringRef S = Arg->getValue();
473     if (S == "binary")
474       return true;
475     error("unknown --oformat value: " + S);
476   }
477   return false;
478 }
479 
480 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
481   if (Args.hasArg(OPT_relocatable))
482     return DiscardPolicy::None;
483 
484   auto *Arg =
485       Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
486   if (!Arg)
487     return DiscardPolicy::Default;
488   if (Arg->getOption().getID() == OPT_discard_all)
489     return DiscardPolicy::All;
490   if (Arg->getOption().getID() == OPT_discard_locals)
491     return DiscardPolicy::Locals;
492   return DiscardPolicy::None;
493 }
494 
495 static StringRef getDynamicLinker(opt::InputArgList &Args) {
496   auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
497   if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
498     return "";
499   return Arg->getValue();
500 }
501 
502 static StripPolicy getStrip(opt::InputArgList &Args) {
503   if (Args.hasArg(OPT_relocatable))
504     return StripPolicy::None;
505 
506   auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
507   if (!Arg)
508     return StripPolicy::None;
509   if (Arg->getOption().getID() == OPT_strip_all)
510     return StripPolicy::All;
511   return StripPolicy::Debug;
512 }
513 
514 static uint64_t parseSectionAddress(StringRef S, opt::Arg *Arg) {
515   uint64_t VA = 0;
516   if (S.startswith("0x"))
517     S = S.drop_front(2);
518   if (!to_integer(S, VA, 16))
519     error("invalid argument: " + toString(Arg));
520   return VA;
521 }
522 
523 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
524   StringMap<uint64_t> Ret;
525   for (auto *Arg : Args.filtered(OPT_section_start)) {
526     StringRef Name;
527     StringRef Addr;
528     std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
529     Ret[Name] = parseSectionAddress(Addr, Arg);
530   }
531 
532   if (auto *Arg = Args.getLastArg(OPT_Ttext))
533     Ret[".text"] = parseSectionAddress(Arg->getValue(), Arg);
534   if (auto *Arg = Args.getLastArg(OPT_Tdata))
535     Ret[".data"] = parseSectionAddress(Arg->getValue(), Arg);
536   if (auto *Arg = Args.getLastArg(OPT_Tbss))
537     Ret[".bss"] = parseSectionAddress(Arg->getValue(), Arg);
538   return Ret;
539 }
540 
541 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
542   StringRef S = Args.getLastArgValue(OPT_sort_section);
543   if (S == "alignment")
544     return SortSectionPolicy::Alignment;
545   if (S == "name")
546     return SortSectionPolicy::Name;
547   if (!S.empty())
548     error("unknown --sort-section rule: " + S);
549   return SortSectionPolicy::Default;
550 }
551 
552 static std::pair<bool, bool> getHashStyle(opt::InputArgList &Args) {
553   StringRef S = Args.getLastArgValue(OPT_hash_style, "sysv");
554   if (S == "sysv")
555     return {true, false};
556   if (S == "gnu")
557     return {false, true};
558   if (S != "both")
559     error("unknown -hash-style: " + S);
560   return {true, true};
561 }
562 
563 // Parse --build-id or --build-id=<style>. We handle "tree" as a
564 // synonym for "sha1" because all our hash functions including
565 // -build-id=sha1 are actually tree hashes for performance reasons.
566 static std::pair<BuildIdKind, std::vector<uint8_t>>
567 getBuildId(opt::InputArgList &Args) {
568   auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
569   if (!Arg)
570     return {BuildIdKind::None, {}};
571 
572   if (Arg->getOption().getID() == OPT_build_id)
573     return {BuildIdKind::Fast, {}};
574 
575   StringRef S = Arg->getValue();
576   if (S == "md5")
577     return {BuildIdKind::Md5, {}};
578   if (S == "sha1" || S == "tree")
579     return {BuildIdKind::Sha1, {}};
580   if (S == "uuid")
581     return {BuildIdKind::Uuid, {}};
582   if (S.startswith("0x"))
583     return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
584 
585   if (S != "none")
586     error("unknown --build-id style: " + S);
587   return {BuildIdKind::None, {}};
588 }
589 
590 static std::vector<StringRef> getLines(MemoryBufferRef MB) {
591   SmallVector<StringRef, 0> Arr;
592   MB.getBuffer().split(Arr, '\n');
593 
594   std::vector<StringRef> Ret;
595   for (StringRef S : Arr) {
596     S = S.trim();
597     if (!S.empty())
598       Ret.push_back(S);
599   }
600   return Ret;
601 }
602 
603 static bool getCompressDebugSections(opt::InputArgList &Args) {
604   StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
605   if (S == "none")
606     return false;
607   if (S != "zlib")
608     error("unknown --compress-debug-sections value: " + S);
609   if (!zlib::isAvailable())
610     error("--compress-debug-sections: zlib is not available");
611   return true;
612 }
613 
614 static int parseInt(StringRef S, opt::Arg *Arg) {
615   int V = 0;
616   if (!to_integer(S, V, 10))
617     error(Arg->getSpelling() + ": number expected, but got '" + S + "'");
618   return V;
619 }
620 
621 // Initializes Config members by the command line options.
622 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
623   Config->AllowMultipleDefinition =
624       Args.hasArg(OPT_allow_multiple_definition) || hasZOption(Args, "muldefs");
625   Config->AuxiliaryList = getArgs(Args, OPT_auxiliary);
626   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
627   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
628   Config->Chroot = Args.getLastArgValue(OPT_chroot);
629   Config->CompressDebugSections = getCompressDebugSections(Args);
630   Config->DefineCommon = getArg(Args, OPT_define_common, OPT_no_define_common,
631                                 !Args.hasArg(OPT_relocatable));
632   Config->Demangle = getArg(Args, OPT_demangle, OPT_no_demangle, true);
633   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
634   Config->Discard = getDiscard(Args);
635   Config->DynamicLinker = getDynamicLinker(Args);
636   Config->EhFrameHdr = Args.hasArg(OPT_eh_frame_hdr);
637   Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
638   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
639   Config->Entry = Args.getLastArgValue(OPT_entry);
640   Config->ExportDynamic =
641       getArg(Args, OPT_export_dynamic, OPT_no_export_dynamic, false);
642   Config->FatalWarnings =
643       getArg(Args, OPT_fatal_warnings, OPT_no_fatal_warnings, false);
644   Config->FilterList = getArgs(Args, OPT_filter);
645   Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
646   Config->GcSections = getArg(Args, OPT_gc_sections, OPT_no_gc_sections, false);
647   Config->GdbIndex = Args.hasArg(OPT_gdb_index);
648   Config->ICF = getArg(Args, OPT_icf_all, OPT_icf_none, false);
649   Config->Init = Args.getLastArgValue(OPT_init, "_init");
650   Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
651   Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
652   Config->LTOO = getInteger(Args, OPT_lto_O, 2);
653   Config->LTOPartitions = getInteger(Args, OPT_lto_partitions, 1);
654   Config->MapFile = Args.getLastArgValue(OPT_Map);
655   Config->NoGnuUnique = Args.hasArg(OPT_no_gnu_unique);
656   Config->NoUndefinedVersion = Args.hasArg(OPT_no_undefined_version);
657   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
658   Config->Nostdlib = Args.hasArg(OPT_nostdlib);
659   Config->OFormatBinary = isOutputFormatBinary(Args);
660   Config->Omagic = Args.hasArg(OPT_omagic);
661   Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
662   Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
663   Config->Optimize = getInteger(Args, OPT_O, 1);
664   Config->OutputFile = Args.getLastArgValue(OPT_o);
665   Config->Pie = getArg(Args, OPT_pie, OPT_nopie, false);
666   Config->PrintGcSections = Args.hasArg(OPT_print_gc_sections);
667   Config->Rpath = getRpath(Args);
668   Config->Relocatable = Args.hasArg(OPT_relocatable);
669   Config->SaveTemps = Args.hasArg(OPT_save_temps);
670   Config->SearchPaths = getArgs(Args, OPT_library_path);
671   Config->SectionStartMap = getSectionStartMap(Args);
672   Config->Shared = Args.hasArg(OPT_shared);
673   Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
674   Config->SoName = Args.getLastArgValue(OPT_soname);
675   Config->SortSection = getSortSection(Args);
676   Config->Strip = getStrip(Args);
677   Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
678   Config->Target1Rel = getArg(Args, OPT_target1_rel, OPT_target1_abs, false);
679   Config->Target2 = getTarget2(Args);
680   Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
681   Config->ThinLTOCachePolicy = check(
682       parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
683       "--thinlto-cache-policy: invalid cache policy");
684   Config->ThinLTOJobs = getInteger(Args, OPT_thinlto_jobs, -1u);
685   Config->Threads = getArg(Args, OPT_threads, OPT_no_threads, true);
686   Config->Trace = Args.hasArg(OPT_trace);
687   Config->Undefined = getArgs(Args, OPT_undefined);
688   Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
689   Config->Verbose = Args.hasArg(OPT_verbose);
690   Config->WarnCommon = Args.hasArg(OPT_warn_common);
691   Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
692   Config->ZExecstack = hasZOption(Args, "execstack");
693   Config->ZNocopyreloc = hasZOption(Args, "nocopyreloc");
694   Config->ZNodelete = hasZOption(Args, "nodelete");
695   Config->ZNodlopen = hasZOption(Args, "nodlopen");
696   Config->ZNow = hasZOption(Args, "now");
697   Config->ZOrigin = hasZOption(Args, "origin");
698   Config->ZRelro = !hasZOption(Args, "norelro");
699   Config->ZRodynamic = hasZOption(Args, "rodynamic");
700   Config->ZStackSize = getZOptionValue(Args, "stack-size", 0);
701   Config->ZText = !hasZOption(Args, "notext");
702   Config->ZWxneeded = hasZOption(Args, "wxneeded");
703 
704   // Parse LTO plugin-related options for compatibility with gold.
705   for (auto *Arg : Args.filtered(OPT_plugin_opt, OPT_plugin_opt_eq)) {
706     StringRef S = Arg->getValue();
707     if (S == "disable-verify")
708       Config->DisableVerify = true;
709     else if (S == "save-temps")
710       Config->SaveTemps = true;
711     else if (S.startswith("O"))
712       Config->LTOO = parseInt(S.substr(1), Arg);
713     else if (S.startswith("lto-partitions="))
714       Config->LTOPartitions = parseInt(S.substr(15), Arg);
715     else if (S.startswith("jobs="))
716       Config->ThinLTOJobs = parseInt(S.substr(5), Arg);
717     else if (!S.startswith("/") && !S.startswith("-fresolution=") &&
718              !S.startswith("-pass-through=") && !S.startswith("mcpu=") &&
719              !S.startswith("thinlto") && S != "-function-sections" &&
720              S != "-data-sections")
721       error(Arg->getSpelling() + ": unknown option: " + S);
722   }
723 
724   if (Config->LTOO > 3)
725     error("invalid optimization level for LTO: " + Twine(Config->LTOO));
726   if (Config->LTOPartitions == 0)
727     error("--lto-partitions: number of threads must be > 0");
728   if (Config->ThinLTOJobs == 0)
729     error("--thinlto-jobs: number of threads must be > 0");
730 
731   // Parse ELF{32,64}{LE,BE} and CPU type.
732   if (auto *Arg = Args.getLastArg(OPT_m)) {
733     StringRef S = Arg->getValue();
734     std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
735         parseEmulation(S);
736     Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
737     Config->Emulation = S;
738   }
739 
740   if (Args.hasArg(OPT_print_map))
741     Config->MapFile = "-";
742 
743   // --omagic is an option to create old-fashioned executables in which
744   // .text segments are writable. Today, the option is still in use to
745   // create special-purpose programs such as boot loaders. It doesn't
746   // make sense to create PT_GNU_RELRO for such executables.
747   if (Config->Omagic)
748     Config->ZRelro = false;
749 
750   std::tie(Config->SysvHash, Config->GnuHash) = getHashStyle(Args);
751   std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
752 
753   if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
754     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
755       Config->SymbolOrderingFile = getLines(*Buffer);
756 
757   // If --retain-symbol-file is used, we'll keep only the symbols listed in
758   // the file and discard all others.
759   if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
760     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
761     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
762       for (StringRef S : getLines(*Buffer))
763         Config->VersionScriptGlobals.push_back(
764             {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
765   }
766 
767   bool HasExportDynamic =
768       getArg(Args, OPT_export_dynamic, OPT_no_export_dynamic, false);
769 
770   // Parses -dynamic-list and -export-dynamic-symbol. They make some
771   // symbols private. Note that -export-dynamic takes precedence over them
772   // as it says all symbols should be exported.
773   if (!HasExportDynamic) {
774     for (auto *Arg : Args.filtered(OPT_dynamic_list))
775       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
776         readDynamicList(*Buffer);
777 
778     for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
779       Config->VersionScriptGlobals.push_back(
780           {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
781 
782     // Dynamic lists are a simplified linker script that doesn't need the
783     // "global:" and implicitly ends with a "local:*". Set the variables
784     // needed to simulate that.
785     if (Args.hasArg(OPT_dynamic_list) ||
786         Args.hasArg(OPT_export_dynamic_symbol)) {
787       Config->ExportDynamic = true;
788       if (!Config->Shared)
789         Config->DefaultSymbolVersion = VER_NDX_LOCAL;
790     }
791   }
792 
793   if (auto *Arg = Args.getLastArg(OPT_version_script))
794     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
795       readVersionScript(*Buffer);
796 }
797 
798 // Some Config members do not directly correspond to any particular
799 // command line options, but computed based on other Config values.
800 // This function initialize such members. See Config.h for the details
801 // of these values.
802 static void setConfigs() {
803   ELFKind Kind = Config->EKind;
804   uint16_t Machine = Config->EMachine;
805 
806   // There is an ILP32 ABI for x86-64, although it's not very popular.
807   // It is called the x32 ABI.
808   bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64);
809 
810   Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
811   Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind);
812   Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind);
813   Config->Endianness =
814       Config->IsLE ? support::endianness::little : support::endianness::big;
815   Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS);
816   Config->IsRela = Config->Is64 || IsX32 || Config->MipsN32Abi;
817   Config->Pic = Config->Pie || Config->Shared;
818   Config->Wordsize = Config->Is64 ? 8 : 4;
819 }
820 
821 // Returns a value of "-format" option.
822 static bool getBinaryOption(StringRef S) {
823   if (S == "binary")
824     return true;
825   if (S == "elf" || S == "default")
826     return false;
827   error("unknown -format value: " + S +
828         " (supported formats: elf, default, binary)");
829   return false;
830 }
831 
832 void LinkerDriver::createFiles(opt::InputArgList &Args) {
833   for (auto *Arg : Args) {
834     switch (Arg->getOption().getUnaliasedOption().getID()) {
835     case OPT_library:
836       addLibrary(Arg->getValue());
837       break;
838     case OPT_INPUT:
839       addFile(Arg->getValue(), /*WithLOption=*/false);
840       break;
841     case OPT_script:
842       if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue()))
843         readLinkerScript(*MB);
844       break;
845     case OPT_as_needed:
846       Config->AsNeeded = true;
847       break;
848     case OPT_format:
849       InBinary = getBinaryOption(Arg->getValue());
850       break;
851     case OPT_no_as_needed:
852       Config->AsNeeded = false;
853       break;
854     case OPT_Bstatic:
855       Config->Static = true;
856       break;
857     case OPT_Bdynamic:
858       Config->Static = false;
859       break;
860     case OPT_whole_archive:
861       InWholeArchive = true;
862       break;
863     case OPT_no_whole_archive:
864       InWholeArchive = false;
865       break;
866     case OPT_start_lib:
867       InLib = true;
868       break;
869     case OPT_end_lib:
870       InLib = false;
871       break;
872     }
873   }
874 
875   if (Files.empty() && ErrorCount == 0)
876     error("no input files");
877 }
878 
879 // If -m <machine_type> was not given, infer it from object files.
880 void LinkerDriver::inferMachineType() {
881   if (Config->EKind != ELFNoneKind)
882     return;
883 
884   for (InputFile *F : Files) {
885     if (F->EKind == ELFNoneKind)
886       continue;
887     Config->EKind = F->EKind;
888     Config->EMachine = F->EMachine;
889     Config->OSABI = F->OSABI;
890     Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
891     return;
892   }
893   error("target emulation unknown: -m or at least one .o file required");
894 }
895 
896 // Parse -z max-page-size=<value>. The default value is defined by
897 // each target.
898 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
899   uint64_t Val =
900       getZOptionValue(Args, "max-page-size", Target->DefaultMaxPageSize);
901   if (!isPowerOf2_64(Val))
902     error("max-page-size: value isn't a power of 2");
903   return Val;
904 }
905 
906 // Parses -image-base option.
907 static uint64_t getImageBase(opt::InputArgList &Args) {
908   // Use default if no -image-base option is given.
909   // Because we are using "Target" here, this function
910   // has to be called after the variable is initialized.
911   auto *Arg = Args.getLastArg(OPT_image_base);
912   if (!Arg)
913     return Config->Pic ? 0 : Target->DefaultImageBase;
914 
915   StringRef S = Arg->getValue();
916   uint64_t V;
917   if (!to_integer(S, V)) {
918     error("-image-base: number expected, but got " + S);
919     return 0;
920   }
921   if ((V % Config->MaxPageSize) != 0)
922     warn("-image-base: address isn't multiple of page size: " + S);
923   return V;
924 }
925 
926 // Parses --defsym=alias option.
927 static std::vector<std::pair<StringRef, StringRef>>
928 getDefsym(opt::InputArgList &Args) {
929   std::vector<std::pair<StringRef, StringRef>> Ret;
930   for (auto *Arg : Args.filtered(OPT_defsym)) {
931     StringRef From;
932     StringRef To;
933     std::tie(From, To) = StringRef(Arg->getValue()).split('=');
934     if (!isValidCIdentifier(To))
935       error("--defsym: symbol name expected, but got " + To);
936     Ret.push_back({From, To});
937   }
938   return Ret;
939 }
940 
941 // Parses `--exclude-libs=lib,lib,...`.
942 // The library names may be delimited by commas or colons.
943 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
944   DenseSet<StringRef> Ret;
945   for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
946     StringRef S = Arg->getValue();
947     for (;;) {
948       size_t Pos = S.find_first_of(",:");
949       if (Pos == StringRef::npos)
950         break;
951       Ret.insert(S.substr(0, Pos));
952       S = S.substr(Pos + 1);
953     }
954     Ret.insert(S);
955   }
956   return Ret;
957 }
958 
959 // Handles the -exclude-libs option. If a static library file is specified
960 // by the -exclude-libs option, all public symbols from the archive become
961 // private unless otherwise specified by version scripts or something.
962 // A special library name "ALL" means all archive files.
963 //
964 // This is not a popular option, but some programs such as bionic libc use it.
965 static void excludeLibs(opt::InputArgList &Args, ArrayRef<InputFile *> Files) {
966   DenseSet<StringRef> Libs = getExcludeLibs(Args);
967   bool All = Libs.count("ALL");
968 
969   for (InputFile *File : Files)
970     if (auto *F = dyn_cast<ArchiveFile>(File))
971       if (All || Libs.count(path::filename(F->getName())))
972         for (SymbolBody *Sym : F->getSymbols())
973           Sym->symbol()->VersionId = VER_NDX_LOCAL;
974 }
975 
976 // Do actual linking. Note that when this function is called,
977 // all linker scripts have already been parsed.
978 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
979   Target = getTarget();
980 
981   Config->MaxPageSize = getMaxPageSize(Args);
982   Config->ImageBase = getImageBase(Args);
983 
984   // Default output filename is "a.out" by the Unix tradition.
985   if (Config->OutputFile.empty())
986     Config->OutputFile = "a.out";
987 
988   // Fail early if the output file or map file is not writable. If a user has a
989   // long link, e.g. due to a large LTO link, they do not wish to run it and
990   // find that it failed because there was a mistake in their command-line.
991   if (auto E = tryCreateFile(Config->OutputFile))
992     error("cannot open output file " + Config->OutputFile + ": " + E.message());
993   if (auto E = tryCreateFile(Config->MapFile))
994     error("cannot open map file " + Config->MapFile + ": " + E.message());
995   if (ErrorCount)
996     return;
997 
998   // Use default entry point name if no name was given via the command
999   // line nor linker scripts. For some reason, MIPS entry point name is
1000   // different from others.
1001   Config->WarnMissingEntry =
1002       (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
1003   if (Config->Entry.empty() && !Config->Relocatable)
1004     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
1005 
1006   // Handle --trace-symbol.
1007   for (auto *Arg : Args.filtered(OPT_trace_symbol))
1008     Symtab->trace(Arg->getValue());
1009 
1010   // Add all files to the symbol table. This will add almost all
1011   // symbols that we need to the symbol table.
1012   for (InputFile *F : Files)
1013     Symtab->addFile<ELFT>(F);
1014 
1015   // Some symbols (such as __ehdr_start) are defined lazily only when there
1016   // are undefined symbols for them, so we add these to trigger that logic.
1017   for (StringRef Sym : Script->Opt.ReferencedSymbols)
1018     Symtab->addUndefined<ELFT>(Sym);
1019 
1020   // If an entry symbol is in a static archive, pull out that file now
1021   // to complete the symbol table. After this, no new names except a
1022   // few linker-synthesized ones will be added to the symbol table.
1023   if (Symtab->find(Config->Entry))
1024     Symtab->addUndefined<ELFT>(Config->Entry);
1025 
1026   // Return if there were name resolution errors.
1027   if (ErrorCount)
1028     return;
1029 
1030   // Handle the `--undefined <sym>` options.
1031   Symtab->scanUndefinedFlags<ELFT>();
1032 
1033   // Handle undefined symbols in DSOs.
1034   Symtab->scanShlibUndefined<ELFT>();
1035 
1036   // Handle the -exclude-libs option.
1037   if (Args.hasArg(OPT_exclude_libs))
1038     excludeLibs(Args, Files);
1039 
1040   // Apply version scripts.
1041   Symtab->scanVersionScript();
1042 
1043   // Create wrapped symbols for -wrap option.
1044   for (auto *Arg : Args.filtered(OPT_wrap))
1045     Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1046 
1047   // Create alias symbols for -defsym option.
1048   for (std::pair<StringRef, StringRef> &Def : getDefsym(Args))
1049     Symtab->addSymbolAlias<ELFT>(Def.first, Def.second);
1050 
1051   Symtab->addCombinedLTOObject<ELFT>();
1052   if (ErrorCount)
1053     return;
1054 
1055   // Apply symbol renames for -wrap and -defsym
1056   Symtab->applySymbolRenames();
1057 
1058   // Now that we have a complete list of input files.
1059   // Beyond this point, no new files are added.
1060   // Aggregate all input sections into one place.
1061   for (ObjFile<ELFT> *F : ObjFile<ELFT>::Instances)
1062     for (InputSectionBase *S : F->getSections())
1063       if (S && S != &InputSection::Discarded)
1064         InputSections.push_back(S);
1065   for (BinaryFile *F : BinaryFile::Instances)
1066     for (InputSectionBase *S : F->getSections())
1067       InputSections.push_back(cast<InputSection>(S));
1068 
1069   // This adds a .comment section containing a version string. We have to add it
1070   // before decompressAndMergeSections because the .comment section is a
1071   // mergeable section.
1072   if (!Config->Relocatable)
1073     InputSections.push_back(createCommentSection<ELFT>());
1074 
1075   // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1076   // and identical code folding.
1077   if (Config->GcSections)
1078     markLive<ELFT>();
1079   decompressAndMergeSections();
1080   if (Config->ICF)
1081     doIcf<ELFT>();
1082 
1083   // Write the result to the file.
1084   writeResult<ELFT>();
1085 }
1086