1 //===- InputFiles.cpp -----------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "InputFiles.h"
13 #include "InputSection.h"
14 #include "SymbolTable.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/raw_ostream.h"
25 using namespace llvm::ELF;
26 using namespace llvm::object;
27 using namespace llvm::sys::fs;
30 using namespace lld::elf;
32 // Returns "(internal)", "foo.a(bar.o)" or "baz.o".
33 std::string elf::getFilename(const InputFile *F) {
36 if (!F->ArchiveName.empty())
37 return (F->ArchiveName + "(" + F->getName() + ")").str();
42 static ELFFile<ELFT> createELFObj(MemoryBufferRef MB) {
44 ELFFile<ELFT> F(MB.getBuffer(), EC);
46 error(EC, "failed to read " + MB.getBufferIdentifier());
50 template <class ELFT> static ELFKind getELFKind() {
51 if (ELFT::TargetEndianness == support::little)
52 return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
53 return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
57 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB)
58 : InputFile(K, MB), ELFObj(createELFObj<ELFT>(MB)) {
59 EKind = getELFKind<ELFT>();
60 EMachine = ELFObj.getHeader()->e_machine;
64 typename ELFT::SymRange ELFFileBase<ELFT>::getElfSymbols(bool OnlyGlobals) {
66 return Elf_Sym_Range(nullptr, nullptr);
67 Elf_Sym_Range Syms = ELFObj.symbols(Symtab);
68 uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
69 uint32_t FirstNonLocal = Symtab->sh_info;
70 if (FirstNonLocal > NumSymbols)
71 fatal(getFilename(this) + ": invalid sh_info in symbol table");
74 return makeArrayRef(Syms.begin() + FirstNonLocal, Syms.end());
75 return makeArrayRef(Syms.begin(), Syms.end());
79 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
80 uint32_t I = Sym.st_shndx;
81 if (I == ELF::SHN_XINDEX)
82 return ELFObj.getExtendedSymbolTableIndex(&Sym, Symtab, SymtabSHNDX);
83 if (I >= ELF::SHN_LORESERVE)
88 template <class ELFT> void ELFFileBase<ELFT>::initStringTable() {
91 StringTable = check(ELFObj.getStringTableForSymtab(*Symtab));
95 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)
96 : ELFFileBase<ELFT>(Base::ObjectKind, M) {}
99 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getNonLocalSymbols() {
101 return this->SymbolBodies;
102 uint32_t FirstNonLocal = this->Symtab->sh_info;
103 return makeArrayRef(this->SymbolBodies).slice(FirstNonLocal);
106 template <class ELFT>
107 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
109 return this->SymbolBodies;
110 uint32_t FirstNonLocal = this->Symtab->sh_info;
111 return makeArrayRef(this->SymbolBodies).slice(1, FirstNonLocal - 1);
114 template <class ELFT>
115 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
117 return this->SymbolBodies;
118 return makeArrayRef(this->SymbolBodies).slice(1);
121 template <class ELFT> uint32_t elf::ObjectFile<ELFT>::getMipsGp0() const {
122 if (ELFT::Is64Bits && MipsOptions && MipsOptions->Reginfo)
123 return MipsOptions->Reginfo->ri_gp_value;
124 if (!ELFT::Is64Bits && MipsReginfo && MipsReginfo->Reginfo)
125 return MipsReginfo->Reginfo->ri_gp_value;
129 template <class ELFT>
130 void elf::ObjectFile<ELFT>::parse(DenseSet<StringRef> &ComdatGroups) {
131 // Read section and symbol tables.
132 initializeSections(ComdatGroups);
136 // Sections with SHT_GROUP and comdat bits define comdat section groups.
137 // They are identified and deduplicated by group name. This function
138 // returns a group name.
139 template <class ELFT>
140 StringRef elf::ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) {
141 const ELFFile<ELFT> &Obj = this->ELFObj;
142 const Elf_Shdr *Symtab = check(Obj.getSection(Sec.sh_link));
143 const Elf_Sym *Sym = Obj.getSymbol(Symtab, Sec.sh_info);
144 StringRef Strtab = check(Obj.getStringTableForSymtab(*Symtab));
145 return check(Sym->getName(Strtab));
148 template <class ELFT>
149 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
150 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
151 const ELFFile<ELFT> &Obj = this->ELFObj;
152 ArrayRef<Elf_Word> Entries =
153 check(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec));
154 if (Entries.empty() || Entries[0] != GRP_COMDAT)
155 fatal(getFilename(this) + ": unsupported SHT_GROUP format");
156 return Entries.slice(1);
159 template <class ELFT>
160 bool elf::ObjectFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
161 // We don't merge sections if -O0 (default is -O1). This makes sometimes
162 // the linker significantly faster, although the output will be bigger.
163 if (Config->Optimize == 0)
166 uintX_t Flags = Sec.sh_flags;
167 if (!(Flags & SHF_MERGE))
169 if (Flags & SHF_WRITE)
170 fatal(getFilename(this) + ": writable SHF_MERGE section is not supported");
171 uintX_t EntSize = Sec.sh_entsize;
172 if (!EntSize || Sec.sh_size % EntSize)
173 fatal(getFilename(this) +
174 ": SHF_MERGE section size must be a multiple of sh_entsize");
176 // Don't try to merge if the alignment is larger than the sh_entsize and this
177 // is not SHF_STRINGS.
179 // Since this is not a SHF_STRINGS, we would need to pad after every entity.
180 // It would be equivalent for the producer of the .o to just set a larger
182 if (Flags & SHF_STRINGS)
185 return Sec.sh_addralign <= EntSize;
188 template <class ELFT>
189 void elf::ObjectFile<ELFT>::initializeSections(
190 DenseSet<StringRef> &ComdatGroups) {
191 uint64_t Size = this->ELFObj.getNumSections();
192 Sections.resize(Size);
194 const ELFFile<ELFT> &Obj = this->ELFObj;
195 for (const Elf_Shdr &Sec : Obj.sections()) {
197 if (Sections[I] == &InputSection<ELFT>::Discarded)
200 switch (Sec.sh_type) {
202 Sections[I] = &InputSection<ELFT>::Discarded;
203 if (ComdatGroups.insert(getShtGroupSignature(Sec)).second)
205 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
206 if (SecIndex >= Size)
207 fatal(getFilename(this) + ": invalid section index in group: " +
209 Sections[SecIndex] = &InputSection<ELFT>::Discarded;
215 case SHT_SYMTAB_SHNDX:
216 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
223 // This section contains relocation information.
224 // If -r is given, we do not interpret or apply relocation
225 // but just copy relocation sections to output.
226 if (Config->Relocatable) {
227 Sections[I] = new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec);
231 // Find the relocation target section and associate this
233 InputSectionBase<ELFT> *Target = getRelocTarget(Sec);
236 if (auto *S = dyn_cast<InputSection<ELFT>>(Target)) {
237 S->RelocSections.push_back(&Sec);
240 if (auto *S = dyn_cast<EhInputSection<ELFT>>(Target)) {
244 ": multiple relocation sections to .eh_frame are not supported");
245 S->RelocSection = &Sec;
248 fatal(getFilename(this) +
249 ": relocations pointing to SHF_MERGE are not supported");
251 case SHT_ARM_ATTRIBUTES:
252 // FIXME: ARM meta-data section. At present attributes are ignored,
253 // they can be used to reason about object compatibility.
254 Sections[I] = &InputSection<ELFT>::Discarded;
257 Sections[I] = createInputSection(Sec);
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: " +
269 InputSectionBase<ELFT> *Target = Sections[Idx];
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)
278 fatal(getFilename(this) + ": unsupported relocation reference");
282 template <class ELFT>
283 InputSectionBase<ELFT> *
284 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
285 StringRef Name = check(this->ELFObj.getSectionName(&Sec));
287 // .note.GNU-stack is a marker section to control the presence of
288 // PT_GNU_STACK segment in outputs. Since the presence of the segment
289 // is controlled only by the command line option (-z execstack) in LLD,
290 // .note.GNU-stack is ignored.
291 if (Name == ".note.GNU-stack")
292 return &InputSection<ELFT>::Discarded;
294 if (Name == ".note.GNU-split-stack") {
295 error("objects using splitstacks are not supported");
296 return &InputSection<ELFT>::Discarded;
299 if (Config->StripDebug && Name.startswith(".debug"))
300 return &InputSection<ELFT>::Discarded;
302 // A MIPS object file has a special sections that contain register
303 // usage info, which need to be handled by the linker specially.
304 if (Config->EMachine == EM_MIPS) {
305 if (Name == ".reginfo") {
306 MipsReginfo.reset(new MipsReginfoInputSection<ELFT>(this, &Sec));
307 return MipsReginfo.get();
309 if (Name == ".MIPS.options") {
310 MipsOptions.reset(new MipsOptionsInputSection<ELFT>(this, &Sec));
311 return MipsOptions.get();
315 // The linker merges EH (exception handling) frames and creates a
316 // .eh_frame_hdr section for runtime. So we handle them with a special
317 // class. For relocatable outputs, they are just passed through.
318 if (Name == ".eh_frame" && !Config->Relocatable)
319 return new (EHAlloc.Allocate()) EhInputSection<ELFT>(this, &Sec);
321 if (shouldMerge(Sec))
322 return new (MAlloc.Allocate()) MergeInputSection<ELFT>(this, &Sec);
323 return new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec);
326 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
327 this->initStringTable();
328 Elf_Sym_Range Syms = this->getElfSymbols(false);
329 uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
330 SymbolBodies.reserve(NumSymbols);
331 for (const Elf_Sym &Sym : Syms)
332 SymbolBodies.push_back(createSymbolBody(&Sym));
335 template <class ELFT>
336 InputSectionBase<ELFT> *
337 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
338 uint32_t Index = this->getSectionIndex(Sym);
341 if (Index >= Sections.size() || !Sections[Index])
342 fatal(getFilename(this) + ": invalid section index: " + Twine(Index));
343 InputSectionBase<ELFT> *S = Sections[Index];
344 if (S == &InputSectionBase<ELFT>::Discarded)
349 template <class ELFT>
350 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
351 int Binding = Sym->getBinding();
352 InputSectionBase<ELFT> *Sec = getSection(*Sym);
353 if (Binding == STB_LOCAL) {
354 if (Sym->st_shndx == SHN_UNDEF)
355 return new (this->Alloc)
356 Undefined(Sym->st_name, Sym->st_other, Sym->getType(), this);
357 return new (this->Alloc) DefinedRegular<ELFT>(*Sym, Sec);
360 StringRef Name = check(Sym->getName(this->StringTable));
362 switch (Sym->st_shndx) {
364 return elf::Symtab<ELFT>::X
365 ->addUndefined(Name, Binding, Sym->st_other, Sym->getType(),
366 /*CanOmitFromDynSym*/ false, this)
369 return elf::Symtab<ELFT>::X
370 ->addCommon(Name, Sym->st_size, Sym->st_value, Binding, Sym->st_other,
371 Sym->getType(), this)
377 fatal(getFilename(this) + ": unexpected binding: " + Twine(Binding));
381 if (Sec == &InputSection<ELFT>::Discarded)
382 return elf::Symtab<ELFT>::X
383 ->addUndefined(Name, Binding, Sym->st_other, Sym->getType(),
384 /*CanOmitFromDynSym*/ false, this)
386 return elf::Symtab<ELFT>::X->addRegular(Name, *Sym, Sec)->body();
390 template <class ELFT> void ArchiveFile::parse() {
391 File = check(Archive::create(MB), "failed to parse archive");
393 // Read the symbol table to construct Lazy objects.
394 for (const Archive::Symbol &Sym : File->symbols())
395 Symtab<ELFT>::X->addLazyArchive(this, Sym);
398 // Returns a buffer pointing to a member file containing a given symbol.
399 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
401 check(Sym->getMember(),
402 "could not get the member for symbol " + Sym->getName());
404 if (!Seen.insert(C.getChildOffset()).second)
405 return MemoryBufferRef();
407 MemoryBufferRef Ret =
408 check(C.getMemoryBufferRef(),
409 "could not get the buffer for the member defining symbol " +
412 if (C.getParent()->isThin() && Driver->Cpio)
413 Driver->Cpio->append(relativeToRoot(check(C.getFullName())),
419 template <class ELFT>
420 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
421 : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
423 template <class ELFT>
424 const typename ELFT::Shdr *
425 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
426 uint32_t Index = this->getSectionIndex(Sym);
429 return check(this->ELFObj.getSection(Index));
432 // Partially parse the shared object file so that we can call
433 // getSoName on this object.
434 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
435 typedef typename ELFT::Dyn Elf_Dyn;
436 typedef typename ELFT::uint uintX_t;
437 const Elf_Shdr *DynamicSec = nullptr;
439 const ELFFile<ELFT> Obj = this->ELFObj;
440 for (const Elf_Shdr &Sec : Obj.sections()) {
441 switch (Sec.sh_type) {
450 case SHT_SYMTAB_SHNDX:
451 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
454 this->VersymSec = &Sec;
457 this->VerdefSec = &Sec;
462 this->initStringTable();
463 SoName = sys::path::filename(this->getName());
468 reinterpret_cast<const Elf_Dyn *>(Obj.base() + DynamicSec->sh_offset);
469 const Elf_Dyn *End = Begin + DynamicSec->sh_size / sizeof(Elf_Dyn);
471 for (const Elf_Dyn &Dyn : make_range(Begin, End)) {
472 if (Dyn.d_tag == DT_SONAME) {
473 uintX_t Val = Dyn.getVal();
474 if (Val >= this->StringTable.size())
475 fatal(getFilename(this) + ": invalid DT_SONAME entry");
476 SoName = StringRef(this->StringTable.data() + Val);
482 // Parse the version definitions in the object file if present. Returns a vector
483 // whose nth element contains a pointer to the Elf_Verdef for version identifier
484 // n. Version identifiers that are not definitions map to nullptr. The array
485 // always has at least length 1.
486 template <class ELFT>
487 std::vector<const typename ELFT::Verdef *>
488 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
489 std::vector<const Elf_Verdef *> Verdefs(1);
490 // We only need to process symbol versions for this DSO if it has both a
491 // versym and a verdef section, which indicates that the DSO contains symbol
492 // version definitions.
493 if (!VersymSec || !VerdefSec)
496 // The location of the first global versym entry.
497 Versym = reinterpret_cast<const Elf_Versym *>(this->ELFObj.base() +
498 VersymSec->sh_offset) +
499 this->Symtab->sh_info;
501 // We cannot determine the largest verdef identifier without inspecting
502 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
503 // sequentially starting from 1, so we predict that the largest identifier
504 // will be VerdefCount.
505 unsigned VerdefCount = VerdefSec->sh_info;
506 Verdefs.resize(VerdefCount + 1);
508 // Build the Verdefs array by following the chain of Elf_Verdef objects
509 // from the start of the .gnu.version_d section.
510 const uint8_t *Verdef = this->ELFObj.base() + VerdefSec->sh_offset;
511 for (unsigned I = 0; I != VerdefCount; ++I) {
512 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
513 Verdef += CurVerdef->vd_next;
514 unsigned VerdefIndex = CurVerdef->vd_ndx;
515 if (Verdefs.size() <= VerdefIndex)
516 Verdefs.resize(VerdefIndex + 1);
517 Verdefs[VerdefIndex] = CurVerdef;
523 // Fully parse the shared object file. This must be called after parseSoName().
524 template <class ELFT> void SharedFile<ELFT>::parseRest() {
525 // Create mapping from version identifiers to Elf_Verdef entries.
526 const Elf_Versym *Versym = nullptr;
527 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
529 Elf_Sym_Range Syms = this->getElfSymbols(true);
530 for (const Elf_Sym &Sym : Syms) {
531 unsigned VersymIndex = 0;
533 VersymIndex = Versym->vs_index;
537 StringRef Name = check(Sym.getName(this->StringTable));
538 if (Sym.isUndefined()) {
539 Undefs.push_back(Name);
544 // Ignore local symbols and non-default versions.
545 if (VersymIndex == VER_NDX_LOCAL || (VersymIndex & VERSYM_HIDDEN))
549 const Elf_Verdef *V =
550 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
551 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
555 static ELFKind getELFKind(MemoryBufferRef MB) {
556 std::string TripleStr = getBitcodeTargetTriple(MB, Driver->Context);
557 Triple TheTriple(TripleStr);
558 bool Is64Bits = TheTriple.isArch64Bit();
559 if (TheTriple.isLittleEndian())
560 return Is64Bits ? ELF64LEKind : ELF32LEKind;
561 return Is64Bits ? ELF64BEKind : ELF32BEKind;
564 static uint8_t getMachineKind(MemoryBufferRef MB) {
565 std::string TripleStr = getBitcodeTargetTriple(MB, Driver->Context);
566 switch (Triple(TripleStr).getArch()) {
567 case Triple::aarch64:
574 case Triple::mips64el:
585 fatal(MB.getBufferIdentifier() +
586 ": could not infer e_machine from bitcode target triple " +
591 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) {
592 EKind = getELFKind(MB);
593 EMachine = getMachineKind(MB);
596 static uint8_t getGvVisibility(const GlobalValue *GV) {
597 switch (GV->getVisibility()) {
598 case GlobalValue::DefaultVisibility:
600 case GlobalValue::HiddenVisibility:
602 case GlobalValue::ProtectedVisibility:
603 return STV_PROTECTED;
605 llvm_unreachable("unknown visibility");
608 template <class ELFT>
609 Symbol *BitcodeFile::createSymbol(const DenseSet<const Comdat *> &KeptComdats,
610 const IRObjectFile &Obj,
611 const BasicSymbolRef &Sym) {
612 const GlobalValue *GV = Obj.getSymbolGV(Sym.getRawDataRefImpl());
614 SmallString<64> Name;
615 raw_svector_ostream OS(Name);
617 StringRef NameRef = Saver.save(StringRef(Name));
619 uint32_t Flags = Sym.getFlags();
620 bool IsWeak = Flags & BasicSymbolRef::SF_Weak;
621 uint32_t Binding = IsWeak ? STB_WEAK : STB_GLOBAL;
623 uint8_t Type = STT_NOTYPE;
624 bool CanOmitFromDynSym = false;
625 // FIXME: Expose a thread-local flag for module asm symbols.
627 if (GV->isThreadLocal())
629 CanOmitFromDynSym = canBeOmittedFromSymbolTable(GV);
634 Visibility = getGvVisibility(GV);
636 // FIXME: Set SF_Hidden flag correctly for module asm symbols, and expose
637 // protected visibility.
638 Visibility = STV_DEFAULT;
641 if (const Comdat *C = GV->getComdat())
642 if (!KeptComdats.count(C))
643 return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
644 CanOmitFromDynSym, this);
646 const Module &M = Obj.getModule();
647 if (Flags & BasicSymbolRef::SF_Undefined)
648 return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
649 CanOmitFromDynSym, this);
650 if (Flags & BasicSymbolRef::SF_Common) {
651 // FIXME: Set SF_Common flag correctly for module asm symbols, and expose
652 // size and alignment.
654 const DataLayout &DL = M.getDataLayout();
655 uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
656 return Symtab<ELFT>::X->addCommon(NameRef, Size, GV->getAlignment(),
657 Binding, Visibility, STT_OBJECT, this);
659 return Symtab<ELFT>::X->addBitcode(NameRef, IsWeak, Visibility, Type,
660 CanOmitFromDynSym, this);
663 bool BitcodeFile::shouldSkip(uint32_t Flags) {
664 return !(Flags & BasicSymbolRef::SF_Global) ||
665 (Flags & BasicSymbolRef::SF_FormatSpecific);
668 template <class ELFT>
669 void BitcodeFile::parse(DenseSet<StringRef> &ComdatGroups) {
670 Obj = check(IRObjectFile::create(MB, Driver->Context));
671 const Module &M = Obj->getModule();
673 DenseSet<const Comdat *> KeptComdats;
674 for (const auto &P : M.getComdatSymbolTable()) {
675 StringRef N = Saver.save(P.first());
676 if (ComdatGroups.insert(N).second)
677 KeptComdats.insert(&P.second);
680 for (const BasicSymbolRef &Sym : Obj->symbols())
681 if (!shouldSkip(Sym.getFlags()))
682 Symbols.push_back(createSymbol<ELFT>(KeptComdats, *Obj, Sym));
685 template <template <class> class T>
686 static std::unique_ptr<InputFile> createELFFile(MemoryBufferRef MB) {
688 unsigned char Endian;
689 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
690 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
691 fatal("invalid data encoding: " + MB.getBufferIdentifier());
693 std::unique_ptr<InputFile> Obj;
694 if (Size == ELFCLASS32 && Endian == ELFDATA2LSB)
695 Obj.reset(new T<ELF32LE>(MB));
696 else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB)
697 Obj.reset(new T<ELF32BE>(MB));
698 else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB)
699 Obj.reset(new T<ELF64LE>(MB));
700 else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB)
701 Obj.reset(new T<ELF64BE>(MB));
703 fatal("invalid file class: " + MB.getBufferIdentifier());
705 if (!Config->FirstElf)
706 Config->FirstElf = Obj.get();
710 static bool isBitcode(MemoryBufferRef MB) {
711 using namespace sys::fs;
712 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
715 std::unique_ptr<InputFile> elf::createObjectFile(MemoryBufferRef MB,
716 StringRef ArchiveName) {
717 std::unique_ptr<InputFile> F;
719 F.reset(new BitcodeFile(MB));
721 F = createELFFile<ObjectFile>(MB);
722 F->ArchiveName = ArchiveName;
726 std::unique_ptr<InputFile> elf::createSharedFile(MemoryBufferRef MB) {
727 return createELFFile<SharedFile>(MB);
730 MemoryBufferRef LazyObjectFile::getBuffer() {
732 return MemoryBufferRef();
737 template <class ELFT>
738 void LazyObjectFile::parse() {
739 for (StringRef Sym : getSymbols())
740 Symtab<ELFT>::X->addLazyObject(Sym, *this);
743 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
744 typedef typename ELFT::Shdr Elf_Shdr;
745 typedef typename ELFT::Sym Elf_Sym;
746 typedef typename ELFT::SymRange Elf_Sym_Range;
748 const ELFFile<ELFT> Obj = createELFObj<ELFT>(this->MB);
749 for (const Elf_Shdr &Sec : Obj.sections()) {
750 if (Sec.sh_type != SHT_SYMTAB)
752 Elf_Sym_Range Syms = Obj.symbols(&Sec);
753 uint32_t FirstNonLocal = Sec.sh_info;
754 StringRef StringTable = check(Obj.getStringTableForSymtab(Sec));
755 std::vector<StringRef> V;
756 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
757 if (Sym.st_shndx != SHN_UNDEF)
758 V.push_back(check(Sym.getName(StringTable)));
764 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
766 std::unique_ptr<IRObjectFile> Obj =
767 check(IRObjectFile::create(this->MB, Context));
768 std::vector<StringRef> V;
769 for (const BasicSymbolRef &Sym : Obj->symbols()) {
770 uint32_t Flags = Sym.getFlags();
771 if (BitcodeFile::shouldSkip(Flags))
773 if (Flags & BasicSymbolRef::SF_Undefined)
775 SmallString<64> Name;
776 raw_svector_ostream OS(Name);
778 V.push_back(Saver.save(StringRef(Name)));
783 // Returns a vector of globally-visible defined symbol names.
784 std::vector<StringRef> LazyObjectFile::getSymbols() {
785 if (isBitcode(this->MB))
786 return getBitcodeSymbols();
789 unsigned char Endian;
790 std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer());
791 if (Size == ELFCLASS32) {
792 if (Endian == ELFDATA2LSB)
793 return getElfSymbols<ELF32LE>();
794 return getElfSymbols<ELF32BE>();
796 if (Endian == ELFDATA2LSB)
797 return getElfSymbols<ELF64LE>();
798 return getElfSymbols<ELF64BE>();
801 template void ArchiveFile::parse<ELF32LE>();
802 template void ArchiveFile::parse<ELF32BE>();
803 template void ArchiveFile::parse<ELF64LE>();
804 template void ArchiveFile::parse<ELF64BE>();
806 template void BitcodeFile::parse<ELF32LE>(DenseSet<StringRef> &);
807 template void BitcodeFile::parse<ELF32BE>(DenseSet<StringRef> &);
808 template void BitcodeFile::parse<ELF64LE>(DenseSet<StringRef> &);
809 template void BitcodeFile::parse<ELF64BE>(DenseSet<StringRef> &);
811 template void LazyObjectFile::parse<ELF32LE>();
812 template void LazyObjectFile::parse<ELF32BE>();
813 template void LazyObjectFile::parse<ELF64LE>();
814 template void LazyObjectFile::parse<ELF64BE>();
816 template class elf::ELFFileBase<ELF32LE>;
817 template class elf::ELFFileBase<ELF32BE>;
818 template class elf::ELFFileBase<ELF64LE>;
819 template class elf::ELFFileBase<ELF64BE>;
821 template class elf::ObjectFile<ELF32LE>;
822 template class elf::ObjectFile<ELF32BE>;
823 template class elf::ObjectFile<ELF64LE>;
824 template class elf::ObjectFile<ELF64BE>;
826 template class elf::SharedFile<ELF32LE>;
827 template class elf::SharedFile<ELF32BE>;
828 template class elf::SharedFile<ELF64LE>;
829 template class elf::SharedFile<ELF64BE>;