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