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