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<CachedHashStringRef> &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<CachedHashStringRef> &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(CachedHashStringRef(getShtGroupSignature(Sec)))
252               .second)
253         continue;
254       for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
255         if (SecIndex >= Size)
256           fatal(getFilename(this) + ": invalid section index in group: " +
257                 Twine(SecIndex));
258         Sections[SecIndex] = &InputSection<ELFT>::Discarded;
259       }
260       break;
261     case SHT_SYMTAB:
262       this->Symtab = &Sec;
263       break;
264     case SHT_SYMTAB_SHNDX:
265       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
266       break;
267     case SHT_STRTAB:
268     case SHT_NULL:
269       break;
270     default:
271       Sections[I] = createInputSection(Sec);
272     }
273   }
274 }
275 
276 // .ARM.exidx sections have a reverse dependency on the InputSection they
277 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
278 template <class ELFT>
279 void elf::ObjectFile<ELFT>::initializeReverseDependencies() {
280   unsigned I = -1;
281   for (const Elf_Shdr &Sec : this->ELFObj.sections()) {
282     ++I;
283     if ((Sections[I] == &InputSection<ELFT>::Discarded) ||
284         !(Sec.sh_flags & SHF_LINK_ORDER))
285       continue;
286     if (Sec.sh_link >= Sections.size())
287       fatal(getFilename(this) + ": invalid sh_link index: " +
288             Twine(Sec.sh_link));
289     auto *IS = cast<InputSection<ELFT>>(Sections[Sec.sh_link]);
290     IS->DependentSection = Sections[I];
291   }
292 }
293 
294 template <class ELFT>
295 InputSectionBase<ELFT> *
296 elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
297   uint32_t Idx = Sec.sh_info;
298   if (Idx >= Sections.size())
299     fatal(getFilename(this) + ": invalid relocated section index: " +
300           Twine(Idx));
301   InputSectionBase<ELFT> *Target = Sections[Idx];
302 
303   // Strictly speaking, a relocation section must be included in the
304   // group of the section it relocates. However, LLVM 3.3 and earlier
305   // would fail to do so, so we gracefully handle that case.
306   if (Target == &InputSection<ELFT>::Discarded)
307     return nullptr;
308 
309   if (!Target)
310     fatal(getFilename(this) + ": unsupported relocation reference");
311   return Target;
312 }
313 
314 template <class ELFT>
315 InputSectionBase<ELFT> *
316 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
317   StringRef Name = check(this->ELFObj.getSectionName(&Sec));
318 
319   switch (Sec.sh_type) {
320   case SHT_ARM_ATTRIBUTES:
321     // FIXME: ARM meta-data section. At present attributes are ignored,
322     // they can be used to reason about object compatibility.
323     return &InputSection<ELFT>::Discarded;
324   case SHT_MIPS_REGINFO:
325     if (MipsReginfo)
326       fatal(getFilename(this) +
327             ": multiple SHT_MIPS_REGINFO sections are not allowed");
328     MipsReginfo.reset(new MipsReginfoInputSection<ELFT>(this, &Sec, Name));
329     return MipsReginfo.get();
330   case SHT_MIPS_OPTIONS:
331     if (MipsOptions)
332       fatal(getFilename(this) +
333             ": multiple SHT_MIPS_OPTIONS sections are not allowed");
334     MipsOptions.reset(new MipsOptionsInputSection<ELFT>(this, &Sec, Name));
335     return MipsOptions.get();
336   case SHT_MIPS_ABIFLAGS:
337     if (MipsAbiFlags)
338       fatal(getFilename(this) +
339             ": multiple SHT_MIPS_ABIFLAGS sections are not allowed");
340     MipsAbiFlags.reset(new MipsAbiFlagsInputSection<ELFT>(this, &Sec, Name));
341     return MipsAbiFlags.get();
342   case SHT_RELA:
343   case SHT_REL: {
344     // This section contains relocation information.
345     // If -r is given, we do not interpret or apply relocation
346     // but just copy relocation sections to output.
347     if (Config->Relocatable)
348       return new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec, Name);
349 
350     // Find the relocation target section and associate this
351     // section with it.
352     InputSectionBase<ELFT> *Target = getRelocTarget(Sec);
353     if (!Target)
354       return nullptr;
355     if (auto *S = dyn_cast<InputSection<ELFT>>(Target)) {
356       S->RelocSections.push_back(&Sec);
357       return nullptr;
358     }
359     if (auto *S = dyn_cast<EhInputSection<ELFT>>(Target)) {
360       if (S->RelocSection)
361         fatal(getFilename(this) +
362               ": multiple relocation sections to .eh_frame are not supported");
363       S->RelocSection = &Sec;
364       return nullptr;
365     }
366     fatal(getFilename(this) +
367           ": relocations pointing to SHF_MERGE are not supported");
368   }
369   }
370 
371   // .note.GNU-stack is a marker section to control the presence of
372   // PT_GNU_STACK segment in outputs. Since the presence of the segment
373   // is controlled only by the command line option (-z execstack) in LLD,
374   // .note.GNU-stack is ignored.
375   if (Name == ".note.GNU-stack")
376     return &InputSection<ELFT>::Discarded;
377 
378   if (Name == ".note.GNU-split-stack") {
379     error("objects using splitstacks are not supported");
380     return &InputSection<ELFT>::Discarded;
381   }
382 
383   if (Config->Strip != StripPolicy::None && Name.startswith(".debug"))
384     return &InputSection<ELFT>::Discarded;
385 
386   // The linker merges EH (exception handling) frames and creates a
387   // .eh_frame_hdr section for runtime. So we handle them with a special
388   // class. For relocatable outputs, they are just passed through.
389   if (Name == ".eh_frame" && !Config->Relocatable)
390     return new (EHAlloc.Allocate()) EhInputSection<ELFT>(this, &Sec, Name);
391 
392   if (shouldMerge(Sec))
393     return new (MAlloc.Allocate()) MergeInputSection<ELFT>(this, &Sec, Name);
394   return new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec, Name);
395 }
396 
397 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
398   this->initStringTable();
399   Elf_Sym_Range Syms = this->getElfSymbols(false);
400   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
401   SymbolBodies.reserve(NumSymbols);
402   for (const Elf_Sym &Sym : Syms)
403     SymbolBodies.push_back(createSymbolBody(&Sym));
404 }
405 
406 template <class ELFT>
407 InputSectionBase<ELFT> *
408 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
409   uint32_t Index = this->getSectionIndex(Sym);
410   if (Index >= Sections.size())
411     fatal(getFilename(this) + ": invalid section index: " + Twine(Index));
412   InputSectionBase<ELFT> *S = Sections[Index];
413 
414   // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03
415   // could generate broken objects. STT_SECTION symbols can be
416   // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections.
417   // In this case it is fine for section to be null here as we
418   // do not allocate sections of these types.
419   if (!S) {
420     if (Index == 0 || Sym.getType() == STT_SECTION)
421       return nullptr;
422     fatal(getFilename(this) + ": invalid section index: " + Twine(Index));
423   }
424 
425   if (S == &InputSectionBase<ELFT>::Discarded)
426     return S;
427   return S->Repl;
428 }
429 
430 template <class ELFT>
431 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
432   int Binding = Sym->getBinding();
433   InputSectionBase<ELFT> *Sec = getSection(*Sym);
434   if (Binding == STB_LOCAL) {
435     if (Sym->st_shndx == SHN_UNDEF)
436       return new (this->Alloc)
437           Undefined(Sym->st_name, Sym->st_other, Sym->getType(), this);
438     return new (this->Alloc) DefinedRegular<ELFT>(*Sym, Sec);
439   }
440 
441   StringRef Name = check(Sym->getName(this->StringTable));
442 
443   switch (Sym->st_shndx) {
444   case SHN_UNDEF:
445     return elf::Symtab<ELFT>::X->addUndefined(Name, Binding, Sym->st_other,
446                                               Sym->getType(),
447                                               /*CanOmitFromDynSym*/ false, this)
448         ->body();
449   case SHN_COMMON:
450     if (Sym->st_value == 0 || Sym->st_value >= UINT32_MAX)
451       fatal(getFilename(this) + ": common symbol '" + Name +
452             "' has invalid alignment: " + Twine(Sym->st_value));
453     return elf::Symtab<ELFT>::X->addCommon(Name, Sym->st_size, Sym->st_value,
454                                            Binding, Sym->st_other,
455                                            Sym->getType(), this)
456         ->body();
457   }
458 
459   switch (Binding) {
460   default:
461     fatal(getFilename(this) + ": unexpected binding: " + Twine(Binding));
462   case STB_GLOBAL:
463   case STB_WEAK:
464   case STB_GNU_UNIQUE:
465     if (Sec == &InputSection<ELFT>::Discarded)
466       return elf::Symtab<ELFT>::X->addUndefined(Name, Binding, Sym->st_other,
467                                                 Sym->getType(),
468                                                 /*CanOmitFromDynSym*/ false,
469                                                 this)
470           ->body();
471     return elf::Symtab<ELFT>::X->addRegular(Name, *Sym, Sec)->body();
472   }
473 }
474 
475 template <class ELFT> void ArchiveFile::parse() {
476   File = check(Archive::create(MB), "failed to parse archive");
477 
478   // Read the symbol table to construct Lazy objects.
479   for (const Archive::Symbol &Sym : File->symbols())
480     Symtab<ELFT>::X->addLazyArchive(this, Sym);
481 }
482 
483 // Returns a buffer pointing to a member file containing a given symbol.
484 std::pair<MemoryBufferRef, uint64_t>
485 ArchiveFile::getMember(const Archive::Symbol *Sym) {
486   Archive::Child C =
487       check(Sym->getMember(),
488             "could not get the member for symbol " + Sym->getName());
489 
490   if (!Seen.insert(C.getChildOffset()).second)
491     return {MemoryBufferRef(), 0};
492 
493   MemoryBufferRef Ret =
494       check(C.getMemoryBufferRef(),
495             "could not get the buffer for the member defining symbol " +
496                 Sym->getName());
497 
498   if (C.getParent()->isThin() && Driver->Cpio)
499     Driver->Cpio->append(relativeToRoot(check(C.getFullName())),
500                          Ret.getBuffer());
501   if (C.getParent()->isThin())
502     return {Ret, 0};
503   return {Ret, C.getChildOffset()};
504 }
505 
506 template <class ELFT>
507 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
508     : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
509 
510 template <class ELFT>
511 const typename ELFT::Shdr *
512 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
513   uint32_t Index = this->getSectionIndex(Sym);
514   if (Index == 0)
515     return nullptr;
516   return check(this->ELFObj.getSection(Index));
517 }
518 
519 // Partially parse the shared object file so that we can call
520 // getSoName on this object.
521 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
522   typedef typename ELFT::Dyn Elf_Dyn;
523   typedef typename ELFT::uint uintX_t;
524   const Elf_Shdr *DynamicSec = nullptr;
525 
526   const ELFFile<ELFT> Obj = this->ELFObj;
527   for (const Elf_Shdr &Sec : Obj.sections()) {
528     switch (Sec.sh_type) {
529     default:
530       continue;
531     case SHT_DYNSYM:
532       this->Symtab = &Sec;
533       break;
534     case SHT_DYNAMIC:
535       DynamicSec = &Sec;
536       break;
537     case SHT_SYMTAB_SHNDX:
538       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
539       break;
540     case SHT_GNU_versym:
541       this->VersymSec = &Sec;
542       break;
543     case SHT_GNU_verdef:
544       this->VerdefSec = &Sec;
545       break;
546     }
547   }
548 
549   this->initStringTable();
550 
551   // DSOs are identified by soname, and they usually contain
552   // DT_SONAME tag in their header. But if they are missing,
553   // filenames are used as default sonames.
554   SoName = sys::path::filename(this->getName());
555 
556   if (!DynamicSec)
557     return;
558 
559   ArrayRef<Elf_Dyn> Arr =
560       check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
561             getFilename(this) + ": getSectionContentsAsArray failed");
562   for (const Elf_Dyn &Dyn : Arr) {
563     if (Dyn.d_tag == DT_SONAME) {
564       uintX_t Val = Dyn.getVal();
565       if (Val >= this->StringTable.size())
566         fatal(getFilename(this) + ": invalid DT_SONAME entry");
567       SoName = StringRef(this->StringTable.data() + Val);
568       return;
569     }
570   }
571 }
572 
573 // Parse the version definitions in the object file if present. Returns a vector
574 // whose nth element contains a pointer to the Elf_Verdef for version identifier
575 // n. Version identifiers that are not definitions map to nullptr. The array
576 // always has at least length 1.
577 template <class ELFT>
578 std::vector<const typename ELFT::Verdef *>
579 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
580   std::vector<const Elf_Verdef *> Verdefs(1);
581   // We only need to process symbol versions for this DSO if it has both a
582   // versym and a verdef section, which indicates that the DSO contains symbol
583   // version definitions.
584   if (!VersymSec || !VerdefSec)
585     return Verdefs;
586 
587   // The location of the first global versym entry.
588   Versym = reinterpret_cast<const Elf_Versym *>(this->ELFObj.base() +
589                                                 VersymSec->sh_offset) +
590            this->Symtab->sh_info;
591 
592   // We cannot determine the largest verdef identifier without inspecting
593   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
594   // sequentially starting from 1, so we predict that the largest identifier
595   // will be VerdefCount.
596   unsigned VerdefCount = VerdefSec->sh_info;
597   Verdefs.resize(VerdefCount + 1);
598 
599   // Build the Verdefs array by following the chain of Elf_Verdef objects
600   // from the start of the .gnu.version_d section.
601   const uint8_t *Verdef = this->ELFObj.base() + VerdefSec->sh_offset;
602   for (unsigned I = 0; I != VerdefCount; ++I) {
603     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
604     Verdef += CurVerdef->vd_next;
605     unsigned VerdefIndex = CurVerdef->vd_ndx;
606     if (Verdefs.size() <= VerdefIndex)
607       Verdefs.resize(VerdefIndex + 1);
608     Verdefs[VerdefIndex] = CurVerdef;
609   }
610 
611   return Verdefs;
612 }
613 
614 // Fully parse the shared object file. This must be called after parseSoName().
615 template <class ELFT> void SharedFile<ELFT>::parseRest() {
616   // Create mapping from version identifiers to Elf_Verdef entries.
617   const Elf_Versym *Versym = nullptr;
618   std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
619 
620   Elf_Sym_Range Syms = this->getElfSymbols(true);
621   for (const Elf_Sym &Sym : Syms) {
622     unsigned VersymIndex = 0;
623     if (Versym) {
624       VersymIndex = Versym->vs_index;
625       ++Versym;
626     }
627 
628     StringRef Name = check(Sym.getName(this->StringTable));
629     if (Sym.isUndefined()) {
630       Undefs.push_back(Name);
631       continue;
632     }
633 
634     if (Versym) {
635       // Ignore local symbols and non-default versions.
636       if (VersymIndex == VER_NDX_LOCAL || (VersymIndex & VERSYM_HIDDEN))
637         continue;
638     }
639 
640     const Elf_Verdef *V =
641         VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
642     elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
643   }
644 }
645 
646 static ELFKind getBitcodeELFKind(MemoryBufferRef MB) {
647   Triple T(getBitcodeTargetTriple(MB, Driver->Context));
648   if (T.isLittleEndian())
649     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
650   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
651 }
652 
653 static uint8_t getBitcodeMachineKind(MemoryBufferRef MB) {
654   Triple T(getBitcodeTargetTriple(MB, Driver->Context));
655   switch (T.getArch()) {
656   case Triple::aarch64:
657     return EM_AARCH64;
658   case Triple::arm:
659     return EM_ARM;
660   case Triple::mips:
661   case Triple::mipsel:
662   case Triple::mips64:
663   case Triple::mips64el:
664     return EM_MIPS;
665   case Triple::ppc:
666     return EM_PPC;
667   case Triple::ppc64:
668     return EM_PPC64;
669   case Triple::x86:
670     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
671   case Triple::x86_64:
672     return EM_X86_64;
673   default:
674     fatal(MB.getBufferIdentifier() +
675           ": could not infer e_machine from bitcode target triple " + T.str());
676   }
677 }
678 
679 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) {
680   EKind = getBitcodeELFKind(MB);
681   EMachine = getBitcodeMachineKind(MB);
682 }
683 
684 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
685   switch (GvVisibility) {
686   case GlobalValue::DefaultVisibility:
687     return STV_DEFAULT;
688   case GlobalValue::HiddenVisibility:
689     return STV_HIDDEN;
690   case GlobalValue::ProtectedVisibility:
691     return STV_PROTECTED;
692   }
693   llvm_unreachable("unknown visibility");
694 }
695 
696 template <class ELFT>
697 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
698                                    const lto::InputFile::Symbol &ObjSym,
699                                    StringSaver &Saver, BitcodeFile *F) {
700   StringRef NameRef = Saver.save(ObjSym.getName());
701   uint32_t Flags = ObjSym.getFlags();
702   uint32_t Binding = (Flags & BasicSymbolRef::SF_Weak) ? STB_WEAK : STB_GLOBAL;
703 
704   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
705   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
706   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
707 
708   int C = check(ObjSym.getComdatIndex());
709   if (C != -1 && !KeptComdats[C])
710     return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
711                                          CanOmitFromDynSym, F);
712 
713   if (Flags & BasicSymbolRef::SF_Undefined)
714     return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
715                                          CanOmitFromDynSym, F);
716 
717   if (Flags & BasicSymbolRef::SF_Common)
718     return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(),
719                                       ObjSym.getCommonAlignment(), Binding,
720                                       Visibility, STT_OBJECT, F);
721 
722   return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type,
723                                      CanOmitFromDynSym, F);
724 }
725 
726 template <class ELFT>
727 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
728 
729   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
730   // (the fully resolved path of the archive) + member name + offset of the
731   // member in the archive.
732   // ThinLTO uses the MemoryBufferRef identifier to access its internal
733   // data structures and if two archives define two members with the same name,
734   // this causes a collision which result in only one of the objects being
735   // taken into consideration at LTO time (which very likely causes undefined
736   // symbols later in the link stage).
737   Obj = check(lto::InputFile::create(MemoryBufferRef(
738       MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier() +
739                                  utostr(OffsetInArchive)))));
740 
741   std::vector<bool> KeptComdats;
742   for (StringRef S : Obj->getComdatTable()) {
743     StringRef N = Saver.save(S);
744     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(N)).second);
745   }
746 
747   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
748     Symbols.push_back(
749         createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, Saver, this));
750 }
751 
752 template <template <class> class T>
753 static InputFile *createELFFile(MemoryBufferRef MB) {
754   unsigned char Size;
755   unsigned char Endian;
756   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
757   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
758     fatal("invalid data encoding: " + MB.getBufferIdentifier());
759 
760   InputFile *Obj;
761   if (Size == ELFCLASS32 && Endian == ELFDATA2LSB)
762     Obj = new T<ELF32LE>(MB);
763   else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB)
764     Obj = new T<ELF32BE>(MB);
765   else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB)
766     Obj = new T<ELF64LE>(MB);
767   else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB)
768     Obj = new T<ELF64BE>(MB);
769   else
770     fatal("invalid file class: " + MB.getBufferIdentifier());
771 
772   if (!Config->FirstElf)
773     Config->FirstElf = Obj;
774   return Obj;
775 }
776 
777 // Wraps a binary blob with an ELF header and footer
778 // so that we can link it as a regular ELF file.
779 template <class ELFT> InputFile *BinaryFile::createELF() {
780   ArrayRef<uint8_t> Blob((uint8_t *)MB.getBufferStart(), MB.getBufferSize());
781   StringRef Filename = MB.getBufferIdentifier();
782   Buffer = wrapBinaryWithElfHeader<ELFT>(Blob, Filename);
783 
784   return createELFFile<ObjectFile>(
785       MemoryBufferRef(toStringRef(Buffer), Filename));
786 }
787 
788 static bool isBitcode(MemoryBufferRef MB) {
789   using namespace sys::fs;
790   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
791 }
792 
793 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
794                                  uint64_t OffsetInArchive) {
795   InputFile *F =
796       isBitcode(MB) ? new BitcodeFile(MB) : createELFFile<ObjectFile>(MB);
797   F->ArchiveName = ArchiveName;
798   F->OffsetInArchive = OffsetInArchive;
799   return F;
800 }
801 
802 InputFile *elf::createSharedFile(MemoryBufferRef MB) {
803   return createELFFile<SharedFile>(MB);
804 }
805 
806 MemoryBufferRef LazyObjectFile::getBuffer() {
807   if (Seen)
808     return MemoryBufferRef();
809   Seen = true;
810   return MB;
811 }
812 
813 template <class ELFT> void LazyObjectFile::parse() {
814   for (StringRef Sym : getSymbols())
815     Symtab<ELFT>::X->addLazyObject(Sym, *this);
816 }
817 
818 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
819   typedef typename ELFT::Shdr Elf_Shdr;
820   typedef typename ELFT::Sym Elf_Sym;
821   typedef typename ELFT::SymRange Elf_Sym_Range;
822 
823   const ELFFile<ELFT> Obj = createELFObj<ELFT>(this->MB);
824   for (const Elf_Shdr &Sec : Obj.sections()) {
825     if (Sec.sh_type != SHT_SYMTAB)
826       continue;
827     Elf_Sym_Range Syms = Obj.symbols(&Sec);
828     uint32_t FirstNonLocal = Sec.sh_info;
829     StringRef StringTable = check(Obj.getStringTableForSymtab(Sec));
830     std::vector<StringRef> V;
831     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
832       if (Sym.st_shndx != SHN_UNDEF)
833         V.push_back(check(Sym.getName(StringTable)));
834     return V;
835   }
836   return {};
837 }
838 
839 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
840   std::unique_ptr<lto::InputFile> Obj = check(lto::InputFile::create(this->MB));
841   std::vector<StringRef> V;
842   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
843     if (!(Sym.getFlags() & BasicSymbolRef::SF_Undefined))
844       V.push_back(Saver.save(Sym.getName()));
845   return V;
846 }
847 
848 // Returns a vector of globally-visible defined symbol names.
849 std::vector<StringRef> LazyObjectFile::getSymbols() {
850   if (isBitcode(this->MB))
851     return getBitcodeSymbols();
852 
853   unsigned char Size;
854   unsigned char Endian;
855   std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer());
856   if (Size == ELFCLASS32) {
857     if (Endian == ELFDATA2LSB)
858       return getElfSymbols<ELF32LE>();
859     return getElfSymbols<ELF32BE>();
860   }
861   if (Endian == ELFDATA2LSB)
862     return getElfSymbols<ELF64LE>();
863   return getElfSymbols<ELF64BE>();
864 }
865 
866 template void ArchiveFile::parse<ELF32LE>();
867 template void ArchiveFile::parse<ELF32BE>();
868 template void ArchiveFile::parse<ELF64LE>();
869 template void ArchiveFile::parse<ELF64BE>();
870 
871 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
872 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
873 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
874 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
875 
876 template void LazyObjectFile::parse<ELF32LE>();
877 template void LazyObjectFile::parse<ELF32BE>();
878 template void LazyObjectFile::parse<ELF64LE>();
879 template void LazyObjectFile::parse<ELF64BE>();
880 
881 template class elf::ELFFileBase<ELF32LE>;
882 template class elf::ELFFileBase<ELF32BE>;
883 template class elf::ELFFileBase<ELF64LE>;
884 template class elf::ELFFileBase<ELF64BE>;
885 
886 template class elf::ObjectFile<ELF32LE>;
887 template class elf::ObjectFile<ELF32BE>;
888 template class elf::ObjectFile<ELF64LE>;
889 template class elf::ObjectFile<ELF64BE>;
890 
891 template class elf::SharedFile<ELF32LE>;
892 template class elf::SharedFile<ELF32BE>;
893 template class elf::SharedFile<ELF64LE>;
894 template class elf::SharedFile<ELF64BE>;
895 
896 template InputFile *BinaryFile::createELF<ELF32LE>();
897 template InputFile *BinaryFile::createELF<ELF32BE>();
898 template InputFile *BinaryFile::createELF<ELF64LE>();
899 template InputFile *BinaryFile::createELF<ELF64BE>();
900