//===- InputFiles.cpp -----------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "InputFiles.h" #include "InputSection.h" #include "Error.h" #include "Symbols.h" #include "llvm/ADT/STLExtras.h" using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; using namespace llvm::sys::fs; using namespace lld; using namespace lld::elf2; namespace { class ECRAII { std::error_code EC; public: std::error_code &getEC() { return EC; } ~ECRAII() { error(EC); } }; } template ELFFileBase::ELFFileBase(Kind K, MemoryBufferRef M) : InputFile(K, M), ELFObj(MB.getBuffer(), ECRAII().getEC()) {} template ELFKind ELFFileBase::getELFKind() { if (ELFT::TargetEndianness == support::little) return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind; return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind; } template typename ELFFileBase::Elf_Sym_Range ELFFileBase::getSymbolsHelper(bool Local) { if (!Symtab) return Elf_Sym_Range(nullptr, nullptr); Elf_Sym_Range Syms = ELFObj.symbols(Symtab); uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end()); uint32_t FirstNonLocal = Symtab->sh_info; if (FirstNonLocal > NumSymbols) error("Invalid sh_info in symbol table"); if (!Local) return make_range(Syms.begin() + FirstNonLocal, Syms.end()); // +1 to skip over dummy symbol. return make_range(Syms.begin() + 1, Syms.begin() + FirstNonLocal); } template uint32_t ELFFileBase::getSectionIndex(const Elf_Sym &Sym) const { uint32_t I = Sym.st_shndx; if (I == ELF::SHN_XINDEX) return ELFObj.getExtendedSymbolTableIndex(&Sym, Symtab, SymtabSHNDX); if (I >= ELF::SHN_LORESERVE || I == ELF::SHN_ABS) return 0; return I; } template void ELFFileBase::initStringTable() { if (!Symtab) return; ErrorOr StringTableOrErr = ELFObj.getStringTableForSymtab(*Symtab); error(StringTableOrErr); StringTable = *StringTableOrErr; } template typename ELFFileBase::Elf_Sym_Range ELFFileBase::getNonLocalSymbols() { return getSymbolsHelper(false); } template ObjectFile::ObjectFile(MemoryBufferRef M) : ELFFileBase(Base::ObjectKind, M) {} template typename ObjectFile::Elf_Sym_Range ObjectFile::getLocalSymbols() { return this->getSymbolsHelper(true); } template uint32_t ObjectFile::getMipsGp0() const { return MipsReginfo ? MipsReginfo->getGp0() : 0; } template const typename ObjectFile::Elf_Sym * ObjectFile::getLocalSymbol(uintX_t SymIndex) { uint32_t FirstNonLocal = this->Symtab->sh_info; if (SymIndex >= FirstNonLocal) return nullptr; Elf_Sym_Range Syms = this->ELFObj.symbols(this->Symtab); return Syms.begin() + SymIndex; } template void ObjectFile::parse(DenseSet &ComdatGroups) { // Read section and symbol tables. initializeSections(ComdatGroups); initializeSymbols(); } // Sections with SHT_GROUP and comdat bits define comdat section groups. // They are identified and deduplicated by group name. This function // returns a group name. template StringRef ObjectFile::getShtGroupSignature(const Elf_Shdr &Sec) { const ELFFile &Obj = this->ELFObj; uint32_t SymtabdSectionIndex = Sec.sh_link; ErrorOr SecOrErr = Obj.getSection(SymtabdSectionIndex); error(SecOrErr); const Elf_Shdr *SymtabSec = *SecOrErr; uint32_t SymIndex = Sec.sh_info; const Elf_Sym *Sym = Obj.getSymbol(SymtabSec, SymIndex); ErrorOr StringTableOrErr = Obj.getStringTableForSymtab(*SymtabSec); error(StringTableOrErr); ErrorOr SignatureOrErr = Sym->getName(*StringTableOrErr); error(SignatureOrErr); return *SignatureOrErr; } template ArrayRef::GroupEntryType> ObjectFile::getShtGroupEntries(const Elf_Shdr &Sec) { const ELFFile &Obj = this->ELFObj; ErrorOr> EntriesOrErr = Obj.template getSectionContentsAsArray(&Sec); error(EntriesOrErr); ArrayRef Entries = *EntriesOrErr; if (Entries.empty() || Entries[0] != GRP_COMDAT) error("Unsupported SHT_GROUP format"); return Entries.slice(1); } template static bool shouldMerge(const typename ELFFile::Elf_Shdr &Sec) { typedef typename ELFFile::uintX_t uintX_t; uintX_t Flags = Sec.sh_flags; if (!(Flags & SHF_MERGE)) return false; if (Flags & SHF_WRITE) error("Writable SHF_MERGE sections are not supported"); uintX_t EntSize = Sec.sh_entsize; if (!EntSize || Sec.sh_size % EntSize) error("SHF_MERGE section size must be a multiple of sh_entsize"); // Don't try to merge if the aligment is larger than the sh_entsize. // // If this is not a SHF_STRINGS, we would need to pad after every entity. It // would be equivalent for the producer of the .o to just set a larger // sh_entsize. // // If this is a SHF_STRINGS, the larger alignment makes sense. Unfortunately // it would complicate tail merging. This doesn't seem that common to // justify the effort. if (Sec.sh_addralign > EntSize) return false; return true; } template void ObjectFile::initializeSections(DenseSet &ComdatGroups) { uint64_t Size = this->ELFObj.getNumSections(); Sections.resize(Size); unsigned I = -1; const ELFFile &Obj = this->ELFObj; for (const Elf_Shdr &Sec : Obj.sections()) { ++I; if (Sections[I] == &InputSection::Discarded) continue; switch (Sec.sh_type) { case SHT_GROUP: Sections[I] = &InputSection::Discarded; if (ComdatGroups.insert(getShtGroupSignature(Sec)).second) continue; for (GroupEntryType E : getShtGroupEntries(Sec)) { uint32_t SecIndex = E; if (SecIndex >= Size) error("Invalid section index in group"); Sections[SecIndex] = &InputSection::Discarded; } break; case SHT_SYMTAB: this->Symtab = &Sec; break; case SHT_SYMTAB_SHNDX: { ErrorOr> ErrorOrTable = Obj.getSHNDXTable(Sec); error(ErrorOrTable); this->SymtabSHNDX = *ErrorOrTable; break; } case SHT_STRTAB: case SHT_NULL: break; case SHT_RELA: case SHT_REL: { uint32_t RelocatedSectionIndex = Sec.sh_info; if (RelocatedSectionIndex >= Size) error("Invalid relocated section index"); InputSectionBase *RelocatedSection = Sections[RelocatedSectionIndex]; if (!RelocatedSection) error("Unsupported relocation reference"); if (auto *S = dyn_cast>(RelocatedSection)) { S->RelocSections.push_back(&Sec); } else if (auto *S = dyn_cast>(RelocatedSection)) { if (S->RelocSection) error("Multiple relocation sections to .eh_frame are not supported"); S->RelocSection = &Sec; } else { error("Relocations pointing to SHF_MERGE are not supported"); } break; } default: Sections[I] = createInputSection(Sec); } } } template InputSectionBase * ObjectFile::createInputSection(const Elf_Shdr &Sec) { ErrorOr NameOrErr = this->ELFObj.getSectionName(&Sec); error(NameOrErr); StringRef Name = *NameOrErr; // .note.GNU-stack is a marker section to control the presence of // PT_GNU_STACK segment in outputs. Since the presence of the segment // is controlled only by the command line option (-z execstack) in LLD, // .note.GNU-stack is ignored. if (Name == ".note.GNU-stack") return &InputSection::Discarded; // A MIPS object file has a special section that contains register // usage info, which needs to be handled by the linker specially. if (Config->EMachine == EM_MIPS && Name == ".reginfo") { MipsReginfo = new (Alloc) MipsReginfoInputSection(this, &Sec); return MipsReginfo; } if (Name == ".eh_frame") return new (EHAlloc.Allocate()) EHInputSection(this, &Sec); if (shouldMerge(Sec)) return new (MAlloc.Allocate()) MergeInputSection(this, &Sec); return new (Alloc) InputSection(this, &Sec); } template void ObjectFile::initializeSymbols() { this->initStringTable(); Elf_Sym_Range Syms = this->getNonLocalSymbols(); uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end()); SymbolBodies.reserve(NumSymbols); for (const Elf_Sym &Sym : Syms) SymbolBodies.push_back(createSymbolBody(this->StringTable, &Sym)); } template InputSectionBase * ObjectFile::getSection(const Elf_Sym &Sym) const { uint32_t Index = this->getSectionIndex(Sym); if (Index == 0) return nullptr; if (Index >= Sections.size() || !Sections[Index]) error("Invalid section index"); return Sections[Index]; } template SymbolBody *ObjectFile::createSymbolBody(StringRef StringTable, const Elf_Sym *Sym) { ErrorOr NameOrErr = Sym->getName(StringTable); error(NameOrErr); StringRef Name = *NameOrErr; switch (Sym->st_shndx) { case SHN_UNDEF: return new (Alloc) UndefinedElf(Name, *Sym); case SHN_COMMON: return new (Alloc) DefinedCommon(Name, Sym->st_size, Sym->st_value, Sym->getBinding() == llvm::ELF::STB_WEAK, Sym->getVisibility()); } switch (Sym->getBinding()) { default: error("unexpected binding"); case STB_GLOBAL: case STB_WEAK: case STB_GNU_UNIQUE: { InputSectionBase *Sec = getSection(*Sym); if (Sec == &InputSection::Discarded) return new (Alloc) UndefinedElf(Name, *Sym); return new (Alloc) DefinedRegular(Name, *Sym, Sec); } } } void ArchiveFile::parse() { ErrorOr> FileOrErr = Archive::create(MB); error(FileOrErr, "Failed to parse archive"); File = std::move(*FileOrErr); // Allocate a buffer for Lazy objects. size_t NumSyms = File->getNumberOfSymbols(); LazySymbols.reserve(NumSyms); // Read the symbol table to construct Lazy objects. for (const Archive::Symbol &Sym : File->symbols()) LazySymbols.emplace_back(this, Sym); } // Returns a buffer pointing to a member file containing a given symbol. MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) { ErrorOr COrErr = Sym->getMember(); error(COrErr, "Could not get the member for symbol " + Sym->getName()); const Archive::Child &C = *COrErr; if (!Seen.insert(C.getChildOffset()).second) return MemoryBufferRef(); ErrorOr RefOrErr = C.getMemoryBufferRef(); if (!RefOrErr) error(RefOrErr, "Could not get the buffer for the member defining symbol " + Sym->getName()); return *RefOrErr; } template SharedFile::SharedFile(MemoryBufferRef M) : ELFFileBase(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {} template const typename ELFFile::Elf_Shdr * SharedFile::getSection(const Elf_Sym &Sym) const { uint32_t Index = this->getSectionIndex(Sym); if (Index == 0) return nullptr; ErrorOr Ret = this->ELFObj.getSection(Index); error(Ret); return *Ret; } // Partially parse the shared object file so that we can call // getSoName on this object. template void SharedFile::parseSoName() { typedef typename ELFFile::Elf_Dyn Elf_Dyn; typedef typename ELFFile::uintX_t uintX_t; const Elf_Shdr *DynamicSec = nullptr; const ELFFile Obj = this->ELFObj; for (const Elf_Shdr &Sec : Obj.sections()) { switch (Sec.sh_type) { default: continue; case SHT_DYNSYM: this->Symtab = &Sec; break; case SHT_DYNAMIC: DynamicSec = &Sec; break; case SHT_SYMTAB_SHNDX: { ErrorOr> ErrorOrTable = Obj.getSHNDXTable(Sec); error(ErrorOrTable); this->SymtabSHNDX = *ErrorOrTable; break; } } } this->initStringTable(); SoName = this->getName(); if (!DynamicSec) return; auto *Begin = reinterpret_cast(Obj.base() + DynamicSec->sh_offset); const Elf_Dyn *End = Begin + DynamicSec->sh_size / sizeof(Elf_Dyn); for (const Elf_Dyn &Dyn : make_range(Begin, End)) { if (Dyn.d_tag == DT_SONAME) { uintX_t Val = Dyn.getVal(); if (Val >= this->StringTable.size()) error("Invalid DT_SONAME entry"); SoName = StringRef(this->StringTable.data() + Val); return; } } } // Fully parse the shared object file. This must be called after parseSoName(). template void SharedFile::parseRest() { Elf_Sym_Range Syms = this->getNonLocalSymbols(); uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end()); SymbolBodies.reserve(NumSymbols); for (const Elf_Sym &Sym : Syms) { ErrorOr NameOrErr = Sym.getName(this->StringTable); error(NameOrErr.getError()); StringRef Name = *NameOrErr; if (Sym.isUndefined()) Undefs.push_back(Name); else SymbolBodies.emplace_back(this, Name, Sym); } } template static std::unique_ptr createELFFileAux(MemoryBufferRef MB) { std::unique_ptr Ret = llvm::make_unique(MB); if (!Config->FirstElf) Config->FirstElf = Ret.get(); if (Config->EKind == ELFNoneKind) { Config->EKind = Ret->getELFKind(); Config->EMachine = Ret->getEMachine(); } return std::move(Ret); } template