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 "Error.h"
13 #include "InputSection.h"
14 #include "Symbols.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/CodeGen/Analysis.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/Support/raw_ostream.h"
20 
21 using namespace llvm;
22 using namespace llvm::ELF;
23 using namespace llvm::object;
24 using namespace llvm::sys::fs;
25 
26 using namespace lld;
27 using namespace lld::elf;
28 
29 template <class ELFT>
30 static ELFFile<ELFT> createELFObj(MemoryBufferRef MB) {
31   std::error_code EC;
32   ELFFile<ELFT> F(MB.getBuffer(), EC);
33   check(EC);
34   return F;
35 }
36 
37 template <class ELFT>
38 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB)
39     : InputFile(K, MB), ELFObj(createELFObj<ELFT>(MB)) {}
40 
41 template <class ELFT>
42 ELFKind ELFFileBase<ELFT>::getELFKind() {
43   if (ELFT::TargetEndianness == support::little)
44     return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
45   return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
46 }
47 
48 template <class ELFT>
49 typename ELFT::SymRange ELFFileBase<ELFT>::getElfSymbols(bool OnlyGlobals) {
50   if (!Symtab)
51     return Elf_Sym_Range(nullptr, nullptr);
52   Elf_Sym_Range Syms = ELFObj.symbols(Symtab);
53   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
54   uint32_t FirstNonLocal = Symtab->sh_info;
55   if (FirstNonLocal > NumSymbols)
56     fatal("invalid sh_info in symbol table");
57 
58   if (OnlyGlobals)
59     return makeArrayRef(Syms.begin() + FirstNonLocal, Syms.end());
60   return makeArrayRef(Syms.begin(), Syms.end());
61 }
62 
63 template <class ELFT>
64 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
65   uint32_t I = Sym.st_shndx;
66   if (I == ELF::SHN_XINDEX)
67     return ELFObj.getExtendedSymbolTableIndex(&Sym, Symtab, SymtabSHNDX);
68   if (I >= ELF::SHN_LORESERVE)
69     return 0;
70   return I;
71 }
72 
73 template <class ELFT> void ELFFileBase<ELFT>::initStringTable() {
74   if (!Symtab)
75     return;
76   StringTable = check(ELFObj.getStringTableForSymtab(*Symtab));
77 }
78 
79 template <class ELFT>
80 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)
81     : ELFFileBase<ELFT>(Base::ObjectKind, M) {}
82 
83 template <class ELFT>
84 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getNonLocalSymbols() {
85   if (!this->Symtab)
86     return this->SymbolBodies;
87   uint32_t FirstNonLocal = this->Symtab->sh_info;
88   return makeArrayRef(this->SymbolBodies).slice(FirstNonLocal);
89 }
90 
91 template <class ELFT>
92 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
93   if (!this->Symtab)
94     return this->SymbolBodies;
95   uint32_t FirstNonLocal = this->Symtab->sh_info;
96   return makeArrayRef(this->SymbolBodies).slice(1, FirstNonLocal - 1);
97 }
98 
99 template <class ELFT>
100 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
101   if (!this->Symtab)
102     return this->SymbolBodies;
103   return makeArrayRef(this->SymbolBodies).slice(1);
104 }
105 
106 template <class ELFT> uint32_t elf::ObjectFile<ELFT>::getMipsGp0() const {
107   if (MipsReginfo)
108     return MipsReginfo->Reginfo->ri_gp_value;
109   return 0;
110 }
111 
112 template <class ELFT>
113 void elf::ObjectFile<ELFT>::parse(DenseSet<StringRef> &ComdatGroups) {
114   // Read section and symbol tables.
115   initializeSections(ComdatGroups);
116   initializeSymbols();
117 }
118 
119 // Sections with SHT_GROUP and comdat bits define comdat section groups.
120 // They are identified and deduplicated by group name. This function
121 // returns a group name.
122 template <class ELFT>
123 StringRef elf::ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) {
124   const ELFFile<ELFT> &Obj = this->ELFObj;
125   uint32_t SymtabdSectionIndex = Sec.sh_link;
126   const Elf_Shdr *SymtabSec = check(Obj.getSection(SymtabdSectionIndex));
127   uint32_t SymIndex = Sec.sh_info;
128   const Elf_Sym *Sym = Obj.getSymbol(SymtabSec, SymIndex);
129   StringRef StringTable = check(Obj.getStringTableForSymtab(*SymtabSec));
130   return check(Sym->getName(StringTable));
131 }
132 
133 template <class ELFT>
134 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
135 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
136   const ELFFile<ELFT> &Obj = this->ELFObj;
137   ArrayRef<Elf_Word> Entries =
138       check(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec));
139   if (Entries.empty() || Entries[0] != GRP_COMDAT)
140     fatal("unsupported SHT_GROUP format");
141   return Entries.slice(1);
142 }
143 
144 template <class ELFT> static bool shouldMerge(const typename ELFT::Shdr &Sec) {
145   typedef typename ELFT::uint uintX_t;
146 
147   // We don't merge sections if -O0 (default is -O1). This makes sometimes
148   // the linker significantly faster, although the output will be bigger.
149   if (Config->Optimize == 0)
150     return false;
151 
152   uintX_t Flags = Sec.sh_flags;
153   if (!(Flags & SHF_MERGE))
154     return false;
155   if (Flags & SHF_WRITE)
156     fatal("writable SHF_MERGE sections are not supported");
157   uintX_t EntSize = Sec.sh_entsize;
158   if (!EntSize || Sec.sh_size % EntSize)
159     fatal("SHF_MERGE section size must be a multiple of sh_entsize");
160 
161   // Don't try to merge if the aligment is larger than the sh_entsize and this
162   // is not SHF_STRINGS.
163   //
164   // Since this is not a SHF_STRINGS, we would need to pad after every entity.
165   // It would be equivalent for the producer of the .o to just set a larger
166   // sh_entsize.
167   if (Flags & SHF_STRINGS)
168     return true;
169 
170   if (Sec.sh_addralign > EntSize)
171     return false;
172 
173   return true;
174 }
175 
176 template <class ELFT>
177 void elf::ObjectFile<ELFT>::initializeSections(
178     DenseSet<StringRef> &ComdatGroups) {
179   uint64_t Size = this->ELFObj.getNumSections();
180   Sections.resize(Size);
181   unsigned I = -1;
182   const ELFFile<ELFT> &Obj = this->ELFObj;
183   for (const Elf_Shdr &Sec : Obj.sections()) {
184     ++I;
185     if (Sections[I] == &InputSection<ELFT>::Discarded)
186       continue;
187 
188     switch (Sec.sh_type) {
189     case SHT_GROUP:
190       Sections[I] = &InputSection<ELFT>::Discarded;
191       if (ComdatGroups.insert(getShtGroupSignature(Sec)).second)
192         continue;
193       for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
194         if (SecIndex >= Size)
195           fatal("invalid section index in group");
196         Sections[SecIndex] = &InputSection<ELFT>::Discarded;
197       }
198       break;
199     case SHT_SYMTAB:
200       this->Symtab = &Sec;
201       break;
202     case SHT_SYMTAB_SHNDX:
203       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
204       break;
205     case SHT_STRTAB:
206     case SHT_NULL:
207       break;
208     case SHT_RELA:
209     case SHT_REL: {
210       // This section contains relocation information.
211       // If -r is given, we do not interpret or apply relocation
212       // but just copy relocation sections to output.
213       if (Config->Relocatable) {
214         Sections[I] = new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec);
215         break;
216       }
217 
218       // Find the relocation target section and associate this
219       // section with it.
220       InputSectionBase<ELFT> *Target = getRelocTarget(Sec);
221       if (!Target)
222         break;
223       if (auto *S = dyn_cast<InputSection<ELFT>>(Target)) {
224         S->RelocSections.push_back(&Sec);
225         break;
226       }
227       if (auto *S = dyn_cast<EHInputSection<ELFT>>(Target)) {
228         if (S->RelocSection)
229           fatal("multiple relocation sections to .eh_frame are not supported");
230         S->RelocSection = &Sec;
231         break;
232       }
233       fatal("relocations pointing to SHF_MERGE are not supported");
234     }
235     default:
236       Sections[I] = createInputSection(Sec);
237     }
238   }
239 }
240 
241 template <class ELFT>
242 InputSectionBase<ELFT> *
243 elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
244   uint32_t Idx = Sec.sh_info;
245   if (Idx >= Sections.size())
246     fatal("invalid relocated section index");
247   InputSectionBase<ELFT> *Target = Sections[Idx];
248 
249   // Strictly speaking, a relocation section must be included in the
250   // group of the section it relocates. However, LLVM 3.3 and earlier
251   // would fail to do so, so we gracefully handle that case.
252   if (Target == &InputSection<ELFT>::Discarded)
253     return nullptr;
254 
255   if (!Target)
256     fatal("unsupported relocation reference");
257   return Target;
258 }
259 
260 template <class ELFT>
261 InputSectionBase<ELFT> *
262 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
263   StringRef Name = check(this->ELFObj.getSectionName(&Sec));
264 
265   // .note.GNU-stack is a marker section to control the presence of
266   // PT_GNU_STACK segment in outputs. Since the presence of the segment
267   // is controlled only by the command line option (-z execstack) in LLD,
268   // .note.GNU-stack is ignored.
269   if (Name == ".note.GNU-stack")
270     return &InputSection<ELFT>::Discarded;
271 
272   if (Name == ".note.GNU-split-stack") {
273     error("objects using splitstacks are not supported");
274     return &InputSection<ELFT>::Discarded;
275   }
276 
277   if (Config->StripDebug && Name.startswith(".debug"))
278     return &InputSection<ELFT>::Discarded;
279 
280   // A MIPS object file has a special section that contains register
281   // usage info, which needs to be handled by the linker specially.
282   if (Config->EMachine == EM_MIPS && Name == ".reginfo") {
283     MipsReginfo.reset(new MipsReginfoInputSection<ELFT>(this, &Sec));
284     return MipsReginfo.get();
285   }
286 
287   // We dont need special handling of .eh_frame sections if relocatable
288   // output was choosen. Proccess them as usual input sections.
289   if (!Config->Relocatable && Name == ".eh_frame")
290     return new (EHAlloc.Allocate()) EHInputSection<ELFT>(this, &Sec);
291   if (shouldMerge<ELFT>(Sec))
292     return new (MAlloc.Allocate()) MergeInputSection<ELFT>(this, &Sec);
293   return new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec);
294 }
295 
296 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
297   this->initStringTable();
298   Elf_Sym_Range Syms = this->getElfSymbols(false);
299   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
300   SymbolBodies.reserve(NumSymbols);
301   for (const Elf_Sym &Sym : Syms)
302     SymbolBodies.push_back(createSymbolBody(&Sym));
303 }
304 
305 template <class ELFT>
306 InputSectionBase<ELFT> *
307 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
308   uint32_t Index = this->getSectionIndex(Sym);
309   if (Index == 0)
310     return nullptr;
311   if (Index >= Sections.size() || !Sections[Index])
312     fatal("invalid section index");
313   InputSectionBase<ELFT> *S = Sections[Index];
314   if (S == &InputSectionBase<ELFT>::Discarded)
315     return S;
316   return S->Repl;
317 }
318 
319 template <class ELFT>
320 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
321   unsigned char Binding = Sym->getBinding();
322   InputSectionBase<ELFT> *Sec = getSection(*Sym);
323   if (Binding == STB_LOCAL) {
324     if (Sym->st_shndx == SHN_UNDEF)
325       return new (Alloc) Undefined(Sym->st_name, Sym->st_other, Sym->getType());
326     return new (Alloc) DefinedRegular<ELFT>(*Sym, Sec);
327   }
328 
329   StringRef Name = check(Sym->getName(this->StringTable));
330 
331   switch (Sym->st_shndx) {
332   case SHN_UNDEF:
333     return new (Alloc) Undefined(Name, Binding, Sym->st_other, Sym->getType(),
334                                  /*IsBitcode*/ false);
335   case SHN_COMMON:
336     return new (Alloc) DefinedCommon(Name, Sym->st_size, Sym->st_value, Binding,
337                                      Sym->st_other, Sym->getType());
338   }
339 
340   switch (Binding) {
341   default:
342     fatal("unexpected binding");
343   case STB_GLOBAL:
344   case STB_WEAK:
345   case STB_GNU_UNIQUE:
346     if (Sec == &InputSection<ELFT>::Discarded)
347       return new (Alloc) Undefined(Name, Binding, Sym->st_other, Sym->getType(),
348                                    /*IsBitcode*/ false);
349     return new (Alloc) DefinedRegular<ELFT>(Name, *Sym, Sec);
350   }
351 }
352 
353 void ArchiveFile::parse() {
354   File = check(Archive::create(MB), "failed to parse archive");
355 
356   // Allocate a buffer for Lazy objects.
357   size_t NumSyms = File->getNumberOfSymbols();
358   LazySymbols.reserve(NumSyms);
359 
360   // Read the symbol table to construct Lazy objects.
361   for (const Archive::Symbol &Sym : File->symbols())
362     LazySymbols.emplace_back(this, Sym);
363 }
364 
365 // Returns a buffer pointing to a member file containing a given symbol.
366 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
367   Archive::Child C =
368       check(Sym->getMember(),
369             "could not get the member for symbol " + Sym->getName());
370 
371   if (!Seen.insert(C.getChildOffset()).second)
372     return MemoryBufferRef();
373 
374   return check(C.getMemoryBufferRef(),
375                "could not get the buffer for the member defining symbol " +
376                    Sym->getName());
377 }
378 
379 template <class ELFT>
380 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
381     : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
382 
383 template <class ELFT>
384 const typename ELFT::Shdr *
385 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
386   uint32_t Index = this->getSectionIndex(Sym);
387   if (Index == 0)
388     return nullptr;
389   return check(this->ELFObj.getSection(Index));
390 }
391 
392 // Partially parse the shared object file so that we can call
393 // getSoName on this object.
394 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
395   typedef typename ELFT::Dyn Elf_Dyn;
396   typedef typename ELFT::uint uintX_t;
397   const Elf_Shdr *DynamicSec = nullptr;
398 
399   const ELFFile<ELFT> Obj = this->ELFObj;
400   for (const Elf_Shdr &Sec : Obj.sections()) {
401     switch (Sec.sh_type) {
402     default:
403       continue;
404     case SHT_DYNSYM:
405       this->Symtab = &Sec;
406       break;
407     case SHT_DYNAMIC:
408       DynamicSec = &Sec;
409       break;
410     case SHT_SYMTAB_SHNDX:
411       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
412       break;
413     case SHT_GNU_versym:
414       this->VersymSec = &Sec;
415       break;
416     case SHT_GNU_verdef:
417       this->VerdefSec = &Sec;
418       break;
419     }
420   }
421 
422   this->initStringTable();
423   SoName = this->getName();
424 
425   if (!DynamicSec)
426     return;
427   auto *Begin =
428       reinterpret_cast<const Elf_Dyn *>(Obj.base() + DynamicSec->sh_offset);
429   const Elf_Dyn *End = Begin + DynamicSec->sh_size / sizeof(Elf_Dyn);
430 
431   for (const Elf_Dyn &Dyn : make_range(Begin, End)) {
432     if (Dyn.d_tag == DT_SONAME) {
433       uintX_t Val = Dyn.getVal();
434       if (Val >= this->StringTable.size())
435         fatal("invalid DT_SONAME entry");
436       SoName = StringRef(this->StringTable.data() + Val);
437       return;
438     }
439   }
440 }
441 
442 // Parse the version definitions in the object file if present. Returns a vector
443 // whose nth element contains a pointer to the Elf_Verdef for version identifier
444 // n. Version identifiers that are not definitions map to nullptr. The array
445 // always has at least length 1.
446 template <class ELFT>
447 std::vector<const typename ELFT::Verdef *>
448 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
449   std::vector<const Elf_Verdef *> Verdefs(1);
450   // We only need to process symbol versions for this DSO if it has both a
451   // versym and a verdef section, which indicates that the DSO contains symbol
452   // version definitions.
453   if (!VersymSec || !VerdefSec)
454     return Verdefs;
455 
456   // The location of the first global versym entry.
457   Versym = reinterpret_cast<const Elf_Versym *>(this->ELFObj.base() +
458                                                 VersymSec->sh_offset) +
459            this->Symtab->sh_info;
460 
461   // We cannot determine the largest verdef identifier without inspecting
462   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
463   // sequentially starting from 1, so we predict that the largest identifier
464   // will be VerdefCount.
465   unsigned VerdefCount = VerdefSec->sh_info;
466   Verdefs.resize(VerdefCount + 1);
467 
468   // Build the Verdefs array by following the chain of Elf_Verdef objects
469   // from the start of the .gnu.version_d section.
470   const uint8_t *Verdef = this->ELFObj.base() + VerdefSec->sh_offset;
471   for (unsigned I = 0; I != VerdefCount; ++I) {
472     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
473     Verdef += CurVerdef->vd_next;
474     unsigned VerdefIndex = CurVerdef->vd_ndx;
475     if (Verdefs.size() <= VerdefIndex)
476       Verdefs.resize(VerdefIndex + 1);
477     Verdefs[VerdefIndex] = CurVerdef;
478   }
479 
480   return Verdefs;
481 }
482 
483 // Fully parse the shared object file. This must be called after parseSoName().
484 template <class ELFT> void SharedFile<ELFT>::parseRest() {
485   // Create mapping from version identifiers to Elf_Verdef entries.
486   const Elf_Versym *Versym = nullptr;
487   std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
488 
489   Elf_Sym_Range Syms = this->getElfSymbols(true);
490   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
491   SymbolBodies.reserve(NumSymbols);
492   for (const Elf_Sym &Sym : Syms) {
493     unsigned VersymIndex = 0;
494     if (Versym) {
495       VersymIndex = Versym->vs_index;
496       ++Versym;
497     }
498 
499     StringRef Name = check(Sym.getName(this->StringTable));
500     if (Sym.isUndefined()) {
501       Undefs.push_back(Name);
502       continue;
503     }
504 
505     if (Versym) {
506       // Ignore local symbols and non-default versions.
507       if (VersymIndex == 0 || (VersymIndex & VERSYM_HIDDEN))
508         continue;
509     }
510     SymbolBodies.emplace_back(this, Name, Sym, Verdefs[VersymIndex]);
511   }
512 }
513 
514 BitcodeFile::BitcodeFile(MemoryBufferRef M) : InputFile(BitcodeKind, M) {}
515 
516 bool BitcodeFile::classof(const InputFile *F) {
517   return F->kind() == BitcodeKind;
518 }
519 
520 static uint8_t getGvVisibility(const GlobalValue *GV) {
521   switch (GV->getVisibility()) {
522   case GlobalValue::DefaultVisibility:
523     return STV_DEFAULT;
524   case GlobalValue::HiddenVisibility:
525     return STV_HIDDEN;
526   case GlobalValue::ProtectedVisibility:
527     return STV_PROTECTED;
528   }
529   llvm_unreachable("unknown visibility");
530 }
531 
532 SymbolBody *
533 BitcodeFile::createBody(const DenseSet<const Comdat *> &KeptComdats,
534                               const IRObjectFile &Obj,
535                               const BasicSymbolRef &Sym,
536                               const GlobalValue *GV) {
537   SmallString<64> Name;
538   raw_svector_ostream OS(Name);
539   Sym.printName(OS);
540   StringRef NameRef = Saver.save(StringRef(Name));
541   SymbolBody *Body;
542 
543   uint32_t Flags = Sym.getFlags();
544   bool IsWeak = Flags & BasicSymbolRef::SF_Weak;
545   uint32_t Binding = IsWeak ? STB_WEAK : STB_GLOBAL;
546 
547   uint8_t Visibility;
548   if (GV)
549     Visibility = getGvVisibility(GV);
550   else
551     // FIXME: Set SF_Hidden flag correctly for module asm symbols, and expose
552     // protected visibility.
553     Visibility = STV_DEFAULT;
554 
555   if (GV)
556     if (const Comdat *C = GV->getComdat())
557       if (!KeptComdats.count(C)) {
558         Body = new (Alloc) Undefined(NameRef, Binding, Visibility, /*Type*/ 0,
559                                      /*IsBitcode*/ true);
560         return Body;
561       }
562 
563   const Module &M = Obj.getModule();
564   if (Flags & BasicSymbolRef::SF_Undefined)
565     return new (Alloc) Undefined(NameRef, Binding, Visibility, /*Type*/ 0,
566                                  /*IsBitcode*/ true);
567   if (Flags & BasicSymbolRef::SF_Common) {
568     // FIXME: Set SF_Common flag correctly for module asm symbols, and expose
569     // size and alignment.
570     assert(GV);
571     const DataLayout &DL = M.getDataLayout();
572     uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
573     return new (Alloc) DefinedCommon(NameRef, Size, GV->getAlignment(), Binding,
574                                      Visibility, /*Type*/ 0);
575   }
576   return new (Alloc) DefinedBitcode(NameRef, IsWeak, Visibility);
577 }
578 
579 SymbolBody *
580 BitcodeFile::createSymbolBody(const DenseSet<const Comdat *> &KeptComdats,
581                               const IRObjectFile &Obj,
582                               const BasicSymbolRef &Sym) {
583   const GlobalValue *GV = Obj.getSymbolGV(Sym.getRawDataRefImpl());
584   SymbolBody *Body = createBody(KeptComdats, Obj, Sym, GV);
585 
586   // FIXME: Expose a thread-local flag for module asm symbols.
587   if (GV) {
588     if (GV->isThreadLocal())
589       Body->Type = STT_TLS;
590     Body->CanOmitFromDynSym = canBeOmittedFromSymbolTable(GV);
591   }
592   return Body;
593 }
594 
595 bool BitcodeFile::shouldSkip(const BasicSymbolRef &Sym) {
596   uint32_t Flags = Sym.getFlags();
597   if (!(Flags & BasicSymbolRef::SF_Global))
598     return true;
599   if (Flags & BasicSymbolRef::SF_FormatSpecific)
600     return true;
601   return false;
602 }
603 
604 void BitcodeFile::parse(DenseSet<StringRef> &ComdatGroups) {
605   Obj = check(IRObjectFile::create(MB, Driver->Context));
606   const Module &M = Obj->getModule();
607 
608   DenseSet<const Comdat *> KeptComdats;
609   for (const auto &P : M.getComdatSymbolTable()) {
610     StringRef N = Saver.save(P.first());
611     if (ComdatGroups.insert(N).second)
612       KeptComdats.insert(&P.second);
613   }
614 
615   for (const BasicSymbolRef &Sym : Obj->symbols())
616     if (!shouldSkip(Sym))
617       SymbolBodies.push_back(createSymbolBody(KeptComdats, *Obj, Sym));
618 }
619 
620 template <typename T>
621 static std::unique_ptr<InputFile> createELFFileAux(MemoryBufferRef MB) {
622   std::unique_ptr<T> Ret = llvm::make_unique<T>(MB);
623 
624   if (!Config->FirstElf)
625     Config->FirstElf = Ret.get();
626 
627   if (Config->EKind == ELFNoneKind) {
628     Config->EKind = Ret->getELFKind();
629     Config->EMachine = Ret->getEMachine();
630     if (Config->EMachine == EM_MIPS && Config->EKind == ELF64LEKind)
631       Config->Mips64EL = true;
632   }
633 
634   return std::move(Ret);
635 }
636 
637 template <template <class> class T>
638 static std::unique_ptr<InputFile> createELFFile(MemoryBufferRef MB) {
639   unsigned char Size;
640   unsigned char Endian;
641   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
642   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
643     fatal("invalid data encoding: " + MB.getBufferIdentifier());
644 
645   if (Size == ELFCLASS32) {
646     if (Endian == ELFDATA2LSB)
647       return createELFFileAux<T<ELF32LE>>(MB);
648     return createELFFileAux<T<ELF32BE>>(MB);
649   }
650   if (Size == ELFCLASS64) {
651     if (Endian == ELFDATA2LSB)
652       return createELFFileAux<T<ELF64LE>>(MB);
653     return createELFFileAux<T<ELF64BE>>(MB);
654   }
655   fatal("invalid file class: " + MB.getBufferIdentifier());
656 }
657 
658 static bool isBitcode(MemoryBufferRef MB) {
659   using namespace sys::fs;
660   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
661 }
662 
663 std::unique_ptr<InputFile> elf::createObjectFile(MemoryBufferRef MB,
664                                                  StringRef ArchiveName) {
665   std::unique_ptr<InputFile> F;
666   if (isBitcode(MB))
667     F.reset(new BitcodeFile(MB));
668   else
669     F = createELFFile<ObjectFile>(MB);
670   F->ArchiveName = ArchiveName;
671   return F;
672 }
673 
674 std::unique_ptr<InputFile> elf::createSharedFile(MemoryBufferRef MB) {
675   return createELFFile<SharedFile>(MB);
676 }
677 
678 void LazyObjectFile::parse() {
679   for (StringRef Sym : getSymbols())
680     LazySymbols.emplace_back(Sym, this->MB);
681 }
682 
683 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
684   typedef typename ELFT::Shdr Elf_Shdr;
685   typedef typename ELFT::Sym Elf_Sym;
686   typedef typename ELFT::SymRange Elf_Sym_Range;
687 
688   const ELFFile<ELFT> Obj = createELFObj<ELFT>(this->MB);
689   for (const Elf_Shdr &Sec : Obj.sections()) {
690     if (Sec.sh_type != SHT_SYMTAB)
691       continue;
692     Elf_Sym_Range Syms = Obj.symbols(&Sec);
693     uint32_t FirstNonLocal = Sec.sh_info;
694     StringRef StringTable = check(Obj.getStringTableForSymtab(Sec));
695     std::vector<StringRef> V;
696     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
697       if (Sym.st_shndx != SHN_UNDEF)
698         V.push_back(check(Sym.getName(StringTable)));
699     return V;
700   }
701   return {};
702 }
703 
704 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
705   LLVMContext Context;
706   std::unique_ptr<IRObjectFile> Obj =
707       check(IRObjectFile::create(this->MB, Context));
708   std::vector<StringRef> V;
709   for (const BasicSymbolRef &Sym : Obj->symbols()) {
710     if (BitcodeFile::shouldSkip(Sym))
711       continue;
712     if (Sym.getFlags() & BasicSymbolRef::SF_Undefined)
713       continue;
714     SmallString<64> Name;
715     raw_svector_ostream OS(Name);
716     Sym.printName(OS);
717     V.push_back(Saver.save(StringRef(Name)));
718   }
719   return V;
720 }
721 
722 // Returns a vector of globally-visible defined symbol names.
723 std::vector<StringRef> LazyObjectFile::getSymbols() {
724   if (isBitcode(this->MB))
725     return getBitcodeSymbols();
726 
727   unsigned char Size;
728   unsigned char Endian;
729   std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer());
730   if (Size == ELFCLASS32) {
731     if (Endian == ELFDATA2LSB)
732       return getElfSymbols<ELF32LE>();
733     return getElfSymbols<ELF32BE>();
734   }
735   if (Endian == ELFDATA2LSB)
736     return getElfSymbols<ELF64LE>();
737   return getElfSymbols<ELF64BE>();
738 }
739 
740 template class elf::ELFFileBase<ELF32LE>;
741 template class elf::ELFFileBase<ELF32BE>;
742 template class elf::ELFFileBase<ELF64LE>;
743 template class elf::ELFFileBase<ELF64BE>;
744 
745 template class elf::ObjectFile<ELF32LE>;
746 template class elf::ObjectFile<ELF32BE>;
747 template class elf::ObjectFile<ELF64LE>;
748 template class elf::ObjectFile<ELF64BE>;
749 
750 template class elf::SharedFile<ELF32LE>;
751 template class elf::SharedFile<ELF32BE>;
752 template class elf::SharedFile<ELF64LE>;
753 template class elf::SharedFile<ELF64BE>;
754