1 //===- InputFiles.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 "InputFiles.h"
11 #include "Driver.h"
12 #include "ELFCreator.h"
13 #include "Error.h"
14 #include "InputSection.h"
15 #include "LinkerScript.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/MC/StringTableBuilder.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/raw_ostream.h"
27 
28 using namespace llvm;
29 using namespace llvm::ELF;
30 using namespace llvm::object;
31 using namespace llvm::sys::fs;
32 
33 using namespace lld;
34 using namespace lld::elf;
35 
36 std::vector<InputFile *> InputFile::Pool;
37 
38 // Deletes all InputFile instances created so far.
39 void InputFile::freePool() {
40   // Files are freed in reverse order so that files created
41   // from other files (e.g. object files extracted from archives)
42   // are freed in the proper order.
43   for (int I = Pool.size() - 1; I >= 0; --I)
44     delete Pool[I];
45 }
46 
47 // Returns "(internal)", "foo.a(bar.o)" or "baz.o".
48 std::string elf::getFilename(const InputFile *F) {
49   if (!F)
50     return "(internal)";
51   if (!F->ArchiveName.empty())
52     return (F->ArchiveName + "(" + F->getName() + ")").str();
53   return F->getName();
54 }
55 
56 template <class ELFT> static ELFFile<ELFT> createELFObj(MemoryBufferRef MB) {
57   std::error_code EC;
58   ELFFile<ELFT> F(MB.getBuffer(), EC);
59   if (EC)
60     fatal(EC, "failed to read " + MB.getBufferIdentifier());
61   return F;
62 }
63 
64 template <class ELFT> static ELFKind getELFKind() {
65   if (ELFT::TargetEndianness == support::little)
66     return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
67   return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
68 }
69 
70 template <class ELFT>
71 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB)
72     : InputFile(K, MB), ELFObj(createELFObj<ELFT>(MB)) {
73   EKind = getELFKind<ELFT>();
74   EMachine = ELFObj.getHeader()->e_machine;
75 }
76 
77 template <class ELFT>
78 typename ELFT::SymRange ELFFileBase<ELFT>::getElfSymbols(bool OnlyGlobals) {
79   if (!Symtab)
80     return Elf_Sym_Range(nullptr, nullptr);
81   Elf_Sym_Range Syms = ELFObj.symbols(Symtab);
82   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
83   uint32_t FirstNonLocal = Symtab->sh_info;
84   if (FirstNonLocal == 0 || FirstNonLocal > NumSymbols)
85     fatal(getFilename(this) + ": invalid sh_info in symbol table");
86 
87   if (OnlyGlobals)
88     return makeArrayRef(Syms.begin() + FirstNonLocal, Syms.end());
89   return makeArrayRef(Syms.begin(), Syms.end());
90 }
91 
92 template <class ELFT>
93 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
94   uint32_t I = Sym.st_shndx;
95   if (I == ELF::SHN_XINDEX)
96     return ELFObj.getExtendedSymbolTableIndex(&Sym, Symtab, SymtabSHNDX);
97   if (I >= ELF::SHN_LORESERVE)
98     return 0;
99   return I;
100 }
101 
102 template <class ELFT> void ELFFileBase<ELFT>::initStringTable() {
103   if (!Symtab)
104     return;
105   StringTable = check(ELFObj.getStringTableForSymtab(*Symtab));
106 }
107 
108 template <class ELFT>
109 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)
110     : ELFFileBase<ELFT>(Base::ObjectKind, M) {}
111 
112 template <class ELFT>
113 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getNonLocalSymbols() {
114   if (!this->Symtab)
115     return this->SymbolBodies;
116   uint32_t FirstNonLocal = this->Symtab->sh_info;
117   return makeArrayRef(this->SymbolBodies).slice(FirstNonLocal);
118 }
119 
120 template <class ELFT>
121 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
122   if (!this->Symtab)
123     return this->SymbolBodies;
124   uint32_t FirstNonLocal = this->Symtab->sh_info;
125   return makeArrayRef(this->SymbolBodies).slice(1, FirstNonLocal - 1);
126 }
127 
128 template <class ELFT>
129 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
130   if (!this->Symtab)
131     return this->SymbolBodies;
132   return makeArrayRef(this->SymbolBodies).slice(1);
133 }
134 
135 template <class ELFT> uint32_t elf::ObjectFile<ELFT>::getMipsGp0() const {
136   if (ELFT::Is64Bits && MipsOptions && MipsOptions->Reginfo)
137     return MipsOptions->Reginfo->ri_gp_value;
138   if (!ELFT::Is64Bits && MipsReginfo && MipsReginfo->Reginfo)
139     return MipsReginfo->Reginfo->ri_gp_value;
140   return 0;
141 }
142 
143 template <class ELFT>
144 void elf::ObjectFile<ELFT>::parse(DenseSet<StringRef> &ComdatGroups) {
145   // Read section and symbol tables.
146   initializeSections(ComdatGroups);
147   initializeSymbols();
148   if (Config->GcSections && Config->EMachine == EM_ARM)
149     initializeReverseDependencies();
150 }
151 
152 // Sections with SHT_GROUP and comdat bits define comdat section groups.
153 // They are identified and deduplicated by group name. This function
154 // returns a group name.
155 template <class ELFT>
156 StringRef elf::ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) {
157   const ELFFile<ELFT> &Obj = this->ELFObj;
158   const Elf_Shdr *Symtab = check(Obj.getSection(Sec.sh_link));
159   const Elf_Sym *Sym = Obj.getSymbol(Symtab, Sec.sh_info);
160   StringRef Strtab = check(Obj.getStringTableForSymtab(*Symtab));
161   return check(Sym->getName(Strtab));
162 }
163 
164 template <class ELFT>
165 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
166 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
167   const ELFFile<ELFT> &Obj = this->ELFObj;
168   ArrayRef<Elf_Word> Entries =
169       check(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec));
170   if (Entries.empty() || Entries[0] != GRP_COMDAT)
171     fatal(getFilename(this) + ": unsupported SHT_GROUP format");
172   return Entries.slice(1);
173 }
174 
175 template <class ELFT>
176 bool elf::ObjectFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
177   // We don't merge sections if -O0 (default is -O1). This makes sometimes
178   // the linker significantly faster, although the output will be bigger.
179   if (Config->Optimize == 0)
180     return false;
181 
182   // Do not merge sections if generating a relocatable object. It makes
183   // the code simpler because we do not need to update relocation addends
184   // to reflect changes introduced by merging. Instead of that we write
185   // such "merge" sections into separate OutputSections and keep SHF_MERGE
186   // / SHF_STRINGS flags and sh_entsize value to be able to perform merging
187   // later during a final linking.
188   if (Config->Relocatable)
189     return false;
190 
191   // A mergeable section with size 0 is useless because they don't have
192   // any data to merge. A mergeable string section with size 0 can be
193   // argued as invalid because it doesn't end with a null character.
194   // We'll avoid a mess by handling them as if they were non-mergeable.
195   if (Sec.sh_size == 0)
196     return false;
197 
198   // Check for sh_entsize. The ELF spec is not clear about the zero
199   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
200   // the section does not hold a table of fixed-size entries". We know
201   // that Rust 1.13 produces a string mergeable section with a zero
202   // sh_entsize. Here we just accept it rather than being picky about it.
203   uintX_t EntSize = Sec.sh_entsize;
204   if (EntSize == 0)
205     return false;
206   if (Sec.sh_size % EntSize)
207     fatal(getFilename(this) +
208           ": SHF_MERGE section size must be a multiple of sh_entsize");
209 
210   uintX_t Flags = Sec.sh_flags;
211   if (!(Flags & SHF_MERGE))
212     return false;
213   if (Flags & SHF_WRITE)
214     fatal(getFilename(this) + ": writable SHF_MERGE section is not supported");
215 
216   // Don't try to merge if the alignment is larger than the sh_entsize and this
217   // is not SHF_STRINGS.
218   //
219   // Since this is not a SHF_STRINGS, we would need to pad after every entity.
220   // It would be equivalent for the producer of the .o to just set a larger
221   // sh_entsize.
222   if (Flags & SHF_STRINGS)
223     return true;
224 
225   return Sec.sh_addralign <= EntSize;
226 }
227 
228 template <class ELFT>
229 void elf::ObjectFile<ELFT>::initializeSections(
230     DenseSet<StringRef> &ComdatGroups) {
231   uint64_t Size = this->ELFObj.getNumSections();
232   Sections.resize(Size);
233   unsigned I = -1;
234   const ELFFile<ELFT> &Obj = this->ELFObj;
235   for (const Elf_Shdr &Sec : Obj.sections()) {
236     ++I;
237     if (Sections[I] == &InputSection<ELFT>::Discarded)
238       continue;
239 
240     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
241     // if -r is given, we'll let the final link discard such sections.
242     // This is compatible with GNU.
243     if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
244       Sections[I] = &InputSection<ELFT>::Discarded;
245       continue;
246     }
247 
248     switch (Sec.sh_type) {
249     case SHT_GROUP:
250       Sections[I] = &InputSection<ELFT>::Discarded;
251       if (ComdatGroups.insert(getShtGroupSignature(Sec)).second)
252         continue;
253       for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
254         if (SecIndex >= Size)
255           fatal(getFilename(this) + ": invalid section index in group: " +
256                 Twine(SecIndex));
257         Sections[SecIndex] = &InputSection<ELFT>::Discarded;
258       }
259       break;
260     case SHT_SYMTAB:
261       this->Symtab = &Sec;
262       break;
263     case SHT_SYMTAB_SHNDX:
264       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
265       break;
266     case SHT_STRTAB:
267     case SHT_NULL:
268       break;
269     default:
270       Sections[I] = createInputSection(Sec);
271     }
272   }
273 }
274 
275 // .ARM.exidx sections have a reverse dependency on the InputSection they
276 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
277 template <class ELFT>
278 void elf::ObjectFile<ELFT>::initializeReverseDependencies() {
279   unsigned I = -1;
280   for (const Elf_Shdr &Sec : this->ELFObj.sections()) {
281     ++I;
282     if ((Sections[I] == &InputSection<ELFT>::Discarded) ||
283         !(Sec.sh_flags & SHF_LINK_ORDER))
284       continue;
285     if (Sec.sh_link >= Sections.size())
286       fatal(getFilename(this) + ": invalid sh_link index: " +
287             Twine(Sec.sh_link));
288     auto *IS = cast<InputSection<ELFT>>(Sections[Sec.sh_link]);
289     IS->DependentSection = Sections[I];
290   }
291 }
292 
293 template <class ELFT>
294 InputSectionBase<ELFT> *
295 elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
296   uint32_t Idx = Sec.sh_info;
297   if (Idx >= Sections.size())
298     fatal(getFilename(this) + ": invalid relocated section index: " +
299           Twine(Idx));
300   InputSectionBase<ELFT> *Target = Sections[Idx];
301 
302   // Strictly speaking, a relocation section must be included in the
303   // group of the section it relocates. However, LLVM 3.3 and earlier
304   // would fail to do so, so we gracefully handle that case.
305   if (Target == &InputSection<ELFT>::Discarded)
306     return nullptr;
307 
308   if (!Target)
309     fatal(getFilename(this) + ": unsupported relocation reference");
310   return Target;
311 }
312 
313 template <class ELFT>
314 InputSectionBase<ELFT> *
315 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
316   StringRef Name = check(this->ELFObj.getSectionName(&Sec));
317 
318   switch (Sec.sh_type) {
319   case SHT_ARM_ATTRIBUTES:
320     // FIXME: ARM meta-data section. At present attributes are ignored,
321     // they can be used to reason about object compatibility.
322     return &InputSection<ELFT>::Discarded;
323   case SHT_MIPS_REGINFO:
324     MipsReginfo.reset(new MipsReginfoInputSection<ELFT>(this, &Sec, Name));
325     return MipsReginfo.get();
326   case SHT_MIPS_OPTIONS:
327     MipsOptions.reset(new MipsOptionsInputSection<ELFT>(this, &Sec, Name));
328     return MipsOptions.get();
329   case SHT_MIPS_ABIFLAGS:
330     MipsAbiFlags.reset(new MipsAbiFlagsInputSection<ELFT>(this, &Sec, Name));
331     return MipsAbiFlags.get();
332   case SHT_RELA:
333   case SHT_REL: {
334     // This section contains relocation information.
335     // If -r is given, we do not interpret or apply relocation
336     // but just copy relocation sections to output.
337     if (Config->Relocatable)
338       return new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec, Name);
339 
340     // Find the relocation target section and associate this
341     // section with it.
342     InputSectionBase<ELFT> *Target = getRelocTarget(Sec);
343     if (!Target)
344       return nullptr;
345     if (auto *S = dyn_cast<InputSection<ELFT>>(Target)) {
346       S->RelocSections.push_back(&Sec);
347       return nullptr;
348     }
349     if (auto *S = dyn_cast<EhInputSection<ELFT>>(Target)) {
350       if (S->RelocSection)
351         fatal(getFilename(this) +
352               ": multiple relocation sections to .eh_frame are not supported");
353       S->RelocSection = &Sec;
354       return nullptr;
355     }
356     fatal(getFilename(this) +
357           ": relocations pointing to SHF_MERGE are not supported");
358   }
359   }
360 
361   // .note.GNU-stack is a marker section to control the presence of
362   // PT_GNU_STACK segment in outputs. Since the presence of the segment
363   // is controlled only by the command line option (-z execstack) in LLD,
364   // .note.GNU-stack is ignored.
365   if (Name == ".note.GNU-stack")
366     return &InputSection<ELFT>::Discarded;
367 
368   if (Name == ".note.GNU-split-stack") {
369     error("objects using splitstacks are not supported");
370     return &InputSection<ELFT>::Discarded;
371   }
372 
373   if (Config->Strip != StripPolicy::None && Name.startswith(".debug"))
374     return &InputSection<ELFT>::Discarded;
375 
376   // The linker merges EH (exception handling) frames and creates a
377   // .eh_frame_hdr section for runtime. So we handle them with a special
378   // class. For relocatable outputs, they are just passed through.
379   if (Name == ".eh_frame" && !Config->Relocatable)
380     return new (EHAlloc.Allocate()) EhInputSection<ELFT>(this, &Sec, Name);
381 
382   if (shouldMerge(Sec))
383     return new (MAlloc.Allocate()) MergeInputSection<ELFT>(this, &Sec, Name);
384   return new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec, Name);
385 }
386 
387 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
388   this->initStringTable();
389   Elf_Sym_Range Syms = this->getElfSymbols(false);
390   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
391   SymbolBodies.reserve(NumSymbols);
392   for (const Elf_Sym &Sym : Syms)
393     SymbolBodies.push_back(createSymbolBody(&Sym));
394 }
395 
396 template <class ELFT>
397 InputSectionBase<ELFT> *
398 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
399   uint32_t Index = this->getSectionIndex(Sym);
400   if (Index >= Sections.size())
401     fatal(getFilename(this) + ": invalid section index: " + Twine(Index));
402   InputSectionBase<ELFT> *S = Sections[Index];
403 
404   // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03
405   // could generate broken objects. STT_SECTION symbols can be
406   // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections.
407   // In this case it is fine for section to be null here as we
408   // do not allocate sections of these types.
409   if (!S) {
410     if (Index == 0 || Sym.getType() == STT_SECTION)
411       return nullptr;
412     fatal(getFilename(this) + ": invalid section index: " + Twine(Index));
413   }
414 
415   if (S == &InputSectionBase<ELFT>::Discarded)
416     return S;
417   return S->Repl;
418 }
419 
420 template <class ELFT>
421 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
422   int Binding = Sym->getBinding();
423   InputSectionBase<ELFT> *Sec = getSection(*Sym);
424   if (Binding == STB_LOCAL) {
425     if (Sym->st_shndx == SHN_UNDEF)
426       return new (this->Alloc)
427           Undefined(Sym->st_name, Sym->st_other, Sym->getType(), this);
428     return new (this->Alloc) DefinedRegular<ELFT>(*Sym, Sec);
429   }
430 
431   StringRef Name = check(Sym->getName(this->StringTable));
432 
433   switch (Sym->st_shndx) {
434   case SHN_UNDEF:
435     return elf::Symtab<ELFT>::X->addUndefined(Name, Binding, Sym->st_other,
436                                               Sym->getType(),
437                                               /*CanOmitFromDynSym*/ false, this)
438         ->body();
439   case SHN_COMMON:
440     if (Sym->st_value == 0 || Sym->st_value >= UINT32_MAX)
441       fatal(getFilename(this) + ": common symbol '" + Name +
442             "' has invalid alignment: " + Twine(Sym->st_value));
443     return elf::Symtab<ELFT>::X->addCommon(Name, Sym->st_size, Sym->st_value,
444                                            Binding, Sym->st_other,
445                                            Sym->getType(), this)
446         ->body();
447   }
448 
449   switch (Binding) {
450   default:
451     fatal(getFilename(this) + ": unexpected binding: " + Twine(Binding));
452   case STB_GLOBAL:
453   case STB_WEAK:
454   case STB_GNU_UNIQUE:
455     if (Sec == &InputSection<ELFT>::Discarded)
456       return elf::Symtab<ELFT>::X->addUndefined(Name, Binding, Sym->st_other,
457                                                 Sym->getType(),
458                                                 /*CanOmitFromDynSym*/ false,
459                                                 this)
460           ->body();
461     return elf::Symtab<ELFT>::X->addRegular(Name, *Sym, Sec)->body();
462   }
463 }
464 
465 template <class ELFT> void ArchiveFile::parse() {
466   File = check(Archive::create(MB), "failed to parse archive");
467 
468   // Read the symbol table to construct Lazy objects.
469   for (const Archive::Symbol &Sym : File->symbols())
470     Symtab<ELFT>::X->addLazyArchive(this, Sym);
471 }
472 
473 // Returns a buffer pointing to a member file containing a given symbol.
474 std::pair<MemoryBufferRef, uint64_t>
475 ArchiveFile::getMember(const Archive::Symbol *Sym) {
476   Archive::Child C =
477       check(Sym->getMember(),
478             "could not get the member for symbol " + Sym->getName());
479 
480   if (!Seen.insert(C.getChildOffset()).second)
481     return {MemoryBufferRef(), 0};
482 
483   MemoryBufferRef Ret =
484       check(C.getMemoryBufferRef(),
485             "could not get the buffer for the member defining symbol " +
486                 Sym->getName());
487 
488   if (C.getParent()->isThin() && Driver->Cpio)
489     Driver->Cpio->append(relativeToRoot(check(C.getFullName())),
490                          Ret.getBuffer());
491   if (C.getParent()->isThin())
492     return {Ret, 0};
493   return {Ret, C.getChildOffset()};
494 }
495 
496 template <class ELFT>
497 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
498     : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
499 
500 template <class ELFT>
501 const typename ELFT::Shdr *
502 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
503   uint32_t Index = this->getSectionIndex(Sym);
504   if (Index == 0)
505     return nullptr;
506   return check(this->ELFObj.getSection(Index));
507 }
508 
509 // Partially parse the shared object file so that we can call
510 // getSoName on this object.
511 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
512   typedef typename ELFT::Dyn Elf_Dyn;
513   typedef typename ELFT::uint uintX_t;
514   const Elf_Shdr *DynamicSec = nullptr;
515 
516   const ELFFile<ELFT> Obj = this->ELFObj;
517   for (const Elf_Shdr &Sec : Obj.sections()) {
518     switch (Sec.sh_type) {
519     default:
520       continue;
521     case SHT_DYNSYM:
522       this->Symtab = &Sec;
523       break;
524     case SHT_DYNAMIC:
525       DynamicSec = &Sec;
526       break;
527     case SHT_SYMTAB_SHNDX:
528       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
529       break;
530     case SHT_GNU_versym:
531       this->VersymSec = &Sec;
532       break;
533     case SHT_GNU_verdef:
534       this->VerdefSec = &Sec;
535       break;
536     }
537   }
538 
539   this->initStringTable();
540 
541   // DSOs are identified by soname, and they usually contain
542   // DT_SONAME tag in their header. But if they are missing,
543   // filenames are used as default sonames.
544   SoName = sys::path::filename(this->getName());
545 
546   if (!DynamicSec)
547     return;
548 
549   ArrayRef<Elf_Dyn> Arr =
550       check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
551             getFilename(this) + ": getSectionContentsAsArray failed");
552   for (const Elf_Dyn &Dyn : Arr) {
553     if (Dyn.d_tag == DT_SONAME) {
554       uintX_t Val = Dyn.getVal();
555       if (Val >= this->StringTable.size())
556         fatal(getFilename(this) + ": invalid DT_SONAME entry");
557       SoName = StringRef(this->StringTable.data() + Val);
558       return;
559     }
560   }
561 }
562 
563 // Parse the version definitions in the object file if present. Returns a vector
564 // whose nth element contains a pointer to the Elf_Verdef for version identifier
565 // n. Version identifiers that are not definitions map to nullptr. The array
566 // always has at least length 1.
567 template <class ELFT>
568 std::vector<const typename ELFT::Verdef *>
569 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
570   std::vector<const Elf_Verdef *> Verdefs(1);
571   // We only need to process symbol versions for this DSO if it has both a
572   // versym and a verdef section, which indicates that the DSO contains symbol
573   // version definitions.
574   if (!VersymSec || !VerdefSec)
575     return Verdefs;
576 
577   // The location of the first global versym entry.
578   Versym = reinterpret_cast<const Elf_Versym *>(this->ELFObj.base() +
579                                                 VersymSec->sh_offset) +
580            this->Symtab->sh_info;
581 
582   // We cannot determine the largest verdef identifier without inspecting
583   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
584   // sequentially starting from 1, so we predict that the largest identifier
585   // will be VerdefCount.
586   unsigned VerdefCount = VerdefSec->sh_info;
587   Verdefs.resize(VerdefCount + 1);
588 
589   // Build the Verdefs array by following the chain of Elf_Verdef objects
590   // from the start of the .gnu.version_d section.
591   const uint8_t *Verdef = this->ELFObj.base() + VerdefSec->sh_offset;
592   for (unsigned I = 0; I != VerdefCount; ++I) {
593     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
594     Verdef += CurVerdef->vd_next;
595     unsigned VerdefIndex = CurVerdef->vd_ndx;
596     if (Verdefs.size() <= VerdefIndex)
597       Verdefs.resize(VerdefIndex + 1);
598     Verdefs[VerdefIndex] = CurVerdef;
599   }
600 
601   return Verdefs;
602 }
603 
604 // Fully parse the shared object file. This must be called after parseSoName().
605 template <class ELFT> void SharedFile<ELFT>::parseRest() {
606   // Create mapping from version identifiers to Elf_Verdef entries.
607   const Elf_Versym *Versym = nullptr;
608   std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
609 
610   Elf_Sym_Range Syms = this->getElfSymbols(true);
611   for (const Elf_Sym &Sym : Syms) {
612     unsigned VersymIndex = 0;
613     if (Versym) {
614       VersymIndex = Versym->vs_index;
615       ++Versym;
616     }
617 
618     StringRef Name = check(Sym.getName(this->StringTable));
619     if (Sym.isUndefined()) {
620       Undefs.push_back(Name);
621       continue;
622     }
623 
624     if (Versym) {
625       // Ignore local symbols and non-default versions.
626       if (VersymIndex == VER_NDX_LOCAL || (VersymIndex & VERSYM_HIDDEN))
627         continue;
628     }
629 
630     const Elf_Verdef *V =
631         VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
632     elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
633   }
634 }
635 
636 static ELFKind getBitcodeELFKind(MemoryBufferRef MB) {
637   Triple T(getBitcodeTargetTriple(MB, Driver->Context));
638   if (T.isLittleEndian())
639     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
640   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
641 }
642 
643 static uint8_t getBitcodeMachineKind(MemoryBufferRef MB) {
644   Triple T(getBitcodeTargetTriple(MB, Driver->Context));
645   switch (T.getArch()) {
646   case Triple::aarch64:
647     return EM_AARCH64;
648   case Triple::arm:
649     return EM_ARM;
650   case Triple::mips:
651   case Triple::mipsel:
652   case Triple::mips64:
653   case Triple::mips64el:
654     return EM_MIPS;
655   case Triple::ppc:
656     return EM_PPC;
657   case Triple::ppc64:
658     return EM_PPC64;
659   case Triple::x86:
660     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
661   case Triple::x86_64:
662     return EM_X86_64;
663   default:
664     fatal(MB.getBufferIdentifier() +
665           ": could not infer e_machine from bitcode target triple " + T.str());
666   }
667 }
668 
669 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) {
670   EKind = getBitcodeELFKind(MB);
671   EMachine = getBitcodeMachineKind(MB);
672 }
673 
674 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
675   switch (GvVisibility) {
676   case GlobalValue::DefaultVisibility:
677     return STV_DEFAULT;
678   case GlobalValue::HiddenVisibility:
679     return STV_HIDDEN;
680   case GlobalValue::ProtectedVisibility:
681     return STV_PROTECTED;
682   }
683   llvm_unreachable("unknown visibility");
684 }
685 
686 template <class ELFT>
687 static Symbol *createBitcodeSymbol(const DenseSet<const Comdat *> &KeptComdats,
688                                    const lto::InputFile::Symbol &ObjSym,
689                                    StringSaver &Saver, BitcodeFile *F) {
690   StringRef NameRef = Saver.save(ObjSym.getName());
691   uint32_t Flags = ObjSym.getFlags();
692   uint32_t Binding = (Flags & BasicSymbolRef::SF_Weak) ? STB_WEAK : STB_GLOBAL;
693 
694   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
695   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
696   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
697 
698   if (const Comdat *C = check(ObjSym.getComdat()))
699     if (!KeptComdats.count(C))
700       return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
701                                            CanOmitFromDynSym, F);
702 
703   if (Flags & BasicSymbolRef::SF_Undefined)
704     return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
705                                          CanOmitFromDynSym, F);
706 
707   if (Flags & BasicSymbolRef::SF_Common)
708     return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(),
709                                       ObjSym.getCommonAlignment(), Binding,
710                                       Visibility, STT_OBJECT, F);
711 
712   return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type,
713                                      CanOmitFromDynSym, F);
714 }
715 
716 template <class ELFT>
717 void BitcodeFile::parse(DenseSet<StringRef> &ComdatGroups) {
718 
719   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
720   // (the fully resolved path of the archive) + member name + offset of the
721   // member in the archive.
722   // ThinLTO uses the MemoryBufferRef identifier to access its internal
723   // data structures and if two archives define two members with the same name,
724   // this causes a collision which result in only one of the objects being
725   // taken into consideration at LTO time (which very likely causes undefined
726   // symbols later in the link stage).
727   Obj = check(lto::InputFile::create(MemoryBufferRef(
728       MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier() +
729                                  utostr(OffsetInArchive)))));
730   DenseSet<const Comdat *> KeptComdats;
731   for (const auto &P : Obj->getComdatSymbolTable()) {
732     StringRef N = Saver.save(P.first());
733     if (ComdatGroups.insert(N).second)
734       KeptComdats.insert(&P.second);
735   }
736 
737   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
738     Symbols.push_back(
739         createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, Saver, this));
740 }
741 
742 template <template <class> class T>
743 static InputFile *createELFFile(MemoryBufferRef MB) {
744   unsigned char Size;
745   unsigned char Endian;
746   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
747   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
748     fatal("invalid data encoding: " + MB.getBufferIdentifier());
749 
750   InputFile *Obj;
751   if (Size == ELFCLASS32 && Endian == ELFDATA2LSB)
752     Obj = new T<ELF32LE>(MB);
753   else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB)
754     Obj = new T<ELF32BE>(MB);
755   else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB)
756     Obj = new T<ELF64LE>(MB);
757   else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB)
758     Obj = new T<ELF64BE>(MB);
759   else
760     fatal("invalid file class: " + MB.getBufferIdentifier());
761 
762   if (!Config->FirstElf)
763     Config->FirstElf = Obj;
764   return Obj;
765 }
766 
767 // Wraps a binary blob with an ELF header and footer
768 // so that we can link it as a regular ELF file.
769 template <class ELFT> InputFile *BinaryFile::createELF() {
770   // Fill the ELF file header.
771   ELFCreator<ELFT> ELF(ET_REL, Config->EMachine);
772   auto DataSec = ELF.addSection(".data");
773   DataSec.Header->sh_flags = SHF_ALLOC;
774   DataSec.Header->sh_size = MB.getBufferSize();
775   DataSec.Header->sh_type = SHT_PROGBITS;
776   DataSec.Header->sh_addralign = 8;
777 
778   // Replace non-alphanumeric characters with '_'.
779   std::string Filepath = MB.getBufferIdentifier();
780   std::transform(Filepath.begin(), Filepath.end(), Filepath.begin(),
781                  [](char C) { return isalnum(C) ? C : '_'; });
782 
783   // Add _start, _end and _size symbols.
784   std::string StartSym = "_binary_" + Filepath + "_start";
785   auto SSym = ELF.addSymbol(StartSym);
786   SSym.Sym->setBindingAndType(STB_GLOBAL, STT_OBJECT);
787   SSym.Sym->st_shndx = DataSec.Index;
788 
789   std::string EndSym = "_binary_" + Filepath + "_end";
790   auto ESym = ELF.addSymbol(EndSym);
791   ESym.Sym->setBindingAndType(STB_GLOBAL, STT_OBJECT);
792   ESym.Sym->st_shndx = DataSec.Index;
793   ESym.Sym->st_value = MB.getBufferSize();
794 
795   std::string SizeSym = "_binary_" + Filepath + "_size";
796   auto SZSym = ELF.addSymbol(SizeSym);
797   SZSym.Sym->setBindingAndType(STB_GLOBAL, STT_OBJECT);
798   SZSym.Sym->st_shndx = SHN_ABS;
799   SZSym.Sym->st_value = MB.getBufferSize();
800 
801   // Fix the ELF file layout and write it down to ELFData uint8_t vector.
802   std::size_t Size = ELF.layout();
803   ELFData.resize(Size);
804   ELF.write(ELFData.data());
805 
806   // Fill .data section with actual data.
807   std::copy(MB.getBufferStart(), MB.getBufferEnd(),
808             ELFData.data() + DataSec.Header->sh_offset);
809 
810   return createELFFile<ObjectFile>(MemoryBufferRef(
811       StringRef((char *)ELFData.data(), Size), MB.getBufferIdentifier()));
812 }
813 
814 static bool isBitcode(MemoryBufferRef MB) {
815   using namespace sys::fs;
816   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
817 }
818 
819 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
820                                  uint64_t OffsetInArchive) {
821   InputFile *F =
822       isBitcode(MB) ? new BitcodeFile(MB) : createELFFile<ObjectFile>(MB);
823   F->ArchiveName = ArchiveName;
824   F->OffsetInArchive = OffsetInArchive;
825   return F;
826 }
827 
828 InputFile *elf::createSharedFile(MemoryBufferRef MB) {
829   return createELFFile<SharedFile>(MB);
830 }
831 
832 MemoryBufferRef LazyObjectFile::getBuffer() {
833   if (Seen)
834     return MemoryBufferRef();
835   Seen = true;
836   return MB;
837 }
838 
839 template <class ELFT> void LazyObjectFile::parse() {
840   for (StringRef Sym : getSymbols())
841     Symtab<ELFT>::X->addLazyObject(Sym, *this);
842 }
843 
844 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
845   typedef typename ELFT::Shdr Elf_Shdr;
846   typedef typename ELFT::Sym Elf_Sym;
847   typedef typename ELFT::SymRange Elf_Sym_Range;
848 
849   const ELFFile<ELFT> Obj = createELFObj<ELFT>(this->MB);
850   for (const Elf_Shdr &Sec : Obj.sections()) {
851     if (Sec.sh_type != SHT_SYMTAB)
852       continue;
853     Elf_Sym_Range Syms = Obj.symbols(&Sec);
854     uint32_t FirstNonLocal = Sec.sh_info;
855     StringRef StringTable = check(Obj.getStringTableForSymtab(Sec));
856     std::vector<StringRef> V;
857     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
858       if (Sym.st_shndx != SHN_UNDEF)
859         V.push_back(check(Sym.getName(StringTable)));
860     return V;
861   }
862   return {};
863 }
864 
865 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
866   std::unique_ptr<lto::InputFile> Obj = check(lto::InputFile::create(this->MB));
867   std::vector<StringRef> V;
868   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
869     if (!(Sym.getFlags() & BasicSymbolRef::SF_Undefined))
870       V.push_back(Saver.save(Sym.getName()));
871   return V;
872 }
873 
874 // Returns a vector of globally-visible defined symbol names.
875 std::vector<StringRef> LazyObjectFile::getSymbols() {
876   if (isBitcode(this->MB))
877     return getBitcodeSymbols();
878 
879   unsigned char Size;
880   unsigned char Endian;
881   std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer());
882   if (Size == ELFCLASS32) {
883     if (Endian == ELFDATA2LSB)
884       return getElfSymbols<ELF32LE>();
885     return getElfSymbols<ELF32BE>();
886   }
887   if (Endian == ELFDATA2LSB)
888     return getElfSymbols<ELF64LE>();
889   return getElfSymbols<ELF64BE>();
890 }
891 
892 template void ArchiveFile::parse<ELF32LE>();
893 template void ArchiveFile::parse<ELF32BE>();
894 template void ArchiveFile::parse<ELF64LE>();
895 template void ArchiveFile::parse<ELF64BE>();
896 
897 template void BitcodeFile::parse<ELF32LE>(DenseSet<StringRef> &);
898 template void BitcodeFile::parse<ELF32BE>(DenseSet<StringRef> &);
899 template void BitcodeFile::parse<ELF64LE>(DenseSet<StringRef> &);
900 template void BitcodeFile::parse<ELF64BE>(DenseSet<StringRef> &);
901 
902 template void LazyObjectFile::parse<ELF32LE>();
903 template void LazyObjectFile::parse<ELF32BE>();
904 template void LazyObjectFile::parse<ELF64LE>();
905 template void LazyObjectFile::parse<ELF64BE>();
906 
907 template class elf::ELFFileBase<ELF32LE>;
908 template class elf::ELFFileBase<ELF32BE>;
909 template class elf::ELFFileBase<ELF64LE>;
910 template class elf::ELFFileBase<ELF64BE>;
911 
912 template class elf::ObjectFile<ELF32LE>;
913 template class elf::ObjectFile<ELF32BE>;
914 template class elf::ObjectFile<ELF64LE>;
915 template class elf::ObjectFile<ELF64BE>;
916 
917 template class elf::SharedFile<ELF32LE>;
918 template class elf::SharedFile<ELF32BE>;
919 template class elf::SharedFile<ELF64LE>;
920 template class elf::SharedFile<ELF64BE>;
921 
922 template InputFile *BinaryFile::createELF<ELF32LE>();
923 template InputFile *BinaryFile::createELF<ELF32BE>();
924 template InputFile *BinaryFile::createELF<ELF64LE>();
925 template InputFile *BinaryFile::createELF<ELF64BE>();
926