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