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