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