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