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