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