]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/Driver.cpp
Merge ^/head r337619 through r337645.
[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 "Filesystem.h"
29 #include "ICF.h"
30 #include "InputFiles.h"
31 #include "InputSection.h"
32 #include "LinkerScript.h"
33 #include "MarkLive.h"
34 #include "OutputSections.h"
35 #include "ScriptParser.h"
36 #include "SymbolTable.h"
37 #include "Symbols.h"
38 #include "SyntheticSections.h"
39 #include "Target.h"
40 #include "Writer.h"
41 #include "lld/Common/Args.h"
42 #include "lld/Common/Driver.h"
43 #include "lld/Common/ErrorHandler.h"
44 #include "lld/Common/Memory.h"
45 #include "lld/Common/Strings.h"
46 #include "lld/Common/TargetOptionsCommandFlags.h"
47 #include "lld/Common/Threads.h"
48 #include "lld/Common/Version.h"
49 #include "llvm/ADT/SetVector.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/StringSwitch.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compression.h"
54 #include "llvm/Support/LEB128.h"
55 #include "llvm/Support/Path.h"
56 #include "llvm/Support/TarWriter.h"
57 #include "llvm/Support/TargetSelect.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include <cstdlib>
60 #include <utility>
61
62 using namespace llvm;
63 using namespace llvm::ELF;
64 using namespace llvm::object;
65 using namespace llvm::sys;
66
67 using namespace lld;
68 using namespace lld::elf;
69
70 Configuration *elf::Config;
71 LinkerDriver *elf::Driver;
72
73 static void setConfigs(opt::InputArgList &Args);
74
75 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
76                raw_ostream &Error) {
77   errorHandler().LogName = sys::path::filename(Args[0]);
78   errorHandler().ErrorLimitExceededMsg =
79       "too many errors emitted, stopping now (use "
80       "-error-limit=0 to see all errors)";
81   errorHandler().ErrorOS = &Error;
82   errorHandler().ExitEarly = CanExitEarly;
83   errorHandler().ColorDiagnostics = Error.has_colors();
84
85   InputSections.clear();
86   OutputSections.clear();
87   Tar = nullptr;
88   BinaryFiles.clear();
89   BitcodeFiles.clear();
90   ObjectFiles.clear();
91   SharedFiles.clear();
92
93   Config = make<Configuration>();
94   Driver = make<LinkerDriver>();
95   Script = make<LinkerScript>();
96   Symtab = make<SymbolTable>();
97   Config->ProgName = Args[0];
98
99   Driver->main(Args);
100
101   // Exit immediately if we don't need to return to the caller.
102   // This saves time because the overhead of calling destructors
103   // for all globally-allocated objects is not negligible.
104   if (CanExitEarly)
105     exitLld(errorCount() ? 1 : 0);
106
107   freeArena();
108   return !errorCount();
109 }
110
111 // Parses a linker -m option.
112 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
113   uint8_t OSABI = 0;
114   StringRef S = Emul;
115   if (S.endswith("_fbsd")) {
116     S = S.drop_back(5);
117     OSABI = ELFOSABI_FREEBSD;
118   }
119
120   std::pair<ELFKind, uint16_t> Ret =
121       StringSwitch<std::pair<ELFKind, uint16_t>>(S)
122           .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
123                  {ELF64LEKind, EM_AARCH64})
124           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
125           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
126           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
127           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
128           .Case("elf32ppc", {ELF32BEKind, EM_PPC})
129           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
130           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
131           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
132           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
133           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
134           .Case("elf_i386", {ELF32LEKind, EM_386})
135           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
136           .Default({ELFNoneKind, EM_NONE});
137
138   if (Ret.first == ELFNoneKind)
139     error("unknown emulation: " + Emul);
140   return std::make_tuple(Ret.first, Ret.second, OSABI);
141 }
142
143 // Returns slices of MB by parsing MB as an archive file.
144 // Each slice consists of a member file in the archive.
145 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
146     MemoryBufferRef MB) {
147   std::unique_ptr<Archive> File =
148       CHECK(Archive::create(MB),
149             MB.getBufferIdentifier() + ": failed to parse archive");
150
151   std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
152   Error Err = Error::success();
153   bool AddToTar = File->isThin() && Tar;
154   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
155     Archive::Child C =
156         CHECK(COrErr, MB.getBufferIdentifier() +
157                           ": could not get the child of the archive");
158     MemoryBufferRef MBRef =
159         CHECK(C.getMemoryBufferRef(),
160               MB.getBufferIdentifier() +
161                   ": could not get the buffer for a child of the archive");
162     if (AddToTar)
163       Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer());
164     V.push_back(std::make_pair(MBRef, C.getChildOffset()));
165   }
166   if (Err)
167     fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
168           toString(std::move(Err)));
169
170   // Take ownership of memory buffers created for members of thin archives.
171   for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
172     make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
173
174   return V;
175 }
176
177 // Opens a file and create a file object. Path has to be resolved already.
178 void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
179   using namespace sys::fs;
180
181   Optional<MemoryBufferRef> Buffer = readFile(Path);
182   if (!Buffer.hasValue())
183     return;
184   MemoryBufferRef MBRef = *Buffer;
185
186   if (InBinary) {
187     Files.push_back(make<BinaryFile>(MBRef));
188     return;
189   }
190
191   switch (identify_magic(MBRef.getBuffer())) {
192   case file_magic::unknown:
193     readLinkerScript(MBRef);
194     return;
195   case file_magic::archive: {
196     // Handle -whole-archive.
197     if (InWholeArchive) {
198       for (const auto &P : getArchiveMembers(MBRef))
199         Files.push_back(createObjectFile(P.first, Path, P.second));
200       return;
201     }
202
203     std::unique_ptr<Archive> File =
204         CHECK(Archive::create(MBRef), Path + ": failed to parse archive");
205
206     // If an archive file has no symbol table, it is likely that a user
207     // is attempting LTO and using a default ar command that doesn't
208     // understand the LLVM bitcode file. It is a pretty common error, so
209     // we'll handle it as if it had a symbol table.
210     if (!File->isEmpty() && !File->hasSymbolTable()) {
211       for (const auto &P : getArchiveMembers(MBRef))
212         Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
213       return;
214     }
215
216     // Handle the regular case.
217     Files.push_back(make<ArchiveFile>(std::move(File)));
218     return;
219   }
220   case file_magic::elf_shared_object:
221     if (Config->Relocatable) {
222       error("attempted static link of dynamic object " + Path);
223       return;
224     }
225
226     // DSOs usually have DT_SONAME tags in their ELF headers, and the
227     // sonames are used to identify DSOs. But if they are missing,
228     // they are identified by filenames. We don't know whether the new
229     // file has a DT_SONAME or not because we haven't parsed it yet.
230     // Here, we set the default soname for the file because we might
231     // need it later.
232     //
233     // If a file was specified by -lfoo, the directory part is not
234     // significant, as a user did not specify it. This behavior is
235     // compatible with GNU.
236     Files.push_back(
237         createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path));
238     return;
239   case file_magic::bitcode:
240   case file_magic::elf_relocatable:
241     if (InLib)
242       Files.push_back(make<LazyObjFile>(MBRef, "", 0));
243     else
244       Files.push_back(createObjectFile(MBRef));
245     break;
246   default:
247     error(Path + ": unknown file type");
248   }
249 }
250
251 // Add a given library by searching it from input search paths.
252 void LinkerDriver::addLibrary(StringRef Name) {
253   if (Optional<std::string> Path = searchLibrary(Name))
254     addFile(*Path, /*WithLOption=*/true);
255   else
256     error("unable to find library -l" + Name);
257 }
258
259 // This function is called on startup. We need this for LTO since
260 // LTO calls LLVM functions to compile bitcode files to native code.
261 // Technically this can be delayed until we read bitcode files, but
262 // we don't bother to do lazily because the initialization is fast.
263 static void initLLVM() {
264   InitializeAllTargets();
265   InitializeAllTargetMCs();
266   InitializeAllAsmPrinters();
267   InitializeAllAsmParsers();
268 }
269
270 // Some command line options or some combinations of them are not allowed.
271 // This function checks for such errors.
272 static void checkOptions(opt::InputArgList &Args) {
273   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
274   // table which is a relatively new feature.
275   if (Config->EMachine == EM_MIPS && Config->GnuHash)
276     error("the .gnu.hash section is not compatible with the MIPS target.");
277
278   if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64)
279     error("--fix-cortex-a53-843419 is only supported on AArch64 targets.");
280
281   if (Config->Pie && Config->Shared)
282     error("-shared and -pie may not be used together");
283
284   if (!Config->Shared && !Config->FilterList.empty())
285     error("-F may not be used without -shared");
286
287   if (!Config->Shared && !Config->AuxiliaryList.empty())
288     error("-f may not be used without -shared");
289
290   if (!Config->Relocatable && !Config->DefineCommon)
291     error("-no-define-common not supported in non relocatable output");
292
293   if (Config->Relocatable) {
294     if (Config->Shared)
295       error("-r and -shared may not be used together");
296     if (Config->GcSections)
297       error("-r and --gc-sections may not be used together");
298     if (Config->GdbIndex)
299       error("-r and --gdb-index may not be used together");
300     if (Config->ICF != ICFLevel::None)
301       error("-r and --icf may not be used together");
302     if (Config->Pie)
303       error("-r and -pie may not be used together");
304   }
305
306   if (Config->ExecuteOnly) {
307     if (Config->EMachine != EM_AARCH64)
308       error("-execute-only is only supported on AArch64 targets");
309
310     if (Config->SingleRoRx && !Script->HasSectionsCommand)
311       error("-execute-only and -no-rosegment cannot be used together");
312   }
313 }
314
315 static const char *getReproduceOption(opt::InputArgList &Args) {
316   if (auto *Arg = Args.getLastArg(OPT_reproduce))
317     return Arg->getValue();
318   return getenv("LLD_REPRODUCE");
319 }
320
321 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
322   for (auto *Arg : Args.filtered(OPT_z))
323     if (Key == Arg->getValue())
324       return true;
325   return false;
326 }
327
328 static bool getZFlag(opt::InputArgList &Args, StringRef K1, StringRef K2,
329                      bool Default) {
330   for (auto *Arg : Args.filtered_reverse(OPT_z)) {
331     if (K1 == Arg->getValue())
332       return true;
333     if (K2 == Arg->getValue())
334       return false;
335   }
336   return Default;
337 }
338
339 static bool isKnown(StringRef S) {
340   return S == "combreloc" || S == "copyreloc" || S == "defs" ||
341          S == "execstack" || S == "hazardplt" || S == "initfirst" ||
342          S == "keep-text-section-prefix" || S == "lazy" || S == "muldefs" ||
343          S == "nocombreloc" || S == "nocopyreloc" || S == "nodelete" ||
344          S == "nodlopen" || S == "noexecstack" ||
345          S == "nokeep-text-section-prefix" || S == "norelro" || S == "notext" ||
346          S == "now" || S == "origin" || S == "relro" || S == "retpolineplt" ||
347          S == "rodynamic" || S == "text" || S == "wxneeded" ||
348          S.startswith("max-page-size=") || S.startswith("stack-size=");
349 }
350
351 // Report an error for an unknown -z option.
352 static void checkZOptions(opt::InputArgList &Args) {
353   for (auto *Arg : Args.filtered(OPT_z))
354     if (!isKnown(Arg->getValue()))
355       error("unknown -z value: " + StringRef(Arg->getValue()));
356 }
357
358 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
359   ELFOptTable Parser;
360   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
361
362   // Interpret this flag early because error() depends on them.
363   errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
364
365   // Handle -help
366   if (Args.hasArg(OPT_help)) {
367     printHelp();
368     return;
369   }
370
371   // Handle -v or -version.
372   //
373   // A note about "compatible with GNU linkers" message: this is a hack for
374   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
375   // still the newest version in March 2017) or earlier to recognize LLD as
376   // a GNU compatible linker. As long as an output for the -v option
377   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
378   //
379   // This is somewhat ugly hack, but in reality, we had no choice other
380   // than doing this. Considering the very long release cycle of Libtool,
381   // it is not easy to improve it to recognize LLD as a GNU compatible
382   // linker in a timely manner. Even if we can make it, there are still a
383   // lot of "configure" scripts out there that are generated by old version
384   // of Libtool. We cannot convince every software developer to migrate to
385   // the latest version and re-generate scripts. So we have this hack.
386   if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
387     message(getLLDVersion() + " (compatible with GNU linkers)");
388
389   // The behavior of -v or --version is a bit strange, but this is
390   // needed for compatibility with GNU linkers.
391   if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT))
392     return;
393   if (Args.hasArg(OPT_version))
394     return;
395
396   if (const char *Path = getReproduceOption(Args)) {
397     // Note that --reproduce is a debug option so you can ignore it
398     // if you are trying to understand the whole picture of the code.
399     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
400         TarWriter::create(Path, path::stem(Path));
401     if (ErrOrWriter) {
402       Tar = ErrOrWriter->get();
403       Tar->append("response.txt", createResponseFile(Args));
404       Tar->append("version.txt", getLLDVersion() + "\n");
405       make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
406     } else {
407       error(Twine("--reproduce: failed to open ") + Path + ": " +
408             toString(ErrOrWriter.takeError()));
409     }
410   }
411
412   readConfigs(Args);
413   checkZOptions(Args);
414   initLLVM();
415   createFiles(Args);
416   if (errorCount())
417     return;
418
419   inferMachineType();
420   setConfigs(Args);
421   checkOptions(Args);
422   if (errorCount())
423     return;
424
425   switch (Config->EKind) {
426   case ELF32LEKind:
427     link<ELF32LE>(Args);
428     return;
429   case ELF32BEKind:
430     link<ELF32BE>(Args);
431     return;
432   case ELF64LEKind:
433     link<ELF64LE>(Args);
434     return;
435   case ELF64BEKind:
436     link<ELF64BE>(Args);
437     return;
438   default:
439     llvm_unreachable("unknown Config->EKind");
440   }
441 }
442
443 static std::string getRpath(opt::InputArgList &Args) {
444   std::vector<StringRef> V = args::getStrings(Args, OPT_rpath);
445   return llvm::join(V.begin(), V.end(), ":");
446 }
447
448 // Determines what we should do if there are remaining unresolved
449 // symbols after the name resolution.
450 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
451   if (Args.hasArg(OPT_relocatable))
452     return UnresolvedPolicy::IgnoreAll;
453
454   UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols,
455                                               OPT_warn_unresolved_symbols, true)
456                                      ? UnresolvedPolicy::ReportError
457                                      : UnresolvedPolicy::Warn;
458
459   // Process the last of -unresolved-symbols, -no-undefined or -z defs.
460   for (auto *Arg : llvm::reverse(Args)) {
461     switch (Arg->getOption().getID()) {
462     case OPT_unresolved_symbols: {
463       StringRef S = Arg->getValue();
464       if (S == "ignore-all" || S == "ignore-in-object-files")
465         return UnresolvedPolicy::Ignore;
466       if (S == "ignore-in-shared-libs" || S == "report-all")
467         return ErrorOrWarn;
468       error("unknown --unresolved-symbols value: " + S);
469       continue;
470     }
471     case OPT_no_undefined:
472       return ErrorOrWarn;
473     case OPT_z:
474       if (StringRef(Arg->getValue()) == "defs")
475         return ErrorOrWarn;
476       continue;
477     }
478   }
479
480   // -shared implies -unresolved-symbols=ignore-all because missing
481   // symbols are likely to be resolved at runtime using other DSOs.
482   if (Config->Shared)
483     return UnresolvedPolicy::Ignore;
484   return ErrorOrWarn;
485 }
486
487 static Target2Policy getTarget2(opt::InputArgList &Args) {
488   StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
489   if (S == "rel")
490     return Target2Policy::Rel;
491   if (S == "abs")
492     return Target2Policy::Abs;
493   if (S == "got-rel")
494     return Target2Policy::GotRel;
495   error("unknown --target2 option: " + S);
496   return Target2Policy::GotRel;
497 }
498
499 static bool isOutputFormatBinary(opt::InputArgList &Args) {
500   if (auto *Arg = Args.getLastArg(OPT_oformat)) {
501     StringRef S = Arg->getValue();
502     if (S == "binary")
503       return true;
504     if (S.startswith("elf"))
505       return false;
506     error("unknown --oformat value: " + S);
507   }
508   return false;
509 }
510
511 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
512   if (Args.hasArg(OPT_relocatable))
513     return DiscardPolicy::None;
514
515   auto *Arg =
516       Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
517   if (!Arg)
518     return DiscardPolicy::Default;
519   if (Arg->getOption().getID() == OPT_discard_all)
520     return DiscardPolicy::All;
521   if (Arg->getOption().getID() == OPT_discard_locals)
522     return DiscardPolicy::Locals;
523   return DiscardPolicy::None;
524 }
525
526 static StringRef getDynamicLinker(opt::InputArgList &Args) {
527   auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
528   if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
529     return "";
530   return Arg->getValue();
531 }
532
533 static ICFLevel getICF(opt::InputArgList &Args) {
534   auto *Arg = Args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
535   if (!Arg || Arg->getOption().getID() == OPT_icf_none)
536     return ICFLevel::None;
537   if (Arg->getOption().getID() == OPT_icf_safe)
538     return ICFLevel::Safe;
539   return ICFLevel::All;
540 }
541
542 static StripPolicy getStrip(opt::InputArgList &Args) {
543   if (Args.hasArg(OPT_relocatable))
544     return StripPolicy::None;
545
546   auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
547   if (!Arg)
548     return StripPolicy::None;
549   if (Arg->getOption().getID() == OPT_strip_all)
550     return StripPolicy::All;
551   return StripPolicy::Debug;
552 }
553
554 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) {
555   uint64_t VA = 0;
556   if (S.startswith("0x"))
557     S = S.drop_front(2);
558   if (!to_integer(S, VA, 16))
559     error("invalid argument: " + toString(Arg));
560   return VA;
561 }
562
563 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
564   StringMap<uint64_t> Ret;
565   for (auto *Arg : Args.filtered(OPT_section_start)) {
566     StringRef Name;
567     StringRef Addr;
568     std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
569     Ret[Name] = parseSectionAddress(Addr, *Arg);
570   }
571
572   if (auto *Arg = Args.getLastArg(OPT_Ttext))
573     Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg);
574   if (auto *Arg = Args.getLastArg(OPT_Tdata))
575     Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg);
576   if (auto *Arg = Args.getLastArg(OPT_Tbss))
577     Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg);
578   return Ret;
579 }
580
581 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
582   StringRef S = Args.getLastArgValue(OPT_sort_section);
583   if (S == "alignment")
584     return SortSectionPolicy::Alignment;
585   if (S == "name")
586     return SortSectionPolicy::Name;
587   if (!S.empty())
588     error("unknown --sort-section rule: " + S);
589   return SortSectionPolicy::Default;
590 }
591
592 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) {
593   StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place");
594   if (S == "warn")
595     return OrphanHandlingPolicy::Warn;
596   if (S == "error")
597     return OrphanHandlingPolicy::Error;
598   if (S != "place")
599     error("unknown --orphan-handling mode: " + S);
600   return OrphanHandlingPolicy::Place;
601 }
602
603 // Parse --build-id or --build-id=<style>. We handle "tree" as a
604 // synonym for "sha1" because all our hash functions including
605 // -build-id=sha1 are actually tree hashes for performance reasons.
606 static std::pair<BuildIdKind, std::vector<uint8_t>>
607 getBuildId(opt::InputArgList &Args) {
608   auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
609   if (!Arg)
610     return {BuildIdKind::None, {}};
611
612   if (Arg->getOption().getID() == OPT_build_id)
613     return {BuildIdKind::Fast, {}};
614
615   StringRef S = Arg->getValue();
616   if (S == "fast")
617     return {BuildIdKind::Fast, {}};
618   if (S == "md5")
619     return {BuildIdKind::Md5, {}};
620   if (S == "sha1" || S == "tree")
621     return {BuildIdKind::Sha1, {}};
622   if (S == "uuid")
623     return {BuildIdKind::Uuid, {}};
624   if (S.startswith("0x"))
625     return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
626
627   if (S != "none")
628     error("unknown --build-id style: " + S);
629   return {BuildIdKind::None, {}};
630 }
631
632 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &Args) {
633   StringRef S = Args.getLastArgValue(OPT_pack_dyn_relocs, "none");
634   if (S == "android")
635     return {true, false};
636   if (S == "relr")
637     return {false, true};
638   if (S == "android+relr")
639     return {true, true};
640
641   if (S != "none")
642     error("unknown -pack-dyn-relocs format: " + S);
643   return {false, false};
644 }
645
646 static void readCallGraph(MemoryBufferRef MB) {
647   // Build a map from symbol name to section
648   DenseMap<StringRef, const Symbol *> SymbolNameToSymbol;
649   for (InputFile *File : ObjectFiles)
650     for (Symbol *Sym : File->getSymbols())
651       SymbolNameToSymbol[Sym->getName()] = Sym;
652
653   for (StringRef L : args::getLines(MB)) {
654     SmallVector<StringRef, 3> Fields;
655     L.split(Fields, ' ');
656     uint64_t Count;
657     if (Fields.size() != 3 || !to_integer(Fields[2], Count))
658       fatal(MB.getBufferIdentifier() + ": parse error");
659     const Symbol *FromSym = SymbolNameToSymbol.lookup(Fields[0]);
660     const Symbol *ToSym = SymbolNameToSymbol.lookup(Fields[1]);
661     if (Config->WarnSymbolOrdering) {
662       if (!FromSym)
663         warn(MB.getBufferIdentifier() + ": no such symbol: " + Fields[0]);
664       if (!ToSym)
665         warn(MB.getBufferIdentifier() + ": no such symbol: " + Fields[1]);
666     }
667     if (!FromSym || !ToSym || Count == 0)
668       continue;
669     warnUnorderableSymbol(FromSym);
670     warnUnorderableSymbol(ToSym);
671     const Defined *FromSymD = dyn_cast<Defined>(FromSym);
672     const Defined *ToSymD = dyn_cast<Defined>(ToSym);
673     if (!FromSymD || !ToSymD)
674       continue;
675     const auto *FromSB = dyn_cast_or_null<InputSectionBase>(FromSymD->Section);
676     const auto *ToSB = dyn_cast_or_null<InputSectionBase>(ToSymD->Section);
677     if (!FromSB || !ToSB)
678       continue;
679     Config->CallGraphProfile[std::make_pair(FromSB, ToSB)] += Count;
680   }
681 }
682
683 static bool getCompressDebugSections(opt::InputArgList &Args) {
684   StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
685   if (S == "none")
686     return false;
687   if (S != "zlib")
688     error("unknown --compress-debug-sections value: " + S);
689   if (!zlib::isAvailable())
690     error("--compress-debug-sections: zlib is not available");
691   return true;
692 }
693
694 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &Args,
695                                                         unsigned Id) {
696   auto *Arg = Args.getLastArg(Id);
697   if (!Arg)
698     return {"", ""};
699
700   StringRef S = Arg->getValue();
701   std::pair<StringRef, StringRef> Ret = S.split(';');
702   if (Ret.second.empty())
703     error(Arg->getSpelling() + " expects 'old;new' format, but got " + S);
704   return Ret;
705 }
706
707 // Parse the symbol ordering file and warn for any duplicate entries.
708 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef MB) {
709   SetVector<StringRef> Names;
710   for (StringRef S : args::getLines(MB))
711     if (!Names.insert(S) && Config->WarnSymbolOrdering)
712       warn(MB.getBufferIdentifier() + ": duplicate ordered symbol: " + S);
713
714   return Names.takeVector();
715 }
716
717 static void parseClangOption(StringRef Opt, const Twine &Msg) {
718   std::string Err;
719   raw_string_ostream OS(Err);
720
721   const char *Argv[] = {Config->ProgName.data(), Opt.data()};
722   if (cl::ParseCommandLineOptions(2, Argv, "", &OS))
723     return;
724   OS.flush();
725   error(Msg + ": " + StringRef(Err).trim());
726 }
727
728 // Initializes Config members by the command line options.
729 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
730   errorHandler().Verbose = Args.hasArg(OPT_verbose);
731   errorHandler().FatalWarnings =
732       Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
733   ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
734
735   Config->AllowMultipleDefinition =
736       Args.hasFlag(OPT_allow_multiple_definition,
737                    OPT_no_allow_multiple_definition, false) ||
738       hasZOption(Args, "muldefs");
739   Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary);
740   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
741   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
742   Config->CheckSections =
743       Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
744   Config->Chroot = Args.getLastArgValue(OPT_chroot);
745   Config->CompressDebugSections = getCompressDebugSections(Args);
746   Config->Cref = Args.hasFlag(OPT_cref, OPT_no_cref, false);
747   Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common,
748                                       !Args.hasArg(OPT_relocatable));
749   Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
750   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
751   Config->Discard = getDiscard(Args);
752   Config->DwoDir = Args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
753   Config->DynamicLinker = getDynamicLinker(Args);
754   Config->EhFrameHdr =
755       Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
756   Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
757   Config->EnableNewDtags =
758       Args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
759   Config->Entry = Args.getLastArgValue(OPT_entry);
760   Config->ExecuteOnly =
761       Args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
762   Config->ExportDynamic =
763       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
764   Config->FilterList = args::getStrings(Args, OPT_filter);
765   Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
766   Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419);
767   Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
768   Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
769   Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
770   Config->ICF = getICF(Args);
771   Config->IgnoreDataAddressEquality =
772       Args.hasArg(OPT_ignore_data_address_equality);
773   Config->IgnoreFunctionAddressEquality =
774       Args.hasArg(OPT_ignore_function_address_equality);
775   Config->Init = Args.getLastArgValue(OPT_init, "_init");
776   Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
777   Config->LTODebugPassManager = Args.hasArg(OPT_lto_debug_pass_manager);
778   Config->LTONewPassManager = Args.hasArg(OPT_lto_new_pass_manager);
779   Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
780   Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
781   Config->LTOObjPath = Args.getLastArgValue(OPT_plugin_opt_obj_path_eq);
782   Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
783   Config->LTOSampleProfile = Args.getLastArgValue(OPT_lto_sample_profile);
784   Config->MapFile = Args.getLastArgValue(OPT_Map);
785   Config->MipsGotSize = args::getInteger(Args, OPT_mips_got_size, 0xfff0);
786   Config->MergeArmExidx =
787       Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
788   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
789   Config->Nostdlib = Args.hasArg(OPT_nostdlib);
790   Config->OFormatBinary = isOutputFormatBinary(Args);
791   Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false);
792   Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
793   Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
794   Config->Optimize = args::getInteger(Args, OPT_O, 1);
795   Config->OrphanHandling = getOrphanHandling(Args);
796   Config->OutputFile = Args.getLastArgValue(OPT_o);
797   Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false);
798   Config->PrintIcfSections =
799       Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
800   Config->PrintGcSections =
801       Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
802   Config->Rpath = getRpath(Args);
803   Config->Relocatable = Args.hasArg(OPT_relocatable);
804   Config->SaveTemps = Args.hasArg(OPT_save_temps);
805   Config->SearchPaths = args::getStrings(Args, OPT_library_path);
806   Config->SectionStartMap = getSectionStartMap(Args);
807   Config->Shared = Args.hasArg(OPT_shared);
808   Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
809   Config->SoName = Args.getLastArgValue(OPT_soname);
810   Config->SortSection = getSortSection(Args);
811   Config->Strip = getStrip(Args);
812   Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
813   Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
814   Config->Target2 = getTarget2(Args);
815   Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
816   Config->ThinLTOCachePolicy = CHECK(
817       parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
818       "--thinlto-cache-policy: invalid cache policy");
819   Config->ThinLTOEmitImportsFiles =
820       Args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files);
821   Config->ThinLTOIndexOnly = Args.hasArg(OPT_plugin_opt_thinlto_index_only) ||
822                              Args.hasArg(OPT_plugin_opt_thinlto_index_only_eq);
823   Config->ThinLTOIndexOnlyArg =
824       Args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq);
825   Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
826   Config->ThinLTOObjectSuffixReplace =
827       getOldNewOptions(Args, OPT_plugin_opt_thinlto_object_suffix_replace_eq);
828   Config->ThinLTOPrefixReplace =
829       getOldNewOptions(Args, OPT_plugin_opt_thinlto_prefix_replace_eq);
830   Config->Trace = Args.hasArg(OPT_trace);
831   Config->Undefined = args::getStrings(Args, OPT_undefined);
832   Config->UndefinedVersion =
833       Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
834   Config->UseAndroidRelrTags = Args.hasFlag(
835       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
836   Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
837   Config->WarnBackrefs =
838       Args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
839   Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
840   Config->WarnSymbolOrdering =
841       Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
842   Config->ZCombreloc = getZFlag(Args, "combreloc", "nocombreloc", true);
843   Config->ZCopyreloc = getZFlag(Args, "copyreloc", "nocopyreloc", true);
844   Config->ZExecstack = getZFlag(Args, "execstack", "noexecstack", false);
845   Config->ZHazardplt = hasZOption(Args, "hazardplt");
846   Config->ZInitfirst = hasZOption(Args, "initfirst");
847   Config->ZKeepTextSectionPrefix = getZFlag(
848       Args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
849   Config->ZNodelete = hasZOption(Args, "nodelete");
850   Config->ZNodlopen = hasZOption(Args, "nodlopen");
851   Config->ZNow = getZFlag(Args, "now", "lazy", false);
852   Config->ZOrigin = hasZOption(Args, "origin");
853   Config->ZRelro = getZFlag(Args, "relro", "norelro", true);
854   Config->ZRetpolineplt = hasZOption(Args, "retpolineplt");
855   Config->ZRodynamic = hasZOption(Args, "rodynamic");
856   Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
857   Config->ZText = getZFlag(Args, "text", "notext", true);
858   Config->ZWxneeded = hasZOption(Args, "wxneeded");
859
860   // Parse LTO options.
861   if (auto *Arg = Args.getLastArg(OPT_plugin_opt_mcpu_eq))
862     parseClangOption(Saver.save("-mcpu=" + StringRef(Arg->getValue())),
863                      Arg->getSpelling());
864
865   for (auto *Arg : Args.filtered(OPT_plugin_opt))
866     parseClangOption(Arg->getValue(), Arg->getSpelling());
867
868   // Parse -mllvm options.
869   for (auto *Arg : Args.filtered(OPT_mllvm))
870     parseClangOption(Arg->getValue(), Arg->getSpelling());
871
872   if (Config->LTOO > 3)
873     error("invalid optimization level for LTO: " + Twine(Config->LTOO));
874   if (Config->LTOPartitions == 0)
875     error("--lto-partitions: number of threads must be > 0");
876   if (Config->ThinLTOJobs == 0)
877     error("--thinlto-jobs: number of threads must be > 0");
878
879   // Parse ELF{32,64}{LE,BE} and CPU type.
880   if (auto *Arg = Args.getLastArg(OPT_m)) {
881     StringRef S = Arg->getValue();
882     std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
883         parseEmulation(S);
884     Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
885     Config->Emulation = S;
886   }
887
888   // Parse -hash-style={sysv,gnu,both}.
889   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
890     StringRef S = Arg->getValue();
891     if (S == "sysv")
892       Config->SysvHash = true;
893     else if (S == "gnu")
894       Config->GnuHash = true;
895     else if (S == "both")
896       Config->SysvHash = Config->GnuHash = true;
897     else
898       error("unknown -hash-style: " + S);
899   }
900
901   if (Args.hasArg(OPT_print_map))
902     Config->MapFile = "-";
903
904   // --omagic is an option to create old-fashioned executables in which
905   // .text segments are writable. Today, the option is still in use to
906   // create special-purpose programs such as boot loaders. It doesn't
907   // make sense to create PT_GNU_RELRO for such executables.
908   if (Config->Omagic)
909     Config->ZRelro = false;
910
911   std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
912
913   std::tie(Config->AndroidPackDynRelocs, Config->RelrPackDynRelocs) =
914       getPackDynRelocs(Args);
915
916   if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
917     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
918       Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer);
919
920   // If --retain-symbol-file is used, we'll keep only the symbols listed in
921   // the file and discard all others.
922   if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
923     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
924     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
925       for (StringRef S : args::getLines(*Buffer))
926         Config->VersionScriptGlobals.push_back(
927             {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
928   }
929
930   bool HasExportDynamic =
931       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
932
933   // Parses -dynamic-list and -export-dynamic-symbol. They make some
934   // symbols private. Note that -export-dynamic takes precedence over them
935   // as it says all symbols should be exported.
936   if (!HasExportDynamic) {
937     for (auto *Arg : Args.filtered(OPT_dynamic_list))
938       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
939         readDynamicList(*Buffer);
940
941     for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
942       Config->DynamicList.push_back(
943           {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
944   }
945
946   // If --export-dynamic-symbol=foo is given and symbol foo is defined in
947   // an object file in an archive file, that object file should be pulled
948   // out and linked. (It doesn't have to behave like that from technical
949   // point of view, but this is needed for compatibility with GNU.)
950   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
951     Config->Undefined.push_back(Arg->getValue());
952
953   for (auto *Arg : Args.filtered(OPT_version_script))
954     if (Optional<std::string> Path = searchScript(Arg->getValue())) {
955       if (Optional<MemoryBufferRef> Buffer = readFile(*Path))
956         readVersionScript(*Buffer);
957     } else {
958       error(Twine("cannot find version script ") + Arg->getValue());
959     }
960 }
961
962 // Some Config members do not directly correspond to any particular
963 // command line options, but computed based on other Config values.
964 // This function initialize such members. See Config.h for the details
965 // of these values.
966 static void setConfigs(opt::InputArgList &Args) {
967   ELFKind Kind = Config->EKind;
968   uint16_t Machine = Config->EMachine;
969
970   Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
971   Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind);
972   Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind);
973   Config->Endianness =
974       Config->IsLE ? support::endianness::little : support::endianness::big;
975   Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS);
976   Config->Pic = Config->Pie || Config->Shared;
977   Config->Wordsize = Config->Is64 ? 8 : 4;
978
979   // There is an ILP32 ABI for x86-64, although it's not very popular.
980   // It is called the x32 ABI.
981   bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64);
982
983   // ELF defines two different ways to store relocation addends as shown below:
984   //
985   //  Rel:  Addends are stored to the location where relocations are applied.
986   //  Rela: Addends are stored as part of relocation entry.
987   //
988   // In other words, Rela makes it easy to read addends at the price of extra
989   // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
990   // different mechanisms in the first place, but this is how the spec is
991   // defined.
992   //
993   // You cannot choose which one, Rel or Rela, you want to use. Instead each
994   // ABI defines which one you need to use. The following expression expresses
995   // that.
996   Config->IsRela =
997       (Config->Is64 || IsX32 || Machine == EM_PPC) && Machine != EM_MIPS;
998
999   // If the output uses REL relocations we must store the dynamic relocation
1000   // addends to the output sections. We also store addends for RELA relocations
1001   // if --apply-dynamic-relocs is used.
1002   // We default to not writing the addends when using RELA relocations since
1003   // any standard conforming tool can find it in r_addend.
1004   Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs,
1005                                       OPT_no_apply_dynamic_relocs, false) ||
1006                          !Config->IsRela;
1007 }
1008
1009 // Returns a value of "-format" option.
1010 static bool getBinaryOption(StringRef S) {
1011   if (S == "binary")
1012     return true;
1013   if (S == "elf" || S == "default")
1014     return false;
1015   error("unknown -format value: " + S +
1016         " (supported formats: elf, default, binary)");
1017   return false;
1018 }
1019
1020 void LinkerDriver::createFiles(opt::InputArgList &Args) {
1021   // For --{push,pop}-state.
1022   std::vector<std::tuple<bool, bool, bool>> Stack;
1023
1024   // Iterate over argv to process input files and positional arguments.
1025   for (auto *Arg : Args) {
1026     switch (Arg->getOption().getUnaliasedOption().getID()) {
1027     case OPT_library:
1028       addLibrary(Arg->getValue());
1029       break;
1030     case OPT_INPUT:
1031       addFile(Arg->getValue(), /*WithLOption=*/false);
1032       break;
1033     case OPT_defsym: {
1034       StringRef From;
1035       StringRef To;
1036       std::tie(From, To) = StringRef(Arg->getValue()).split('=');
1037       readDefsym(From, MemoryBufferRef(To, "-defsym"));
1038       break;
1039     }
1040     case OPT_script:
1041       if (Optional<std::string> Path = searchScript(Arg->getValue())) {
1042         if (Optional<MemoryBufferRef> MB = readFile(*Path))
1043           readLinkerScript(*MB);
1044         break;
1045       }
1046       error(Twine("cannot find linker script ") + Arg->getValue());
1047       break;
1048     case OPT_as_needed:
1049       Config->AsNeeded = true;
1050       break;
1051     case OPT_format:
1052       InBinary = getBinaryOption(Arg->getValue());
1053       break;
1054     case OPT_no_as_needed:
1055       Config->AsNeeded = false;
1056       break;
1057     case OPT_Bstatic:
1058       Config->Static = true;
1059       break;
1060     case OPT_Bdynamic:
1061       Config->Static = false;
1062       break;
1063     case OPT_whole_archive:
1064       InWholeArchive = true;
1065       break;
1066     case OPT_no_whole_archive:
1067       InWholeArchive = false;
1068       break;
1069     case OPT_just_symbols:
1070       if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue())) {
1071         Files.push_back(createObjectFile(*MB));
1072         Files.back()->JustSymbols = true;
1073       }
1074       break;
1075     case OPT_start_group:
1076       if (InputFile::IsInGroup)
1077         error("nested --start-group");
1078       InputFile::IsInGroup = true;
1079       break;
1080     case OPT_end_group:
1081       if (!InputFile::IsInGroup)
1082         error("stray --end-group");
1083       InputFile::IsInGroup = false;
1084       ++InputFile::NextGroupId;
1085       break;
1086     case OPT_start_lib:
1087       if (InLib)
1088         error("nested --start-lib");
1089       if (InputFile::IsInGroup)
1090         error("may not nest --start-lib in --start-group");
1091       InLib = true;
1092       InputFile::IsInGroup = true;
1093       break;
1094     case OPT_end_lib:
1095       if (!InLib)
1096         error("stray --end-lib");
1097       InLib = false;
1098       InputFile::IsInGroup = false;
1099       ++InputFile::NextGroupId;
1100       break;
1101     case OPT_push_state:
1102       Stack.emplace_back(Config->AsNeeded, Config->Static, InWholeArchive);
1103       break;
1104     case OPT_pop_state:
1105       if (Stack.empty()) {
1106         error("unbalanced --push-state/--pop-state");
1107         break;
1108       }
1109       std::tie(Config->AsNeeded, Config->Static, InWholeArchive) = Stack.back();
1110       Stack.pop_back();
1111       break;
1112     }
1113   }
1114
1115   if (Files.empty() && errorCount() == 0)
1116     error("no input files");
1117 }
1118
1119 // If -m <machine_type> was not given, infer it from object files.
1120 void LinkerDriver::inferMachineType() {
1121   if (Config->EKind != ELFNoneKind)
1122     return;
1123
1124   for (InputFile *F : Files) {
1125     if (F->EKind == ELFNoneKind)
1126       continue;
1127     Config->EKind = F->EKind;
1128     Config->EMachine = F->EMachine;
1129     Config->OSABI = F->OSABI;
1130     Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
1131     return;
1132   }
1133   error("target emulation unknown: -m or at least one .o file required");
1134 }
1135
1136 // Parse -z max-page-size=<value>. The default value is defined by
1137 // each target.
1138 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
1139   uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
1140                                        Target->DefaultMaxPageSize);
1141   if (!isPowerOf2_64(Val))
1142     error("max-page-size: value isn't a power of 2");
1143   return Val;
1144 }
1145
1146 // Parses -image-base option.
1147 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
1148   // Because we are using "Config->MaxPageSize" here, this function has to be
1149   // called after the variable is initialized.
1150   auto *Arg = Args.getLastArg(OPT_image_base);
1151   if (!Arg)
1152     return None;
1153
1154   StringRef S = Arg->getValue();
1155   uint64_t V;
1156   if (!to_integer(S, V)) {
1157     error("-image-base: number expected, but got " + S);
1158     return 0;
1159   }
1160   if ((V % Config->MaxPageSize) != 0)
1161     warn("-image-base: address isn't multiple of page size: " + S);
1162   return V;
1163 }
1164
1165 // Parses `--exclude-libs=lib,lib,...`.
1166 // The library names may be delimited by commas or colons.
1167 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
1168   DenseSet<StringRef> Ret;
1169   for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
1170     StringRef S = Arg->getValue();
1171     for (;;) {
1172       size_t Pos = S.find_first_of(",:");
1173       if (Pos == StringRef::npos)
1174         break;
1175       Ret.insert(S.substr(0, Pos));
1176       S = S.substr(Pos + 1);
1177     }
1178     Ret.insert(S);
1179   }
1180   return Ret;
1181 }
1182
1183 // Handles the -exclude-libs option. If a static library file is specified
1184 // by the -exclude-libs option, all public symbols from the archive become
1185 // private unless otherwise specified by version scripts or something.
1186 // A special library name "ALL" means all archive files.
1187 //
1188 // This is not a popular option, but some programs such as bionic libc use it.
1189 template <class ELFT>
1190 static void excludeLibs(opt::InputArgList &Args) {
1191   DenseSet<StringRef> Libs = getExcludeLibs(Args);
1192   bool All = Libs.count("ALL");
1193
1194   auto Visit = [&](InputFile *File) {
1195     if (!File->ArchiveName.empty())
1196       if (All || Libs.count(path::filename(File->ArchiveName)))
1197         for (Symbol *Sym : File->getSymbols())
1198           if (!Sym->isLocal() && Sym->File == File)
1199             Sym->VersionId = VER_NDX_LOCAL;
1200   };
1201
1202   for (InputFile *File : ObjectFiles)
1203     Visit(File);
1204
1205   for (BitcodeFile *File : BitcodeFiles)
1206     Visit(File);
1207 }
1208
1209 // Force Sym to be entered in the output. Used for -u or equivalent.
1210 template <class ELFT> static void handleUndefined(StringRef Name) {
1211   Symbol *Sym = Symtab->find(Name);
1212   if (!Sym)
1213     return;
1214
1215   // Since symbol S may not be used inside the program, LTO may
1216   // eliminate it. Mark the symbol as "used" to prevent it.
1217   Sym->IsUsedInRegularObj = true;
1218
1219   if (Sym->isLazy())
1220     Symtab->fetchLazy<ELFT>(Sym);
1221 }
1222
1223 template <class ELFT> static bool shouldDemote(Symbol &Sym) {
1224   // If all references to a DSO happen to be weak, the DSO is not added to
1225   // DT_NEEDED. If that happens, we need to eliminate shared symbols created
1226   // from the DSO. Otherwise, they become dangling references that point to a
1227   // non-existent DSO.
1228   if (auto *S = dyn_cast<SharedSymbol>(&Sym))
1229     return !S->getFile<ELFT>().IsNeeded;
1230
1231   // We are done processing archives, so lazy symbols that were used but not
1232   // found can be converted to undefined. We could also just delete the other
1233   // lazy symbols, but that seems to be more work than it is worth.
1234   return Sym.isLazy() && Sym.IsUsedInRegularObj;
1235 }
1236
1237 // Some files, such as .so or files between -{start,end}-lib may be removed
1238 // after their symbols are added to the symbol table. If that happens, we
1239 // need to remove symbols that refer files that no longer exist, so that
1240 // they won't appear in the symbol table of the output file.
1241 //
1242 // We remove symbols by demoting them to undefined symbol.
1243 template <class ELFT> static void demoteSymbols() {
1244   for (Symbol *Sym : Symtab->getSymbols()) {
1245     if (shouldDemote<ELFT>(*Sym)) {
1246       bool Used = Sym->Used;
1247       replaceSymbol<Undefined>(Sym, nullptr, Sym->getName(), Sym->Binding,
1248                                Sym->StOther, Sym->Type);
1249       Sym->Used = Used;
1250     }
1251   }
1252 }
1253
1254 // The section referred to by S is considered address-significant. Set the
1255 // KeepUnique flag on the section if appropriate.
1256 static void markAddrsig(Symbol *S) {
1257   if (auto *D = dyn_cast_or_null<Defined>(S))
1258     if (D->Section)
1259       // We don't need to keep text sections unique under --icf=all even if they
1260       // are address-significant.
1261       if (Config->ICF == ICFLevel::Safe || !(D->Section->Flags & SHF_EXECINSTR))
1262         D->Section->KeepUnique = true;
1263 }
1264
1265 // Record sections that define symbols mentioned in --keep-unique <symbol>
1266 // and symbols referred to by address-significance tables. These sections are
1267 // ineligible for ICF.
1268 template <class ELFT>
1269 static void findKeepUniqueSections(opt::InputArgList &Args) {
1270   for (auto *Arg : Args.filtered(OPT_keep_unique)) {
1271     StringRef Name = Arg->getValue();
1272     auto *D = dyn_cast_or_null<Defined>(Symtab->find(Name));
1273     if (!D || !D->Section) {
1274       warn("could not find symbol " + Name + " to keep unique");
1275       continue;
1276     }
1277     D->Section->KeepUnique = true;
1278   }
1279
1280   // --icf=all --ignore-data-address-equality means that we can ignore
1281   // the dynsym and address-significance tables entirely.
1282   if (Config->ICF == ICFLevel::All && Config->IgnoreDataAddressEquality)
1283     return;
1284
1285   // Symbols in the dynsym could be address-significant in other executables
1286   // or DSOs, so we conservatively mark them as address-significant.
1287   for (Symbol *S : Symtab->getSymbols())
1288     if (S->includeInDynsym())
1289       markAddrsig(S);
1290
1291   // Visit the address-significance table in each object file and mark each
1292   // referenced symbol as address-significant.
1293   for (InputFile *F : ObjectFiles) {
1294     auto *Obj = cast<ObjFile<ELFT>>(F);
1295     ArrayRef<Symbol *> Syms = Obj->getSymbols();
1296     if (Obj->AddrsigSec) {
1297       ArrayRef<uint8_t> Contents =
1298           check(Obj->getObj().getSectionContents(Obj->AddrsigSec));
1299       const uint8_t *Cur = Contents.begin();
1300       while (Cur != Contents.end()) {
1301         unsigned Size;
1302         const char *Err;
1303         uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
1304         if (Err)
1305           fatal(toString(F) + ": could not decode addrsig section: " + Err);
1306         markAddrsig(Syms[SymIndex]);
1307         Cur += Size;
1308       }
1309     } else {
1310       // If an object file does not have an address-significance table,
1311       // conservatively mark all of its symbols as address-significant.
1312       for (Symbol *S : Syms)
1313         markAddrsig(S);
1314     }
1315   }
1316 }
1317
1318 static const char *LibcallRoutineNames[] = {
1319 #define HANDLE_LIBCALL(code, name) name,
1320 #include "llvm/IR/RuntimeLibcalls.def"
1321 #undef HANDLE_LIBCALL
1322 };
1323
1324 // Do actual linking. Note that when this function is called,
1325 // all linker scripts have already been parsed.
1326 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1327   Target = getTarget();
1328
1329   Config->MaxPageSize = getMaxPageSize(Args);
1330   Config->ImageBase = getImageBase(Args);
1331
1332   // If a -hash-style option was not given, set to a default value,
1333   // which varies depending on the target.
1334   if (!Args.hasArg(OPT_hash_style)) {
1335     if (Config->EMachine == EM_MIPS)
1336       Config->SysvHash = true;
1337     else
1338       Config->SysvHash = Config->GnuHash = true;
1339   }
1340
1341   // Default output filename is "a.out" by the Unix tradition.
1342   if (Config->OutputFile.empty())
1343     Config->OutputFile = "a.out";
1344
1345   // Fail early if the output file or map file is not writable. If a user has a
1346   // long link, e.g. due to a large LTO link, they do not wish to run it and
1347   // find that it failed because there was a mistake in their command-line.
1348   if (auto E = tryCreateFile(Config->OutputFile))
1349     error("cannot open output file " + Config->OutputFile + ": " + E.message());
1350   if (auto E = tryCreateFile(Config->MapFile))
1351     error("cannot open map file " + Config->MapFile + ": " + E.message());
1352   if (errorCount())
1353     return;
1354
1355   // Use default entry point name if no name was given via the command
1356   // line nor linker scripts. For some reason, MIPS entry point name is
1357   // different from others.
1358   Config->WarnMissingEntry =
1359       (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
1360   if (Config->Entry.empty() && !Config->Relocatable)
1361     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
1362
1363   // Handle --trace-symbol.
1364   for (auto *Arg : Args.filtered(OPT_trace_symbol))
1365     Symtab->trace(Arg->getValue());
1366
1367   // Add all files to the symbol table. This will add almost all
1368   // symbols that we need to the symbol table.
1369   for (InputFile *F : Files)
1370     Symtab->addFile<ELFT>(F);
1371
1372   // Now that we have every file, we can decide if we will need a
1373   // dynamic symbol table.
1374   // We need one if we were asked to export dynamic symbols or if we are
1375   // producing a shared library.
1376   // We also need one if any shared libraries are used and for pie executables
1377   // (probably because the dynamic linker needs it).
1378   Config->HasDynSymTab =
1379       !SharedFiles.empty() || Config->Pic || Config->ExportDynamic;
1380
1381   // Some symbols (such as __ehdr_start) are defined lazily only when there
1382   // are undefined symbols for them, so we add these to trigger that logic.
1383   for (StringRef Sym : Script->ReferencedSymbols)
1384     Symtab->addUndefined<ELFT>(Sym);
1385
1386   // Handle the `--undefined <sym>` options.
1387   for (StringRef S : Config->Undefined)
1388     handleUndefined<ELFT>(S);
1389
1390   // If an entry symbol is in a static archive, pull out that file now.
1391   handleUndefined<ELFT>(Config->Entry);
1392
1393   // If any of our inputs are bitcode files, the LTO code generator may create
1394   // references to certain library functions that might not be explicit in the
1395   // bitcode file's symbol table. If any of those library functions are defined
1396   // in a bitcode file in an archive member, we need to arrange to use LTO to
1397   // compile those archive members by adding them to the link beforehand.
1398   //
1399   // With this the symbol table should be complete. After this, no new names
1400   // except a few linker-synthesized ones will be added to the symbol table.
1401   if (!BitcodeFiles.empty())
1402     for (const char *S : LibcallRoutineNames)
1403       handleUndefined<ELFT>(S);
1404
1405   // Return if there were name resolution errors.
1406   if (errorCount())
1407     return;
1408
1409   // Now when we read all script files, we want to finalize order of linker
1410   // script commands, which can be not yet final because of INSERT commands.
1411   Script->processInsertCommands();
1412
1413   // We want to declare linker script's symbols early,
1414   // so that we can version them.
1415   // They also might be exported if referenced by DSOs.
1416   Script->declareSymbols();
1417
1418   // Handle the -exclude-libs option.
1419   if (Args.hasArg(OPT_exclude_libs))
1420     excludeLibs<ELFT>(Args);
1421
1422   // Create ElfHeader early. We need a dummy section in
1423   // addReservedSymbols to mark the created symbols as not absolute.
1424   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1425   Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1426
1427   // We need to create some reserved symbols such as _end. Create them.
1428   if (!Config->Relocatable)
1429     addReservedSymbols();
1430
1431   // Apply version scripts.
1432   //
1433   // For a relocatable output, version scripts don't make sense, and
1434   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1435   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1436   if (!Config->Relocatable)
1437     Symtab->scanVersionScript();
1438
1439   // Create wrapped symbols for -wrap option.
1440   for (auto *Arg : Args.filtered(OPT_wrap))
1441     Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1442
1443   // Do link-time optimization if given files are LLVM bitcode files.
1444   // This compiles bitcode files into real object files.
1445   Symtab->addCombinedLTOObject<ELFT>();
1446   if (errorCount())
1447     return;
1448
1449   // If -thinlto-index-only is given, we should create only "index
1450   // files" and not object files. Index file creation is already done
1451   // in addCombinedLTOObject, so we are done if that's the case.
1452   if (Config->ThinLTOIndexOnly)
1453     return;
1454
1455   // Apply symbol renames for -wrap.
1456   Symtab->applySymbolWrap();
1457
1458   // Now that we have a complete list of input files.
1459   // Beyond this point, no new files are added.
1460   // Aggregate all input sections into one place.
1461   for (InputFile *F : ObjectFiles)
1462     for (InputSectionBase *S : F->getSections())
1463       if (S && S != &InputSection::Discarded)
1464         InputSections.push_back(S);
1465   for (BinaryFile *F : BinaryFiles)
1466     for (InputSectionBase *S : F->getSections())
1467       InputSections.push_back(cast<InputSection>(S));
1468
1469   // We do not want to emit debug sections if --strip-all
1470   // or -strip-debug are given.
1471   if (Config->Strip != StripPolicy::None)
1472     llvm::erase_if(InputSections, [](InputSectionBase *S) {
1473       return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1474     });
1475
1476   Config->EFlags = Target->calcEFlags();
1477
1478   if (Config->EMachine == EM_ARM) {
1479     // FIXME: These warnings can be removed when lld only uses these features
1480     // when the input objects have been compiled with an architecture that
1481     // supports them.
1482     if (Config->ARMHasBlx == false)
1483       warn("lld uses blx instruction, no object with architecture supporting "
1484            "feature detected.");
1485     if (Config->ARMJ1J2BranchEncoding == false)
1486       warn("lld uses extended branch encoding, no object with architecture "
1487            "supporting feature detected.");
1488     if (Config->ARMHasMovtMovw == false)
1489       warn("lld may use movt/movw, no object with architecture supporting "
1490            "feature detected.");
1491   }
1492
1493   // This adds a .comment section containing a version string. We have to add it
1494   // before decompressAndMergeSections because the .comment section is a
1495   // mergeable section.
1496   if (!Config->Relocatable)
1497     InputSections.push_back(createCommentSection());
1498
1499   // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1500   // and identical code folding.
1501   decompressSections();
1502   splitSections<ELFT>();
1503   markLive<ELFT>();
1504   demoteSymbols<ELFT>();
1505   mergeSections();
1506   if (Config->ICF != ICFLevel::None) {
1507     findKeepUniqueSections<ELFT>(Args);
1508     doIcf<ELFT>();
1509   }
1510
1511   // Read the callgraph now that we know what was gced or icfed
1512   if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1513     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1514       readCallGraph(*Buffer);
1515
1516   // Write the result to the file.
1517   writeResult<ELFT>();
1518 }