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