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