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