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/raw_ostream.h"
24 using namespace llvm::ELF;
25 using namespace llvm::object;
26 using namespace llvm::sys::fs;
29 using namespace lld::elf;
31 // Returns "(internal)", "foo.a(bar.o)" or "baz.o".
32 std::string elf::getFilename(const InputFile *F) {
35 if (!F->ArchiveName.empty())
36 return (F->ArchiveName + "(" + F->getName() + ")").str();
41 static ELFFile<ELFT> createELFObj(MemoryBufferRef MB) {
43 ELFFile<ELFT> F(MB.getBuffer(), EC);
45 error(EC, "failed to read " + MB.getBufferIdentifier());
49 template <class ELFT> static ELFKind getELFKind() {
50 if (ELFT::TargetEndianness == support::little)
51 return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
52 return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
56 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB)
57 : InputFile(K, MB), ELFObj(createELFObj<ELFT>(MB)) {
58 EKind = getELFKind<ELFT>();
59 EMachine = ELFObj.getHeader()->e_machine;
63 typename ELFT::SymRange ELFFileBase<ELFT>::getElfSymbols(bool OnlyGlobals) {
65 return Elf_Sym_Range(nullptr, nullptr);
66 Elf_Sym_Range Syms = ELFObj.symbols(Symtab);
67 uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
68 uint32_t FirstNonLocal = Symtab->sh_info;
69 if (FirstNonLocal > NumSymbols)
70 fatal(getFilename(this) + ": invalid sh_info in symbol table");
73 return makeArrayRef(Syms.begin() + FirstNonLocal, Syms.end());
74 return makeArrayRef(Syms.begin(), Syms.end());
78 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
79 uint32_t I = Sym.st_shndx;
80 if (I == ELF::SHN_XINDEX)
81 return ELFObj.getExtendedSymbolTableIndex(&Sym, Symtab, SymtabSHNDX);
82 if (I >= ELF::SHN_LORESERVE)
87 template <class ELFT> void ELFFileBase<ELFT>::initStringTable() {
90 StringTable = check(ELFObj.getStringTableForSymtab(*Symtab));
94 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)
95 : ELFFileBase<ELFT>(Base::ObjectKind, M) {}
98 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getNonLocalSymbols() {
100 return this->SymbolBodies;
101 uint32_t FirstNonLocal = this->Symtab->sh_info;
102 return makeArrayRef(this->SymbolBodies).slice(FirstNonLocal);
105 template <class ELFT>
106 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
108 return this->SymbolBodies;
109 uint32_t FirstNonLocal = this->Symtab->sh_info;
110 return makeArrayRef(this->SymbolBodies).slice(1, FirstNonLocal - 1);
113 template <class ELFT>
114 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
116 return this->SymbolBodies;
117 return makeArrayRef(this->SymbolBodies).slice(1);
120 template <class ELFT> uint32_t elf::ObjectFile<ELFT>::getMipsGp0() const {
121 if (ELFT::Is64Bits && MipsOptions && MipsOptions->Reginfo)
122 return MipsOptions->Reginfo->ri_gp_value;
123 if (!ELFT::Is64Bits && MipsReginfo && MipsReginfo->Reginfo)
124 return MipsReginfo->Reginfo->ri_gp_value;
128 template <class ELFT>
129 void elf::ObjectFile<ELFT>::parse(DenseSet<StringRef> &ComdatGroups) {
130 // Read section and symbol tables.
131 initializeSections(ComdatGroups);
135 // Sections with SHT_GROUP and comdat bits define comdat section groups.
136 // They are identified and deduplicated by group name. This function
137 // returns a group name.
138 template <class ELFT>
139 StringRef elf::ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) {
140 const ELFFile<ELFT> &Obj = this->ELFObj;
141 const Elf_Shdr *Symtab = check(Obj.getSection(Sec.sh_link));
142 const Elf_Sym *Sym = Obj.getSymbol(Symtab, Sec.sh_info);
143 StringRef Strtab = check(Obj.getStringTableForSymtab(*Symtab));
144 return check(Sym->getName(Strtab));
147 template <class ELFT>
148 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
149 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
150 const ELFFile<ELFT> &Obj = this->ELFObj;
151 ArrayRef<Elf_Word> Entries =
152 check(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec));
153 if (Entries.empty() || Entries[0] != GRP_COMDAT)
154 fatal(getFilename(this) + ": unsupported SHT_GROUP format");
155 return Entries.slice(1);
158 template <class ELFT>
159 bool elf::ObjectFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
160 // We don't merge sections if -O0 (default is -O1). This makes sometimes
161 // the linker significantly faster, although the output will be bigger.
162 if (Config->Optimize == 0)
165 uintX_t Flags = Sec.sh_flags;
166 if (!(Flags & SHF_MERGE))
168 if (Flags & SHF_WRITE)
169 fatal(getFilename(this) + ": writable SHF_MERGE section is not supported");
170 uintX_t EntSize = Sec.sh_entsize;
171 if (!EntSize || Sec.sh_size % EntSize)
172 fatal(getFilename(this) +
173 ": SHF_MERGE section size must be a multiple of sh_entsize");
175 // Don't try to merge if the alignment is larger than the sh_entsize and this
176 // is not SHF_STRINGS.
178 // Since this is not a SHF_STRINGS, we would need to pad after every entity.
179 // It would be equivalent for the producer of the .o to just set a larger
181 if (Flags & SHF_STRINGS)
184 return Sec.sh_addralign <= EntSize;
187 template <class ELFT>
188 void elf::ObjectFile<ELFT>::initializeSections(
189 DenseSet<StringRef> &ComdatGroups) {
190 uint64_t Size = this->ELFObj.getNumSections();
191 Sections.resize(Size);
193 const ELFFile<ELFT> &Obj = this->ELFObj;
194 for (const Elf_Shdr &Sec : Obj.sections()) {
196 if (Sections[I] == &InputSection<ELFT>::Discarded)
199 switch (Sec.sh_type) {
201 Sections[I] = &InputSection<ELFT>::Discarded;
202 if (ComdatGroups.insert(getShtGroupSignature(Sec)).second)
204 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
205 if (SecIndex >= Size)
206 fatal(getFilename(this) + ": invalid section index in group: " +
208 Sections[SecIndex] = &InputSection<ELFT>::Discarded;
214 case SHT_SYMTAB_SHNDX:
215 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
222 // This section contains relocation information.
223 // If -r is given, we do not interpret or apply relocation
224 // but just copy relocation sections to output.
225 if (Config->Relocatable) {
226 Sections[I] = new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec);
230 // Find the relocation target section and associate this
232 InputSectionBase<ELFT> *Target = getRelocTarget(Sec);
235 if (auto *S = dyn_cast<InputSection<ELFT>>(Target)) {
236 S->RelocSections.push_back(&Sec);
239 if (auto *S = dyn_cast<EhInputSection<ELFT>>(Target)) {
243 ": multiple relocation sections to .eh_frame are not supported");
244 S->RelocSection = &Sec;
247 fatal(getFilename(this) +
248 ": relocations pointing to SHF_MERGE are not supported");
250 case SHT_ARM_ATTRIBUTES:
251 // FIXME: ARM meta-data section. At present attributes are ignored,
252 // they can be used to reason about object compatibility.
253 Sections[I] = &InputSection<ELFT>::Discarded;
256 Sections[I] = createInputSection(Sec);
261 template <class ELFT>
262 InputSectionBase<ELFT> *
263 elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
264 uint32_t Idx = Sec.sh_info;
265 if (Idx >= Sections.size())
266 fatal(getFilename(this) + ": invalid relocated section index: " +
268 InputSectionBase<ELFT> *Target = Sections[Idx];
270 // Strictly speaking, a relocation section must be included in the
271 // group of the section it relocates. However, LLVM 3.3 and earlier
272 // would fail to do so, so we gracefully handle that case.
273 if (Target == &InputSection<ELFT>::Discarded)
277 fatal(getFilename(this) + ": unsupported relocation reference");
281 template <class ELFT>
282 InputSectionBase<ELFT> *
283 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
284 StringRef Name = check(this->ELFObj.getSectionName(&Sec));
286 // .note.GNU-stack is a marker section to control the presence of
287 // PT_GNU_STACK segment in outputs. Since the presence of the segment
288 // is controlled only by the command line option (-z execstack) in LLD,
289 // .note.GNU-stack is ignored.
290 if (Name == ".note.GNU-stack")
291 return &InputSection<ELFT>::Discarded;
293 if (Name == ".note.GNU-split-stack") {
294 error("objects using splitstacks are not supported");
295 return &InputSection<ELFT>::Discarded;
298 if (Config->StripDebug && Name.startswith(".debug"))
299 return &InputSection<ELFT>::Discarded;
301 // A MIPS object file has a special sections that contain register
302 // usage info, which need to be handled by the linker specially.
303 if (Config->EMachine == EM_MIPS) {
304 if (Name == ".reginfo") {
305 MipsReginfo.reset(new MipsReginfoInputSection<ELFT>(this, &Sec));
306 return MipsReginfo.get();
308 if (Name == ".MIPS.options") {
309 MipsOptions.reset(new MipsOptionsInputSection<ELFT>(this, &Sec));
310 return MipsOptions.get();
314 // The linker merges EH (exception handling) frames and creates a
315 // .eh_frame_hdr section for runtime. So we handle them with a special
316 // class. For relocatable outputs, they are just passed through.
317 if (Name == ".eh_frame" && !Config->Relocatable)
318 return new (EHAlloc.Allocate()) EhInputSection<ELFT>(this, &Sec);
320 if (shouldMerge(Sec))
321 return new (MAlloc.Allocate()) MergeInputSection<ELFT>(this, &Sec);
322 return new (IAlloc.Allocate()) InputSection<ELFT>(this, &Sec);
325 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
326 this->initStringTable();
327 Elf_Sym_Range Syms = this->getElfSymbols(false);
328 uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
329 SymbolBodies.reserve(NumSymbols);
330 for (const Elf_Sym &Sym : Syms)
331 SymbolBodies.push_back(createSymbolBody(&Sym));
334 template <class ELFT>
335 InputSectionBase<ELFT> *
336 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
337 uint32_t Index = this->getSectionIndex(Sym);
340 if (Index >= Sections.size() || !Sections[Index])
341 fatal(getFilename(this) + ": invalid section index: " + Twine(Index));
342 InputSectionBase<ELFT> *S = Sections[Index];
343 if (S == &InputSectionBase<ELFT>::Discarded)
348 template <class ELFT>
349 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
350 int Binding = Sym->getBinding();
351 InputSectionBase<ELFT> *Sec = getSection(*Sym);
352 if (Binding == STB_LOCAL) {
353 if (Sym->st_shndx == SHN_UNDEF)
354 return new (this->Alloc)
355 Undefined(Sym->st_name, Sym->st_other, Sym->getType(), this);
356 return new (this->Alloc) DefinedRegular<ELFT>(*Sym, Sec);
359 StringRef Name = check(Sym->getName(this->StringTable));
361 switch (Sym->st_shndx) {
363 return elf::Symtab<ELFT>::X
364 ->addUndefined(Name, Binding, Sym->st_other, Sym->getType(),
365 /*CanOmitFromDynSym*/ false, this)
368 return elf::Symtab<ELFT>::X
369 ->addCommon(Name, Sym->st_size, Sym->st_value, Binding, Sym->st_other,
370 Sym->getType(), this)
376 fatal(getFilename(this) + ": unexpected binding: " + Twine(Binding));
380 if (Sec == &InputSection<ELFT>::Discarded)
381 return elf::Symtab<ELFT>::X
382 ->addUndefined(Name, Binding, Sym->st_other, Sym->getType(),
383 /*CanOmitFromDynSym*/ false, this)
385 return elf::Symtab<ELFT>::X->addRegular(Name, *Sym, Sec)->body();
389 template <class ELFT> void ArchiveFile::parse() {
390 File = check(Archive::create(MB), "failed to parse archive");
392 // Read the symbol table to construct Lazy objects.
393 for (const Archive::Symbol &Sym : File->symbols())
394 Symtab<ELFT>::X->addLazyArchive(this, Sym);
397 // Returns a buffer pointing to a member file containing a given symbol.
398 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
400 check(Sym->getMember(),
401 "could not get the member for symbol " + Sym->getName());
403 if (!Seen.insert(C.getChildOffset()).second)
404 return MemoryBufferRef();
406 MemoryBufferRef Ret =
407 check(C.getMemoryBufferRef(),
408 "could not get the buffer for the member defining symbol " +
411 if (C.getParent()->isThin() && Driver->Cpio)
412 Driver->Cpio->append(relativeToRoot(check(C.getFullName())),
418 template <class ELFT>
419 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
420 : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
422 template <class ELFT>
423 const typename ELFT::Shdr *
424 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
425 uint32_t Index = this->getSectionIndex(Sym);
428 return check(this->ELFObj.getSection(Index));
431 // Partially parse the shared object file so that we can call
432 // getSoName on this object.
433 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
434 typedef typename ELFT::Dyn Elf_Dyn;
435 typedef typename ELFT::uint uintX_t;
436 const Elf_Shdr *DynamicSec = nullptr;
438 const ELFFile<ELFT> Obj = this->ELFObj;
439 for (const Elf_Shdr &Sec : Obj.sections()) {
440 switch (Sec.sh_type) {
449 case SHT_SYMTAB_SHNDX:
450 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
453 this->VersymSec = &Sec;
456 this->VerdefSec = &Sec;
461 this->initStringTable();
462 SoName = this->getName();
467 reinterpret_cast<const Elf_Dyn *>(Obj.base() + DynamicSec->sh_offset);
468 const Elf_Dyn *End = Begin + DynamicSec->sh_size / sizeof(Elf_Dyn);
470 for (const Elf_Dyn &Dyn : make_range(Begin, End)) {
471 if (Dyn.d_tag == DT_SONAME) {
472 uintX_t Val = Dyn.getVal();
473 if (Val >= this->StringTable.size())
474 fatal(getFilename(this) + ": invalid DT_SONAME entry");
475 SoName = StringRef(this->StringTable.data() + Val);
481 // Parse the version definitions in the object file if present. Returns a vector
482 // whose nth element contains a pointer to the Elf_Verdef for version identifier
483 // n. Version identifiers that are not definitions map to nullptr. The array
484 // always has at least length 1.
485 template <class ELFT>
486 std::vector<const typename ELFT::Verdef *>
487 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
488 std::vector<const Elf_Verdef *> Verdefs(1);
489 // We only need to process symbol versions for this DSO if it has both a
490 // versym and a verdef section, which indicates that the DSO contains symbol
491 // version definitions.
492 if (!VersymSec || !VerdefSec)
495 // The location of the first global versym entry.
496 Versym = reinterpret_cast<const Elf_Versym *>(this->ELFObj.base() +
497 VersymSec->sh_offset) +
498 this->Symtab->sh_info;
500 // We cannot determine the largest verdef identifier without inspecting
501 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
502 // sequentially starting from 1, so we predict that the largest identifier
503 // will be VerdefCount.
504 unsigned VerdefCount = VerdefSec->sh_info;
505 Verdefs.resize(VerdefCount + 1);
507 // Build the Verdefs array by following the chain of Elf_Verdef objects
508 // from the start of the .gnu.version_d section.
509 const uint8_t *Verdef = this->ELFObj.base() + VerdefSec->sh_offset;
510 for (unsigned I = 0; I != VerdefCount; ++I) {
511 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
512 Verdef += CurVerdef->vd_next;
513 unsigned VerdefIndex = CurVerdef->vd_ndx;
514 if (Verdefs.size() <= VerdefIndex)
515 Verdefs.resize(VerdefIndex + 1);
516 Verdefs[VerdefIndex] = CurVerdef;
522 // Fully parse the shared object file. This must be called after parseSoName().
523 template <class ELFT> void SharedFile<ELFT>::parseRest() {
524 // Create mapping from version identifiers to Elf_Verdef entries.
525 const Elf_Versym *Versym = nullptr;
526 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
528 Elf_Sym_Range Syms = this->getElfSymbols(true);
529 for (const Elf_Sym &Sym : Syms) {
530 unsigned VersymIndex = 0;
532 VersymIndex = Versym->vs_index;
536 StringRef Name = check(Sym.getName(this->StringTable));
537 if (Sym.isUndefined()) {
538 Undefs.push_back(Name);
543 // Ignore local symbols and non-default versions.
544 if (VersymIndex == VER_NDX_LOCAL || (VersymIndex & VERSYM_HIDDEN))
548 const Elf_Verdef *V =
549 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
550 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
554 static ELFKind getELFKind(MemoryBufferRef MB) {
555 std::string TripleStr = getBitcodeTargetTriple(MB, Driver->Context);
556 Triple TheTriple(TripleStr);
557 bool Is64Bits = TheTriple.isArch64Bit();
558 if (TheTriple.isLittleEndian())
559 return Is64Bits ? ELF64LEKind : ELF32LEKind;
560 return Is64Bits ? ELF64BEKind : ELF32BEKind;
563 static uint8_t getMachineKind(MemoryBufferRef MB) {
564 std::string TripleStr = getBitcodeTargetTriple(MB, Driver->Context);
565 switch (Triple(TripleStr).getArch()) {
566 case Triple::aarch64:
573 case Triple::mips64el:
584 fatal(MB.getBufferIdentifier() +
585 ": could not infer e_machine from bitcode target triple " +
590 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) {
591 EKind = getELFKind(MB);
592 EMachine = getMachineKind(MB);
595 static uint8_t getGvVisibility(const GlobalValue *GV) {
596 switch (GV->getVisibility()) {
597 case GlobalValue::DefaultVisibility:
599 case GlobalValue::HiddenVisibility:
601 case GlobalValue::ProtectedVisibility:
602 return STV_PROTECTED;
604 llvm_unreachable("unknown visibility");
607 template <class ELFT>
608 Symbol *BitcodeFile::createSymbol(const DenseSet<const Comdat *> &KeptComdats,
609 const IRObjectFile &Obj,
610 const BasicSymbolRef &Sym) {
611 const GlobalValue *GV = Obj.getSymbolGV(Sym.getRawDataRefImpl());
613 SmallString<64> Name;
614 raw_svector_ostream OS(Name);
616 StringRef NameRef = Saver.save(StringRef(Name));
618 uint32_t Flags = Sym.getFlags();
619 bool IsWeak = Flags & BasicSymbolRef::SF_Weak;
620 uint32_t Binding = IsWeak ? STB_WEAK : STB_GLOBAL;
622 uint8_t Type = STT_NOTYPE;
623 bool CanOmitFromDynSym = false;
624 // FIXME: Expose a thread-local flag for module asm symbols.
626 if (GV->isThreadLocal())
628 CanOmitFromDynSym = canBeOmittedFromSymbolTable(GV);
633 Visibility = getGvVisibility(GV);
635 // FIXME: Set SF_Hidden flag correctly for module asm symbols, and expose
636 // protected visibility.
637 Visibility = STV_DEFAULT;
640 if (const Comdat *C = GV->getComdat())
641 if (!KeptComdats.count(C))
642 return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
643 CanOmitFromDynSym, this);
645 const Module &M = Obj.getModule();
646 if (Flags & BasicSymbolRef::SF_Undefined)
647 return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
648 CanOmitFromDynSym, this);
649 if (Flags & BasicSymbolRef::SF_Common) {
650 // FIXME: Set SF_Common flag correctly for module asm symbols, and expose
651 // size and alignment.
653 const DataLayout &DL = M.getDataLayout();
654 uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
655 return Symtab<ELFT>::X->addCommon(NameRef, Size, GV->getAlignment(),
656 Binding, Visibility, STT_OBJECT, this);
658 return Symtab<ELFT>::X->addBitcode(NameRef, IsWeak, Visibility, Type,
659 CanOmitFromDynSym, this);
662 bool BitcodeFile::shouldSkip(uint32_t Flags) {
663 return !(Flags & BasicSymbolRef::SF_Global) ||
664 (Flags & BasicSymbolRef::SF_FormatSpecific);
667 template <class ELFT>
668 void BitcodeFile::parse(DenseSet<StringRef> &ComdatGroups) {
669 Obj = check(IRObjectFile::create(MB, Driver->Context));
670 const Module &M = Obj->getModule();
672 DenseSet<const Comdat *> KeptComdats;
673 for (const auto &P : M.getComdatSymbolTable()) {
674 StringRef N = Saver.save(P.first());
675 if (ComdatGroups.insert(N).second)
676 KeptComdats.insert(&P.second);
679 for (const BasicSymbolRef &Sym : Obj->symbols())
680 if (!shouldSkip(Sym.getFlags()))
681 Symbols.push_back(createSymbol<ELFT>(KeptComdats, *Obj, Sym));
684 template <template <class> class T>
685 static std::unique_ptr<InputFile> createELFFile(MemoryBufferRef MB) {
687 unsigned char Endian;
688 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
689 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
690 fatal("invalid data encoding: " + MB.getBufferIdentifier());
692 std::unique_ptr<InputFile> Obj;
693 if (Size == ELFCLASS32 && Endian == ELFDATA2LSB)
694 Obj.reset(new T<ELF32LE>(MB));
695 else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB)
696 Obj.reset(new T<ELF32BE>(MB));
697 else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB)
698 Obj.reset(new T<ELF64LE>(MB));
699 else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB)
700 Obj.reset(new T<ELF64BE>(MB));
702 fatal("invalid file class: " + MB.getBufferIdentifier());
704 if (!Config->FirstElf)
705 Config->FirstElf = Obj.get();
709 static bool isBitcode(MemoryBufferRef MB) {
710 using namespace sys::fs;
711 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
714 std::unique_ptr<InputFile> elf::createObjectFile(MemoryBufferRef MB,
715 StringRef ArchiveName) {
716 std::unique_ptr<InputFile> F;
718 F.reset(new BitcodeFile(MB));
720 F = createELFFile<ObjectFile>(MB);
721 F->ArchiveName = ArchiveName;
725 std::unique_ptr<InputFile> elf::createSharedFile(MemoryBufferRef MB) {
726 return createELFFile<SharedFile>(MB);
729 MemoryBufferRef LazyObjectFile::getBuffer() {
731 return MemoryBufferRef();
736 template <class ELFT>
737 void LazyObjectFile::parse() {
738 for (StringRef Sym : getSymbols())
739 Symtab<ELFT>::X->addLazyObject(Sym, *this);
742 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
743 typedef typename ELFT::Shdr Elf_Shdr;
744 typedef typename ELFT::Sym Elf_Sym;
745 typedef typename ELFT::SymRange Elf_Sym_Range;
747 const ELFFile<ELFT> Obj = createELFObj<ELFT>(this->MB);
748 for (const Elf_Shdr &Sec : Obj.sections()) {
749 if (Sec.sh_type != SHT_SYMTAB)
751 Elf_Sym_Range Syms = Obj.symbols(&Sec);
752 uint32_t FirstNonLocal = Sec.sh_info;
753 StringRef StringTable = check(Obj.getStringTableForSymtab(Sec));
754 std::vector<StringRef> V;
755 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
756 if (Sym.st_shndx != SHN_UNDEF)
757 V.push_back(check(Sym.getName(StringTable)));
763 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
765 std::unique_ptr<IRObjectFile> Obj =
766 check(IRObjectFile::create(this->MB, Context));
767 std::vector<StringRef> V;
768 for (const BasicSymbolRef &Sym : Obj->symbols()) {
769 uint32_t Flags = Sym.getFlags();
770 if (BitcodeFile::shouldSkip(Flags))
772 if (Flags & BasicSymbolRef::SF_Undefined)
774 SmallString<64> Name;
775 raw_svector_ostream OS(Name);
777 V.push_back(Saver.save(StringRef(Name)));
782 // Returns a vector of globally-visible defined symbol names.
783 std::vector<StringRef> LazyObjectFile::getSymbols() {
784 if (isBitcode(this->MB))
785 return getBitcodeSymbols();
788 unsigned char Endian;
789 std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer());
790 if (Size == ELFCLASS32) {
791 if (Endian == ELFDATA2LSB)
792 return getElfSymbols<ELF32LE>();
793 return getElfSymbols<ELF32BE>();
795 if (Endian == ELFDATA2LSB)
796 return getElfSymbols<ELF64LE>();
797 return getElfSymbols<ELF64BE>();
800 template void ArchiveFile::parse<ELF32LE>();
801 template void ArchiveFile::parse<ELF32BE>();
802 template void ArchiveFile::parse<ELF64LE>();
803 template void ArchiveFile::parse<ELF64BE>();
805 template void BitcodeFile::parse<ELF32LE>(DenseSet<StringRef> &);
806 template void BitcodeFile::parse<ELF32BE>(DenseSet<StringRef> &);
807 template void BitcodeFile::parse<ELF64LE>(DenseSet<StringRef> &);
808 template void BitcodeFile::parse<ELF64BE>(DenseSet<StringRef> &);
810 template void LazyObjectFile::parse<ELF32LE>();
811 template void LazyObjectFile::parse<ELF32BE>();
812 template void LazyObjectFile::parse<ELF64LE>();
813 template void LazyObjectFile::parse<ELF64BE>();
815 template class elf::ELFFileBase<ELF32LE>;
816 template class elf::ELFFileBase<ELF32BE>;
817 template class elf::ELFFileBase<ELF64LE>;
818 template class elf::ELFFileBase<ELF64BE>;
820 template class elf::ObjectFile<ELF32LE>;
821 template class elf::ObjectFile<ELF32BE>;
822 template class elf::ObjectFile<ELF64LE>;
823 template class elf::ObjectFile<ELF64BE>;
825 template class elf::SharedFile<ELF32LE>;
826 template class elf::SharedFile<ELF32BE>;
827 template class elf::SharedFile<ELF64LE>;
828 template class elf::SharedFile<ELF64BE>;