Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:18

0001 //===- ELFObjectFile.h - ELF object file implementation ---------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file declares the ELFObjectFile template class.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_OBJECT_ELFOBJECTFILE_H
0014 #define LLVM_OBJECT_ELFOBJECTFILE_H
0015 
0016 #include "llvm/ADT/ArrayRef.h"
0017 #include "llvm/ADT/STLExtras.h"
0018 #include "llvm/ADT/StringRef.h"
0019 #include "llvm/ADT/iterator_range.h"
0020 #include "llvm/BinaryFormat/ELF.h"
0021 #include "llvm/Object/Binary.h"
0022 #include "llvm/Object/ELF.h"
0023 #include "llvm/Object/ELFTypes.h"
0024 #include "llvm/Object/Error.h"
0025 #include "llvm/Object/ObjectFile.h"
0026 #include "llvm/Object/SymbolicFile.h"
0027 #include "llvm/Support/Casting.h"
0028 #include "llvm/Support/ELFAttributeParser.h"
0029 #include "llvm/Support/ELFAttributes.h"
0030 #include "llvm/Support/Error.h"
0031 #include "llvm/Support/ErrorHandling.h"
0032 #include "llvm/Support/LEB128.h"
0033 #include "llvm/Support/MemoryBufferRef.h"
0034 #include "llvm/Support/ScopedPrinter.h"
0035 #include "llvm/TargetParser/SubtargetFeature.h"
0036 #include "llvm/TargetParser/Triple.h"
0037 #include <cassert>
0038 #include <cstdint>
0039 
0040 namespace llvm {
0041 
0042 template <typename T> class SmallVectorImpl;
0043 
0044 namespace object {
0045 
0046 constexpr int NumElfSymbolTypes = 16;
0047 extern const llvm::EnumEntry<unsigned> ElfSymbolTypes[NumElfSymbolTypes];
0048 
0049 class elf_symbol_iterator;
0050 
0051 struct ELFPltEntry {
0052   StringRef Section;
0053   std::optional<DataRefImpl> Symbol;
0054   uint64_t Address;
0055 };
0056 
0057 class ELFObjectFileBase : public ObjectFile {
0058   friend class ELFRelocationRef;
0059   friend class ELFSectionRef;
0060   friend class ELFSymbolRef;
0061 
0062   SubtargetFeatures getMIPSFeatures() const;
0063   SubtargetFeatures getARMFeatures() const;
0064   SubtargetFeatures getHexagonFeatures() const;
0065   Expected<SubtargetFeatures> getRISCVFeatures() const;
0066   SubtargetFeatures getLoongArchFeatures() const;
0067 
0068   StringRef getAMDGPUCPUName() const;
0069   StringRef getNVPTXCPUName() const;
0070 
0071 protected:
0072   ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source);
0073 
0074   virtual uint64_t getSymbolSize(DataRefImpl Symb) const = 0;
0075   virtual uint8_t getSymbolBinding(DataRefImpl Symb) const = 0;
0076   virtual uint8_t getSymbolOther(DataRefImpl Symb) const = 0;
0077   virtual uint8_t getSymbolELFType(DataRefImpl Symb) const = 0;
0078 
0079   virtual uint32_t getSectionType(DataRefImpl Sec) const = 0;
0080   virtual uint64_t getSectionFlags(DataRefImpl Sec) const = 0;
0081   virtual uint64_t getSectionOffset(DataRefImpl Sec) const = 0;
0082 
0083   virtual Expected<int64_t> getRelocationAddend(DataRefImpl Rel) const = 0;
0084   virtual Error getBuildAttributes(ELFAttributeParser &Attributes) const = 0;
0085 
0086 public:
0087   using elf_symbol_iterator_range = iterator_range<elf_symbol_iterator>;
0088 
0089   virtual elf_symbol_iterator_range getDynamicSymbolIterators() const = 0;
0090 
0091   /// Returns platform-specific object flags, if any.
0092   virtual unsigned getPlatformFlags() const = 0;
0093 
0094   elf_symbol_iterator_range symbols() const;
0095 
0096   static bool classof(const Binary *v) { return v->isELF(); }
0097 
0098   Expected<SubtargetFeatures> getFeatures() const override;
0099 
0100   std::optional<StringRef> tryGetCPUName() const override;
0101 
0102   void setARMSubArch(Triple &TheTriple) const override;
0103 
0104   virtual uint16_t getEType() const = 0;
0105 
0106   virtual uint16_t getEMachine() const = 0;
0107 
0108   virtual uint8_t getEIdentABIVersion() const = 0;
0109 
0110   std::vector<ELFPltEntry> getPltEntries() const;
0111 
0112   /// Returns a vector containing a symbol version for each dynamic symbol.
0113   /// Returns an empty vector if version sections do not exist.
0114   Expected<std::vector<VersionEntry>> readDynsymVersions() const;
0115 
0116   /// Returns a vector of all BB address maps in the object file. When
0117   /// `TextSectionIndex` is specified, only returns the BB address maps
0118   /// corresponding to the section with that index. When `PGOAnalyses`is
0119   /// specified (PGOAnalyses is not nullptr), the vector is cleared then filled
0120   /// with extra PGO data. `PGOAnalyses` will always be the same length as the
0121   /// return value when it is requested assuming no error occurs. Upon failure,
0122   /// `PGOAnalyses` will be emptied.
0123   Expected<std::vector<BBAddrMap>>
0124   readBBAddrMap(std::optional<unsigned> TextSectionIndex = std::nullopt,
0125                 std::vector<PGOAnalysisMap> *PGOAnalyses = nullptr) const;
0126 
0127   StringRef getCrelDecodeProblem(SectionRef Sec) const;
0128 };
0129 
0130 class ELFSectionRef : public SectionRef {
0131 public:
0132   ELFSectionRef(const SectionRef &B) : SectionRef(B) {
0133     assert(isa<ELFObjectFileBase>(SectionRef::getObject()));
0134   }
0135 
0136   const ELFObjectFileBase *getObject() const {
0137     return cast<ELFObjectFileBase>(SectionRef::getObject());
0138   }
0139 
0140   uint32_t getType() const {
0141     return getObject()->getSectionType(getRawDataRefImpl());
0142   }
0143 
0144   uint64_t getFlags() const {
0145     return getObject()->getSectionFlags(getRawDataRefImpl());
0146   }
0147 
0148   uint64_t getOffset() const {
0149     return getObject()->getSectionOffset(getRawDataRefImpl());
0150   }
0151 };
0152 
0153 class elf_section_iterator : public section_iterator {
0154 public:
0155   elf_section_iterator(const section_iterator &B) : section_iterator(B) {
0156     assert(isa<ELFObjectFileBase>(B->getObject()));
0157   }
0158 
0159   const ELFSectionRef *operator->() const {
0160     return static_cast<const ELFSectionRef *>(section_iterator::operator->());
0161   }
0162 
0163   const ELFSectionRef &operator*() const {
0164     return static_cast<const ELFSectionRef &>(section_iterator::operator*());
0165   }
0166 };
0167 
0168 class ELFSymbolRef : public SymbolRef {
0169 public:
0170   ELFSymbolRef(const SymbolRef &B) : SymbolRef(B) {
0171     assert(isa<ELFObjectFileBase>(SymbolRef::getObject()));
0172   }
0173 
0174   const ELFObjectFileBase *getObject() const {
0175     return cast<ELFObjectFileBase>(BasicSymbolRef::getObject());
0176   }
0177 
0178   uint64_t getSize() const {
0179     return getObject()->getSymbolSize(getRawDataRefImpl());
0180   }
0181 
0182   uint8_t getBinding() const {
0183     return getObject()->getSymbolBinding(getRawDataRefImpl());
0184   }
0185 
0186   uint8_t getOther() const {
0187     return getObject()->getSymbolOther(getRawDataRefImpl());
0188   }
0189 
0190   uint8_t getELFType() const {
0191     return getObject()->getSymbolELFType(getRawDataRefImpl());
0192   }
0193 
0194   StringRef getELFTypeName() const {
0195     uint8_t Type = getELFType();
0196     for (const auto &EE : ElfSymbolTypes) {
0197       if (EE.Value == Type) {
0198         return EE.AltName;
0199       }
0200     }
0201     return "";
0202   }
0203 };
0204 
0205 inline bool operator<(const ELFSymbolRef &A, const ELFSymbolRef &B) {
0206   const DataRefImpl &DRIA = A.getRawDataRefImpl();
0207   const DataRefImpl &DRIB = B.getRawDataRefImpl();
0208   if (DRIA.d.a == DRIB.d.a)
0209     return DRIA.d.b < DRIB.d.b;
0210   return DRIA.d.a < DRIB.d.a;
0211 }
0212 
0213 class elf_symbol_iterator : public symbol_iterator {
0214 public:
0215   elf_symbol_iterator(const basic_symbol_iterator &B)
0216       : symbol_iterator(SymbolRef(B->getRawDataRefImpl(),
0217                                   cast<ELFObjectFileBase>(B->getObject()))) {}
0218 
0219   const ELFSymbolRef *operator->() const {
0220     return static_cast<const ELFSymbolRef *>(symbol_iterator::operator->());
0221   }
0222 
0223   const ELFSymbolRef &operator*() const {
0224     return static_cast<const ELFSymbolRef &>(symbol_iterator::operator*());
0225   }
0226 };
0227 
0228 class ELFRelocationRef : public RelocationRef {
0229 public:
0230   ELFRelocationRef(const RelocationRef &B) : RelocationRef(B) {
0231     assert(isa<ELFObjectFileBase>(RelocationRef::getObject()));
0232   }
0233 
0234   const ELFObjectFileBase *getObject() const {
0235     return cast<ELFObjectFileBase>(RelocationRef::getObject());
0236   }
0237 
0238   Expected<int64_t> getAddend() const {
0239     return getObject()->getRelocationAddend(getRawDataRefImpl());
0240   }
0241 };
0242 
0243 class elf_relocation_iterator : public relocation_iterator {
0244 public:
0245   elf_relocation_iterator(const relocation_iterator &B)
0246       : relocation_iterator(RelocationRef(
0247             B->getRawDataRefImpl(), cast<ELFObjectFileBase>(B->getObject()))) {}
0248 
0249   const ELFRelocationRef *operator->() const {
0250     return static_cast<const ELFRelocationRef *>(
0251         relocation_iterator::operator->());
0252   }
0253 
0254   const ELFRelocationRef &operator*() const {
0255     return static_cast<const ELFRelocationRef &>(
0256         relocation_iterator::operator*());
0257   }
0258 };
0259 
0260 inline ELFObjectFileBase::elf_symbol_iterator_range
0261 ELFObjectFileBase::symbols() const {
0262   return elf_symbol_iterator_range(symbol_begin(), symbol_end());
0263 }
0264 
0265 template <class ELFT> class ELFObjectFile : public ELFObjectFileBase {
0266   uint16_t getEMachine() const override;
0267   uint16_t getEType() const override;
0268   uint8_t getEIdentABIVersion() const override;
0269   uint64_t getSymbolSize(DataRefImpl Sym) const override;
0270 
0271 public:
0272   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
0273 
0274   SectionRef toSectionRef(const Elf_Shdr *Sec) const {
0275     return SectionRef(toDRI(Sec), this);
0276   }
0277 
0278   ELFSymbolRef toSymbolRef(const Elf_Shdr *SymTable, unsigned SymbolNum) const {
0279     return ELFSymbolRef({toDRI(SymTable, SymbolNum), this});
0280   }
0281 
0282   bool IsContentValid() const { return ContentValid; }
0283 
0284 private:
0285   ELFObjectFile(MemoryBufferRef Object, ELFFile<ELFT> EF,
0286                 const Elf_Shdr *DotDynSymSec, const Elf_Shdr *DotSymtabSec,
0287                 const Elf_Shdr *DotSymtabShndxSec);
0288 
0289   bool ContentValid = false;
0290 
0291 protected:
0292   ELFFile<ELFT> EF;
0293 
0294   const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
0295   const Elf_Shdr *DotSymtabSec = nullptr; // Symbol table section.
0296   const Elf_Shdr *DotSymtabShndxSec = nullptr; // SHT_SYMTAB_SHNDX section.
0297 
0298   // Hold CREL relocations for SectionRef::relocations().
0299   mutable SmallVector<SmallVector<Elf_Crel, 0>, 0> Crels;
0300   mutable SmallVector<std::string, 0> CrelDecodeProblems;
0301 
0302   Error initContent() override;
0303 
0304   void moveSymbolNext(DataRefImpl &Symb) const override;
0305   Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
0306   Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
0307   uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
0308   uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
0309   uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
0310   Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
0311   uint8_t getSymbolBinding(DataRefImpl Symb) const override;
0312   uint8_t getSymbolOther(DataRefImpl Symb) const override;
0313   uint8_t getSymbolELFType(DataRefImpl Symb) const override;
0314   Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
0315   Expected<section_iterator> getSymbolSection(const Elf_Sym *Symb,
0316                                               const Elf_Shdr *SymTab) const;
0317   Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
0318 
0319   void moveSectionNext(DataRefImpl &Sec) const override;
0320   Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
0321   uint64_t getSectionAddress(DataRefImpl Sec) const override;
0322   uint64_t getSectionIndex(DataRefImpl Sec) const override;
0323   uint64_t getSectionSize(DataRefImpl Sec) const override;
0324   Expected<ArrayRef<uint8_t>>
0325   getSectionContents(DataRefImpl Sec) const override;
0326   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
0327   bool isSectionCompressed(DataRefImpl Sec) const override;
0328   bool isSectionText(DataRefImpl Sec) const override;
0329   bool isSectionData(DataRefImpl Sec) const override;
0330   bool isSectionBSS(DataRefImpl Sec) const override;
0331   bool isSectionVirtual(DataRefImpl Sec) const override;
0332   bool isBerkeleyText(DataRefImpl Sec) const override;
0333   bool isBerkeleyData(DataRefImpl Sec) const override;
0334   bool isDebugSection(DataRefImpl Sec) const override;
0335   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
0336   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
0337   std::vector<SectionRef> dynamic_relocation_sections() const override;
0338   Expected<section_iterator>
0339   getRelocatedSection(DataRefImpl Sec) const override;
0340 
0341   void moveRelocationNext(DataRefImpl &Rel) const override;
0342   uint64_t getRelocationOffset(DataRefImpl Rel) const override;
0343   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
0344   uint64_t getRelocationType(DataRefImpl Rel) const override;
0345   void getRelocationTypeName(DataRefImpl Rel,
0346                              SmallVectorImpl<char> &Result) const override;
0347 
0348   uint32_t getSectionType(DataRefImpl Sec) const override;
0349   uint64_t getSectionFlags(DataRefImpl Sec) const override;
0350   uint64_t getSectionOffset(DataRefImpl Sec) const override;
0351   StringRef getRelocationTypeName(uint32_t Type) const;
0352 
0353   DataRefImpl toDRI(const Elf_Shdr *SymTable, unsigned SymbolNum) const {
0354     DataRefImpl DRI;
0355     if (!SymTable) {
0356       DRI.d.a = 0;
0357       DRI.d.b = 0;
0358       return DRI;
0359     }
0360     assert(SymTable->sh_type == ELF::SHT_SYMTAB ||
0361            SymTable->sh_type == ELF::SHT_DYNSYM);
0362 
0363     auto SectionsOrErr = EF.sections();
0364     if (!SectionsOrErr) {
0365       DRI.d.a = 0;
0366       DRI.d.b = 0;
0367       return DRI;
0368     }
0369     uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
0370     unsigned SymTableIndex =
0371         (reinterpret_cast<uintptr_t>(SymTable) - SHT) / sizeof(Elf_Shdr);
0372 
0373     DRI.d.a = SymTableIndex;
0374     DRI.d.b = SymbolNum;
0375     return DRI;
0376   }
0377 
0378   const Elf_Shdr *toELFShdrIter(DataRefImpl Sec) const {
0379     return reinterpret_cast<const Elf_Shdr *>(Sec.p);
0380   }
0381 
0382   DataRefImpl toDRI(const Elf_Shdr *Sec) const {
0383     DataRefImpl DRI;
0384     DRI.p = reinterpret_cast<uintptr_t>(Sec);
0385     return DRI;
0386   }
0387 
0388   DataRefImpl toDRI(const Elf_Dyn *Dyn) const {
0389     DataRefImpl DRI;
0390     DRI.p = reinterpret_cast<uintptr_t>(Dyn);
0391     return DRI;
0392   }
0393 
0394   bool isExportedToOtherDSO(const Elf_Sym *ESym) const {
0395     unsigned char Binding = ESym->getBinding();
0396     unsigned char Visibility = ESym->getVisibility();
0397 
0398     // A symbol is exported if its binding is either GLOBAL or WEAK, and its
0399     // visibility is either DEFAULT or PROTECTED. All other symbols are not
0400     // exported.
0401     return (
0402         (Binding == ELF::STB_GLOBAL || Binding == ELF::STB_WEAK ||
0403          Binding == ELF::STB_GNU_UNIQUE) &&
0404         (Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_PROTECTED));
0405   }
0406 
0407   Error getBuildAttributes(ELFAttributeParser &Attributes) const override {
0408     uint32_t Type;
0409     switch (getEMachine()) {
0410     case ELF::EM_ARM:
0411       Type = ELF::SHT_ARM_ATTRIBUTES;
0412       break;
0413     case ELF::EM_RISCV:
0414       Type = ELF::SHT_RISCV_ATTRIBUTES;
0415       break;
0416     case ELF::EM_HEXAGON:
0417       Type = ELF::SHT_HEXAGON_ATTRIBUTES;
0418       break;
0419     default:
0420       return Error::success();
0421     }
0422 
0423     auto SectionsOrErr = EF.sections();
0424     if (!SectionsOrErr)
0425       return SectionsOrErr.takeError();
0426     for (const Elf_Shdr &Sec : *SectionsOrErr) {
0427       if (Sec.sh_type != Type)
0428         continue;
0429       auto ErrorOrContents = EF.getSectionContents(Sec);
0430       if (!ErrorOrContents)
0431         return ErrorOrContents.takeError();
0432 
0433       auto Contents = ErrorOrContents.get();
0434       if (Contents[0] != ELFAttrs::Format_Version || Contents.size() == 1)
0435         return Error::success();
0436 
0437       if (Error E = Attributes.parse(Contents, ELFT::Endianness))
0438         return E;
0439       break;
0440     }
0441     return Error::success();
0442   }
0443 
0444   // This flag is used for classof, to distinguish ELFObjectFile from
0445   // its subclass. If more subclasses will be created, this flag will
0446   // have to become an enum.
0447   bool isDyldELFObject = false;
0448 
0449 public:
0450   ELFObjectFile(ELFObjectFile<ELFT> &&Other);
0451   static Expected<ELFObjectFile<ELFT>> create(MemoryBufferRef Object,
0452                                               bool InitContent = true);
0453 
0454   const Elf_Rel *getRel(DataRefImpl Rel) const;
0455   const Elf_Rela *getRela(DataRefImpl Rela) const;
0456   Elf_Crel getCrel(DataRefImpl Crel) const;
0457 
0458   Expected<const Elf_Sym *> getSymbol(DataRefImpl Sym) const {
0459     return EF.template getEntry<Elf_Sym>(Sym.d.a, Sym.d.b);
0460   }
0461 
0462   /// Get the relocation section that contains \a Rel.
0463   const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
0464     auto RelSecOrErr = EF.getSection(Rel.d.a);
0465     if (!RelSecOrErr)
0466       report_fatal_error(
0467           Twine(errorToErrorCode(RelSecOrErr.takeError()).message()));
0468     return *RelSecOrErr;
0469   }
0470 
0471   const Elf_Shdr *getSection(DataRefImpl Sec) const {
0472     return reinterpret_cast<const Elf_Shdr *>(Sec.p);
0473   }
0474 
0475   basic_symbol_iterator symbol_begin() const override;
0476   basic_symbol_iterator symbol_end() const override;
0477 
0478   bool is64Bit() const override { return getBytesInAddress() == 8; }
0479 
0480   elf_symbol_iterator dynamic_symbol_begin() const;
0481   elf_symbol_iterator dynamic_symbol_end() const;
0482 
0483   section_iterator section_begin() const override;
0484   section_iterator section_end() const override;
0485 
0486   Expected<int64_t> getRelocationAddend(DataRefImpl Rel) const override;
0487 
0488   uint8_t getBytesInAddress() const override;
0489   StringRef getFileFormatName() const override;
0490   Triple::ArchType getArch() const override;
0491   Triple::OSType getOS() const override;
0492   Expected<uint64_t> getStartAddress() const override;
0493 
0494   unsigned getPlatformFlags() const override { return EF.getHeader().e_flags; }
0495 
0496   const ELFFile<ELFT> &getELFFile() const { return EF; }
0497 
0498   bool isDyldType() const { return isDyldELFObject; }
0499   static bool classof(const Binary *v) {
0500     return v->getType() ==
0501            getELFType(ELFT::Endianness == llvm::endianness::little,
0502                       ELFT::Is64Bits);
0503   }
0504 
0505   elf_symbol_iterator_range getDynamicSymbolIterators() const override;
0506 
0507   bool isRelocatableObject() const override;
0508 
0509   void createFakeSections() { EF.createFakeSections(); }
0510 
0511   StringRef getCrelDecodeProblem(DataRefImpl Sec) const;
0512 };
0513 
0514 using ELF32LEObjectFile = ELFObjectFile<ELF32LE>;
0515 using ELF64LEObjectFile = ELFObjectFile<ELF64LE>;
0516 using ELF32BEObjectFile = ELFObjectFile<ELF32BE>;
0517 using ELF64BEObjectFile = ELFObjectFile<ELF64BE>;
0518 
0519 template <class ELFT>
0520 void ELFObjectFile<ELFT>::moveSymbolNext(DataRefImpl &Sym) const {
0521   ++Sym.d.b;
0522 }
0523 
0524 template <class ELFT> Error ELFObjectFile<ELFT>::initContent() {
0525   auto SectionsOrErr = EF.sections();
0526   if (!SectionsOrErr)
0527     return SectionsOrErr.takeError();
0528 
0529   for (const Elf_Shdr &Sec : *SectionsOrErr) {
0530     switch (Sec.sh_type) {
0531     case ELF::SHT_DYNSYM: {
0532       if (!DotDynSymSec)
0533         DotDynSymSec = &Sec;
0534       break;
0535     }
0536     case ELF::SHT_SYMTAB: {
0537       if (!DotSymtabSec)
0538         DotSymtabSec = &Sec;
0539       break;
0540     }
0541     case ELF::SHT_SYMTAB_SHNDX: {
0542       if (!DotSymtabShndxSec)
0543         DotSymtabShndxSec = &Sec;
0544       break;
0545     }
0546     }
0547   }
0548 
0549   ContentValid = true;
0550   return Error::success();
0551 }
0552 
0553 template <class ELFT>
0554 Expected<StringRef> ELFObjectFile<ELFT>::getSymbolName(DataRefImpl Sym) const {
0555   Expected<const Elf_Sym *> SymOrErr = getSymbol(Sym);
0556   if (!SymOrErr)
0557     return SymOrErr.takeError();
0558   auto SymTabOrErr = EF.getSection(Sym.d.a);
0559   if (!SymTabOrErr)
0560     return SymTabOrErr.takeError();
0561   const Elf_Shdr *SymTableSec = *SymTabOrErr;
0562   auto StrTabOrErr = EF.getSection(SymTableSec->sh_link);
0563   if (!StrTabOrErr)
0564     return StrTabOrErr.takeError();
0565   const Elf_Shdr *StringTableSec = *StrTabOrErr;
0566   auto SymStrTabOrErr = EF.getStringTable(*StringTableSec);
0567   if (!SymStrTabOrErr)
0568     return SymStrTabOrErr.takeError();
0569   Expected<StringRef> Name = (*SymOrErr)->getName(*SymStrTabOrErr);
0570   if (Name && !Name->empty())
0571     return Name;
0572 
0573   // If the symbol name is empty use the section name.
0574   if ((*SymOrErr)->getType() == ELF::STT_SECTION) {
0575     Expected<section_iterator> SecOrErr = getSymbolSection(Sym);
0576     if (SecOrErr)
0577       return (*SecOrErr)->getName();
0578     return SecOrErr.takeError();
0579   }
0580   return Name;
0581 }
0582 
0583 template <class ELFT>
0584 uint64_t ELFObjectFile<ELFT>::getSectionFlags(DataRefImpl Sec) const {
0585   return getSection(Sec)->sh_flags;
0586 }
0587 
0588 template <class ELFT>
0589 uint32_t ELFObjectFile<ELFT>::getSectionType(DataRefImpl Sec) const {
0590   return getSection(Sec)->sh_type;
0591 }
0592 
0593 template <class ELFT>
0594 uint64_t ELFObjectFile<ELFT>::getSectionOffset(DataRefImpl Sec) const {
0595   return getSection(Sec)->sh_offset;
0596 }
0597 
0598 template <class ELFT>
0599 uint64_t ELFObjectFile<ELFT>::getSymbolValueImpl(DataRefImpl Symb) const {
0600   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
0601   if (!SymOrErr)
0602     report_fatal_error(SymOrErr.takeError());
0603 
0604   uint64_t Ret = (*SymOrErr)->st_value;
0605   if ((*SymOrErr)->st_shndx == ELF::SHN_ABS)
0606     return Ret;
0607 
0608   const Elf_Ehdr &Header = EF.getHeader();
0609   // Clear the ARM/Thumb or microMIPS indicator flag.
0610   if ((Header.e_machine == ELF::EM_ARM || Header.e_machine == ELF::EM_MIPS) &&
0611       (*SymOrErr)->getType() == ELF::STT_FUNC)
0612     Ret &= ~1;
0613 
0614   return Ret;
0615 }
0616 
0617 template <class ELFT>
0618 Expected<uint64_t>
0619 ELFObjectFile<ELFT>::getSymbolAddress(DataRefImpl Symb) const {
0620   Expected<uint64_t> SymbolValueOrErr = getSymbolValue(Symb);
0621   if (!SymbolValueOrErr)
0622     // TODO: Test this error.
0623     return SymbolValueOrErr.takeError();
0624 
0625   uint64_t Result = *SymbolValueOrErr;
0626   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
0627   if (!SymOrErr)
0628     return SymOrErr.takeError();
0629 
0630   switch ((*SymOrErr)->st_shndx) {
0631   case ELF::SHN_COMMON:
0632   case ELF::SHN_UNDEF:
0633   case ELF::SHN_ABS:
0634     return Result;
0635   }
0636 
0637   auto SymTabOrErr = EF.getSection(Symb.d.a);
0638   if (!SymTabOrErr)
0639     return SymTabOrErr.takeError();
0640 
0641   if (EF.getHeader().e_type == ELF::ET_REL) {
0642     ArrayRef<Elf_Word> ShndxTable;
0643     if (DotSymtabShndxSec) {
0644       // TODO: Test this error.
0645       if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
0646               EF.getSHNDXTable(*DotSymtabShndxSec))
0647         ShndxTable = *ShndxTableOrErr;
0648       else
0649         return ShndxTableOrErr.takeError();
0650     }
0651 
0652     Expected<const Elf_Shdr *> SectionOrErr =
0653         EF.getSection(**SymOrErr, *SymTabOrErr, ShndxTable);
0654     if (!SectionOrErr)
0655       return SectionOrErr.takeError();
0656     const Elf_Shdr *Section = *SectionOrErr;
0657     if (Section)
0658       Result += Section->sh_addr;
0659   }
0660 
0661   return Result;
0662 }
0663 
0664 template <class ELFT>
0665 uint32_t ELFObjectFile<ELFT>::getSymbolAlignment(DataRefImpl Symb) const {
0666   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
0667   if (!SymOrErr)
0668     report_fatal_error(SymOrErr.takeError());
0669   if ((*SymOrErr)->st_shndx == ELF::SHN_COMMON)
0670     return (*SymOrErr)->st_value;
0671   return 0;
0672 }
0673 
0674 template <class ELFT>
0675 uint16_t ELFObjectFile<ELFT>::getEMachine() const {
0676   return EF.getHeader().e_machine;
0677 }
0678 
0679 template <class ELFT> uint16_t ELFObjectFile<ELFT>::getEType() const {
0680   return EF.getHeader().e_type;
0681 }
0682 
0683 template <class ELFT> uint8_t ELFObjectFile<ELFT>::getEIdentABIVersion() const {
0684   return EF.getHeader().e_ident[ELF::EI_ABIVERSION];
0685 }
0686 
0687 template <class ELFT>
0688 uint64_t ELFObjectFile<ELFT>::getSymbolSize(DataRefImpl Sym) const {
0689   Expected<const Elf_Sym *> SymOrErr = getSymbol(Sym);
0690   if (!SymOrErr)
0691     report_fatal_error(SymOrErr.takeError());
0692   return (*SymOrErr)->st_size;
0693 }
0694 
0695 template <class ELFT>
0696 uint64_t ELFObjectFile<ELFT>::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
0697   return getSymbolSize(Symb);
0698 }
0699 
0700 template <class ELFT>
0701 uint8_t ELFObjectFile<ELFT>::getSymbolBinding(DataRefImpl Symb) const {
0702   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
0703   if (!SymOrErr)
0704     report_fatal_error(SymOrErr.takeError());
0705   return (*SymOrErr)->getBinding();
0706 }
0707 
0708 template <class ELFT>
0709 uint8_t ELFObjectFile<ELFT>::getSymbolOther(DataRefImpl Symb) const {
0710   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
0711   if (!SymOrErr)
0712     report_fatal_error(SymOrErr.takeError());
0713   return (*SymOrErr)->st_other;
0714 }
0715 
0716 template <class ELFT>
0717 uint8_t ELFObjectFile<ELFT>::getSymbolELFType(DataRefImpl Symb) const {
0718   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
0719   if (!SymOrErr)
0720     report_fatal_error(SymOrErr.takeError());
0721   return (*SymOrErr)->getType();
0722 }
0723 
0724 template <class ELFT>
0725 Expected<SymbolRef::Type>
0726 ELFObjectFile<ELFT>::getSymbolType(DataRefImpl Symb) const {
0727   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
0728   if (!SymOrErr)
0729     return SymOrErr.takeError();
0730 
0731   switch ((*SymOrErr)->getType()) {
0732   case ELF::STT_NOTYPE:
0733     return SymbolRef::ST_Unknown;
0734   case ELF::STT_SECTION:
0735     return SymbolRef::ST_Debug;
0736   case ELF::STT_FILE:
0737     return SymbolRef::ST_File;
0738   case ELF::STT_FUNC:
0739     return SymbolRef::ST_Function;
0740   case ELF::STT_OBJECT:
0741   case ELF::STT_COMMON:
0742     return SymbolRef::ST_Data;
0743   case ELF::STT_TLS:
0744   default:
0745     return SymbolRef::ST_Other;
0746   }
0747 }
0748 
0749 template <class ELFT>
0750 Expected<uint32_t> ELFObjectFile<ELFT>::getSymbolFlags(DataRefImpl Sym) const {
0751   Expected<const Elf_Sym *> SymOrErr = getSymbol(Sym);
0752   if (!SymOrErr)
0753     return SymOrErr.takeError();
0754 
0755   const Elf_Sym *ESym = *SymOrErr;
0756   uint32_t Result = SymbolRef::SF_None;
0757 
0758   if (ESym->getBinding() != ELF::STB_LOCAL)
0759     Result |= SymbolRef::SF_Global;
0760 
0761   if (ESym->getBinding() == ELF::STB_WEAK)
0762     Result |= SymbolRef::SF_Weak;
0763 
0764   if (ESym->st_shndx == ELF::SHN_ABS)
0765     Result |= SymbolRef::SF_Absolute;
0766 
0767   if (ESym->getType() == ELF::STT_FILE || ESym->getType() == ELF::STT_SECTION)
0768     Result |= SymbolRef::SF_FormatSpecific;
0769 
0770   if (Expected<typename ELFT::SymRange> SymbolsOrErr =
0771           EF.symbols(DotSymtabSec)) {
0772     // Set the SF_FormatSpecific flag for the 0-index null symbol.
0773     if (ESym == SymbolsOrErr->begin())
0774       Result |= SymbolRef::SF_FormatSpecific;
0775   } else
0776     // TODO: Test this error.
0777     return SymbolsOrErr.takeError();
0778 
0779   if (Expected<typename ELFT::SymRange> SymbolsOrErr =
0780           EF.symbols(DotDynSymSec)) {
0781     // Set the SF_FormatSpecific flag for the 0-index null symbol.
0782     if (ESym == SymbolsOrErr->begin())
0783       Result |= SymbolRef::SF_FormatSpecific;
0784   } else
0785     // TODO: Test this error.
0786     return SymbolsOrErr.takeError();
0787 
0788   if (EF.getHeader().e_machine == ELF::EM_AARCH64) {
0789     if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
0790       StringRef Name = *NameOrErr;
0791       if (Name.starts_with("$d") || Name.starts_with("$x"))
0792         Result |= SymbolRef::SF_FormatSpecific;
0793     } else {
0794       // TODO: Actually report errors helpfully.
0795       consumeError(NameOrErr.takeError());
0796     }
0797   } else if (EF.getHeader().e_machine == ELF::EM_ARM) {
0798     if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
0799       StringRef Name = *NameOrErr;
0800       // TODO Investigate why empty name symbols need to be marked.
0801       if (Name.empty() || Name.starts_with("$d") || Name.starts_with("$t") ||
0802           Name.starts_with("$a"))
0803         Result |= SymbolRef::SF_FormatSpecific;
0804     } else {
0805       // TODO: Actually report errors helpfully.
0806       consumeError(NameOrErr.takeError());
0807     }
0808     if (ESym->getType() == ELF::STT_FUNC && (ESym->st_value & 1) == 1)
0809       Result |= SymbolRef::SF_Thumb;
0810   } else if (EF.getHeader().e_machine == ELF::EM_CSKY) {
0811     if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
0812       StringRef Name = *NameOrErr;
0813       if (Name.starts_with("$d") || Name.starts_with("$t"))
0814         Result |= SymbolRef::SF_FormatSpecific;
0815     } else {
0816       // TODO: Actually report errors helpfully.
0817       consumeError(NameOrErr.takeError());
0818     }
0819   } else if (EF.getHeader().e_machine == ELF::EM_RISCV) {
0820     if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
0821       StringRef Name = *NameOrErr;
0822       // Mark fake labels (used for label differences) and mapping symbols.
0823       if (Name == ".L0 " || Name.starts_with("$d") || Name.starts_with("$x"))
0824         Result |= SymbolRef::SF_FormatSpecific;
0825     } else {
0826       // TODO: Actually report errors helpfully.
0827       consumeError(NameOrErr.takeError());
0828     }
0829   }
0830 
0831   if (ESym->st_shndx == ELF::SHN_UNDEF)
0832     Result |= SymbolRef::SF_Undefined;
0833 
0834   if (ESym->getType() == ELF::STT_COMMON || ESym->st_shndx == ELF::SHN_COMMON)
0835     Result |= SymbolRef::SF_Common;
0836 
0837   if (isExportedToOtherDSO(ESym))
0838     Result |= SymbolRef::SF_Exported;
0839 
0840   if (ESym->getType() == ELF::STT_GNU_IFUNC)
0841     Result |= SymbolRef::SF_Indirect;
0842 
0843   if (ESym->getVisibility() == ELF::STV_HIDDEN)
0844     Result |= SymbolRef::SF_Hidden;
0845 
0846   return Result;
0847 }
0848 
0849 template <class ELFT>
0850 Expected<section_iterator>
0851 ELFObjectFile<ELFT>::getSymbolSection(const Elf_Sym *ESym,
0852                                       const Elf_Shdr *SymTab) const {
0853   ArrayRef<Elf_Word> ShndxTable;
0854   if (DotSymtabShndxSec) {
0855     // TODO: Test this error.
0856     Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
0857         EF.getSHNDXTable(*DotSymtabShndxSec);
0858     if (!ShndxTableOrErr)
0859       return ShndxTableOrErr.takeError();
0860     ShndxTable = *ShndxTableOrErr;
0861   }
0862 
0863   auto ESecOrErr = EF.getSection(*ESym, SymTab, ShndxTable);
0864   if (!ESecOrErr)
0865     return ESecOrErr.takeError();
0866 
0867   const Elf_Shdr *ESec = *ESecOrErr;
0868   if (!ESec)
0869     return section_end();
0870 
0871   DataRefImpl Sec;
0872   Sec.p = reinterpret_cast<intptr_t>(ESec);
0873   return section_iterator(SectionRef(Sec, this));
0874 }
0875 
0876 template <class ELFT>
0877 Expected<section_iterator>
0878 ELFObjectFile<ELFT>::getSymbolSection(DataRefImpl Symb) const {
0879   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
0880   if (!SymOrErr)
0881     return SymOrErr.takeError();
0882 
0883   auto SymTabOrErr = EF.getSection(Symb.d.a);
0884   if (!SymTabOrErr)
0885     return SymTabOrErr.takeError();
0886   return getSymbolSection(*SymOrErr, *SymTabOrErr);
0887 }
0888 
0889 template <class ELFT>
0890 void ELFObjectFile<ELFT>::moveSectionNext(DataRefImpl &Sec) const {
0891   const Elf_Shdr *ESec = getSection(Sec);
0892   Sec = toDRI(++ESec);
0893 }
0894 
0895 template <class ELFT>
0896 Expected<StringRef> ELFObjectFile<ELFT>::getSectionName(DataRefImpl Sec) const {
0897   return EF.getSectionName(*getSection(Sec));
0898 }
0899 
0900 template <class ELFT>
0901 uint64_t ELFObjectFile<ELFT>::getSectionAddress(DataRefImpl Sec) const {
0902   return getSection(Sec)->sh_addr;
0903 }
0904 
0905 template <class ELFT>
0906 uint64_t ELFObjectFile<ELFT>::getSectionIndex(DataRefImpl Sec) const {
0907   auto SectionsOrErr = EF.sections();
0908   handleAllErrors(std::move(SectionsOrErr.takeError()),
0909                   [](const ErrorInfoBase &) {
0910                     llvm_unreachable("unable to get section index");
0911                   });
0912   const Elf_Shdr *First = SectionsOrErr->begin();
0913   return getSection(Sec) - First;
0914 }
0915 
0916 template <class ELFT>
0917 uint64_t ELFObjectFile<ELFT>::getSectionSize(DataRefImpl Sec) const {
0918   return getSection(Sec)->sh_size;
0919 }
0920 
0921 template <class ELFT>
0922 Expected<ArrayRef<uint8_t>>
0923 ELFObjectFile<ELFT>::getSectionContents(DataRefImpl Sec) const {
0924   const Elf_Shdr *EShdr = getSection(Sec);
0925   if (EShdr->sh_type == ELF::SHT_NOBITS)
0926     return ArrayRef((const uint8_t *)base(), (size_t)0);
0927   if (Error E =
0928           checkOffset(getMemoryBufferRef(),
0929                       (uintptr_t)base() + EShdr->sh_offset, EShdr->sh_size))
0930     return std::move(E);
0931   return ArrayRef((const uint8_t *)base() + EShdr->sh_offset, EShdr->sh_size);
0932 }
0933 
0934 template <class ELFT>
0935 uint64_t ELFObjectFile<ELFT>::getSectionAlignment(DataRefImpl Sec) const {
0936   return getSection(Sec)->sh_addralign;
0937 }
0938 
0939 template <class ELFT>
0940 bool ELFObjectFile<ELFT>::isSectionCompressed(DataRefImpl Sec) const {
0941   return getSection(Sec)->sh_flags & ELF::SHF_COMPRESSED;
0942 }
0943 
0944 template <class ELFT>
0945 bool ELFObjectFile<ELFT>::isSectionText(DataRefImpl Sec) const {
0946   return getSection(Sec)->sh_flags & ELF::SHF_EXECINSTR;
0947 }
0948 
0949 template <class ELFT>
0950 bool ELFObjectFile<ELFT>::isSectionData(DataRefImpl Sec) const {
0951   const Elf_Shdr *EShdr = getSection(Sec);
0952   return (EShdr->sh_flags & ELF::SHF_ALLOC) &&
0953          !(EShdr->sh_flags & ELF::SHF_EXECINSTR) &&
0954          EShdr->sh_type != ELF::SHT_NOBITS;
0955 }
0956 
0957 template <class ELFT>
0958 bool ELFObjectFile<ELFT>::isSectionBSS(DataRefImpl Sec) const {
0959   const Elf_Shdr *EShdr = getSection(Sec);
0960   return EShdr->sh_flags & ELF::SHF_ALLOC && EShdr->sh_type == ELF::SHT_NOBITS;
0961 }
0962 
0963 template <class ELFT>
0964 std::vector<SectionRef>
0965 ELFObjectFile<ELFT>::dynamic_relocation_sections() const {
0966   std::vector<SectionRef> Res;
0967   std::vector<uintptr_t> Offsets;
0968 
0969   auto SectionsOrErr = EF.sections();
0970   if (!SectionsOrErr)
0971     return Res;
0972 
0973   for (const Elf_Shdr &Sec : *SectionsOrErr) {
0974     if (Sec.sh_type != ELF::SHT_DYNAMIC)
0975       continue;
0976     Elf_Dyn *Dynamic =
0977         reinterpret_cast<Elf_Dyn *>((uintptr_t)base() + Sec.sh_offset);
0978     for (; Dynamic->d_tag != ELF::DT_NULL; Dynamic++) {
0979       if (Dynamic->d_tag == ELF::DT_REL || Dynamic->d_tag == ELF::DT_RELA ||
0980           Dynamic->d_tag == ELF::DT_JMPREL) {
0981         Offsets.push_back(Dynamic->d_un.d_val);
0982       }
0983     }
0984   }
0985   for (const Elf_Shdr &Sec : *SectionsOrErr) {
0986     if (is_contained(Offsets, Sec.sh_addr))
0987       Res.emplace_back(toDRI(&Sec), this);
0988   }
0989   return Res;
0990 }
0991 
0992 template <class ELFT>
0993 bool ELFObjectFile<ELFT>::isSectionVirtual(DataRefImpl Sec) const {
0994   return getSection(Sec)->sh_type == ELF::SHT_NOBITS;
0995 }
0996 
0997 template <class ELFT>
0998 bool ELFObjectFile<ELFT>::isBerkeleyText(DataRefImpl Sec) const {
0999   return getSection(Sec)->sh_flags & ELF::SHF_ALLOC &&
1000          (getSection(Sec)->sh_flags & ELF::SHF_EXECINSTR ||
1001           !(getSection(Sec)->sh_flags & ELF::SHF_WRITE));
1002 }
1003 
1004 template <class ELFT>
1005 bool ELFObjectFile<ELFT>::isBerkeleyData(DataRefImpl Sec) const {
1006   const Elf_Shdr *EShdr = getSection(Sec);
1007   return !isBerkeleyText(Sec) && EShdr->sh_type != ELF::SHT_NOBITS &&
1008          EShdr->sh_flags & ELF::SHF_ALLOC;
1009 }
1010 
1011 template <class ELFT>
1012 bool ELFObjectFile<ELFT>::isDebugSection(DataRefImpl Sec) const {
1013   Expected<StringRef> SectionNameOrErr = getSectionName(Sec);
1014   if (!SectionNameOrErr) {
1015     // TODO: Report the error message properly.
1016     consumeError(SectionNameOrErr.takeError());
1017     return false;
1018   }
1019   StringRef SectionName = SectionNameOrErr.get();
1020   return SectionName.starts_with(".debug") ||
1021          SectionName.starts_with(".zdebug") || SectionName == ".gdb_index";
1022 }
1023 
1024 template <class ELFT>
1025 relocation_iterator
1026 ELFObjectFile<ELFT>::section_rel_begin(DataRefImpl Sec) const {
1027   DataRefImpl RelData;
1028   auto SectionsOrErr = EF.sections();
1029   if (!SectionsOrErr)
1030     return relocation_iterator(RelocationRef());
1031   uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
1032   RelData.d.a = (Sec.p - SHT) / EF.getHeader().e_shentsize;
1033   RelData.d.b = 0;
1034   if (reinterpret_cast<const Elf_Shdr *>(Sec.p)->sh_type == ELF::SHT_CREL) {
1035     if (RelData.d.a + 1 > Crels.size())
1036       Crels.resize(RelData.d.a + 1);
1037     auto &Crel = Crels[RelData.d.a];
1038     if (Crel.empty()) {
1039       ArrayRef<uint8_t> Content = cantFail(getSectionContents(Sec));
1040       size_t I = 0;
1041       Error Err = decodeCrel<ELFT::Is64Bits>(
1042           Content, [&](uint64_t Count, bool) { Crel.resize(Count); },
1043           [&](Elf_Crel Crel) { Crels[RelData.d.a][I++] = Crel; });
1044       if (Err) {
1045         Crel.assign(1, Elf_Crel{0, 0, 0, 0});
1046         if (RelData.d.a + 1 > CrelDecodeProblems.size())
1047           CrelDecodeProblems.resize(RelData.d.a + 1);
1048         CrelDecodeProblems[RelData.d.a] = toString(std::move(Err));
1049       }
1050     }
1051   }
1052   return relocation_iterator(RelocationRef(RelData, this));
1053 }
1054 
1055 template <class ELFT>
1056 relocation_iterator
1057 ELFObjectFile<ELFT>::section_rel_end(DataRefImpl Sec) const {
1058   const Elf_Shdr *S = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1059   relocation_iterator Begin = section_rel_begin(Sec);
1060   DataRefImpl RelData = Begin->getRawDataRefImpl();
1061   if (S->sh_type == ELF::SHT_CREL) {
1062     RelData.d.b = Crels[RelData.d.a].size();
1063     return relocation_iterator(RelocationRef(RelData, this));
1064   }
1065   if (S->sh_type != ELF::SHT_RELA && S->sh_type != ELF::SHT_REL)
1066     return Begin;
1067   const Elf_Shdr *RelSec = getRelSection(RelData);
1068 
1069   // Error check sh_link here so that getRelocationSymbol can just use it.
1070   auto SymSecOrErr = EF.getSection(RelSec->sh_link);
1071   if (!SymSecOrErr)
1072     report_fatal_error(
1073         Twine(errorToErrorCode(SymSecOrErr.takeError()).message()));
1074 
1075   RelData.d.b += S->sh_size / S->sh_entsize;
1076   return relocation_iterator(RelocationRef(RelData, this));
1077 }
1078 
1079 template <class ELFT>
1080 Expected<section_iterator>
1081 ELFObjectFile<ELFT>::getRelocatedSection(DataRefImpl Sec) const {
1082   const Elf_Shdr *EShdr = getSection(Sec);
1083   uintX_t Type = EShdr->sh_type;
1084   if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA && Type != ELF::SHT_CREL)
1085     return section_end();
1086 
1087   Expected<const Elf_Shdr *> SecOrErr = EF.getSection(EShdr->sh_info);
1088   if (!SecOrErr)
1089     return SecOrErr.takeError();
1090   return section_iterator(SectionRef(toDRI(*SecOrErr), this));
1091 }
1092 
1093 // Relocations
1094 template <class ELFT>
1095 void ELFObjectFile<ELFT>::moveRelocationNext(DataRefImpl &Rel) const {
1096   ++Rel.d.b;
1097 }
1098 
1099 template <class ELFT>
1100 symbol_iterator
1101 ELFObjectFile<ELFT>::getRelocationSymbol(DataRefImpl Rel) const {
1102   uint32_t symbolIdx;
1103   const Elf_Shdr *sec = getRelSection(Rel);
1104   if (sec->sh_type == ELF::SHT_CREL)
1105     symbolIdx = getCrel(Rel).r_symidx;
1106   else if (sec->sh_type == ELF::SHT_REL)
1107     symbolIdx = getRel(Rel)->getSymbol(EF.isMips64EL());
1108   else
1109     symbolIdx = getRela(Rel)->getSymbol(EF.isMips64EL());
1110   if (!symbolIdx)
1111     return symbol_end();
1112 
1113   // FIXME: error check symbolIdx
1114   DataRefImpl SymbolData;
1115   SymbolData.d.a = sec->sh_link;
1116   SymbolData.d.b = symbolIdx;
1117   return symbol_iterator(SymbolRef(SymbolData, this));
1118 }
1119 
1120 template <class ELFT>
1121 uint64_t ELFObjectFile<ELFT>::getRelocationOffset(DataRefImpl Rel) const {
1122   const Elf_Shdr *sec = getRelSection(Rel);
1123   if (sec->sh_type == ELF::SHT_CREL)
1124     return getCrel(Rel).r_offset;
1125   if (sec->sh_type == ELF::SHT_REL)
1126     return getRel(Rel)->r_offset;
1127 
1128   return getRela(Rel)->r_offset;
1129 }
1130 
1131 template <class ELFT>
1132 uint64_t ELFObjectFile<ELFT>::getRelocationType(DataRefImpl Rel) const {
1133   const Elf_Shdr *sec = getRelSection(Rel);
1134   if (sec->sh_type == ELF::SHT_CREL)
1135     return getCrel(Rel).r_type;
1136   if (sec->sh_type == ELF::SHT_REL)
1137     return getRel(Rel)->getType(EF.isMips64EL());
1138   else
1139     return getRela(Rel)->getType(EF.isMips64EL());
1140 }
1141 
1142 template <class ELFT>
1143 StringRef ELFObjectFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
1144   return getELFRelocationTypeName(EF.getHeader().e_machine, Type);
1145 }
1146 
1147 template <class ELFT>
1148 void ELFObjectFile<ELFT>::getRelocationTypeName(
1149     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1150   uint32_t type = getRelocationType(Rel);
1151   EF.getRelocationTypeName(type, Result);
1152 }
1153 
1154 template <class ELFT>
1155 Expected<int64_t>
1156 ELFObjectFile<ELFT>::getRelocationAddend(DataRefImpl Rel) const {
1157   if (getRelSection(Rel)->sh_type == ELF::SHT_RELA)
1158     return (int64_t)getRela(Rel)->r_addend;
1159   if (getRelSection(Rel)->sh_type == ELF::SHT_CREL)
1160     return (int64_t)getCrel(Rel).r_addend;
1161   return createError("Relocation section does not have addends");
1162 }
1163 
1164 template <class ELFT>
1165 const typename ELFObjectFile<ELFT>::Elf_Rel *
1166 ELFObjectFile<ELFT>::getRel(DataRefImpl Rel) const {
1167   assert(getRelSection(Rel)->sh_type == ELF::SHT_REL);
1168   auto Ret = EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
1169   if (!Ret)
1170     report_fatal_error(Twine(errorToErrorCode(Ret.takeError()).message()));
1171   return *Ret;
1172 }
1173 
1174 template <class ELFT>
1175 const typename ELFObjectFile<ELFT>::Elf_Rela *
1176 ELFObjectFile<ELFT>::getRela(DataRefImpl Rela) const {
1177   assert(getRelSection(Rela)->sh_type == ELF::SHT_RELA);
1178   auto Ret = EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
1179   if (!Ret)
1180     report_fatal_error(Twine(errorToErrorCode(Ret.takeError()).message()));
1181   return *Ret;
1182 }
1183 
1184 template <class ELFT>
1185 typename ELFObjectFile<ELFT>::Elf_Crel
1186 ELFObjectFile<ELFT>::getCrel(DataRefImpl Crel) const {
1187   assert(getRelSection(Crel)->sh_type == ELF::SHT_CREL);
1188   assert(Crel.d.a < Crels.size());
1189   return Crels[Crel.d.a][Crel.d.b];
1190 }
1191 
1192 template <class ELFT>
1193 Expected<ELFObjectFile<ELFT>>
1194 ELFObjectFile<ELFT>::create(MemoryBufferRef Object, bool InitContent) {
1195   auto EFOrErr = ELFFile<ELFT>::create(Object.getBuffer());
1196   if (Error E = EFOrErr.takeError())
1197     return std::move(E);
1198 
1199   ELFObjectFile<ELFT> Obj = {Object, std::move(*EFOrErr), nullptr, nullptr,
1200                              nullptr};
1201   if (InitContent)
1202     if (Error E = Obj.initContent())
1203       return std::move(E);
1204   return std::move(Obj);
1205 }
1206 
1207 template <class ELFT>
1208 ELFObjectFile<ELFT>::ELFObjectFile(MemoryBufferRef Object, ELFFile<ELFT> EF,
1209                                    const Elf_Shdr *DotDynSymSec,
1210                                    const Elf_Shdr *DotSymtabSec,
1211                                    const Elf_Shdr *DotSymtabShndx)
1212     : ELFObjectFileBase(getELFType(ELFT::Endianness == llvm::endianness::little,
1213                                    ELFT::Is64Bits),
1214                         Object),
1215       EF(EF), DotDynSymSec(DotDynSymSec), DotSymtabSec(DotSymtabSec),
1216       DotSymtabShndxSec(DotSymtabShndx) {}
1217 
1218 template <class ELFT>
1219 ELFObjectFile<ELFT>::ELFObjectFile(ELFObjectFile<ELFT> &&Other)
1220     : ELFObjectFile(Other.Data, Other.EF, Other.DotDynSymSec,
1221                     Other.DotSymtabSec, Other.DotSymtabShndxSec) {}
1222 
1223 template <class ELFT>
1224 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_begin() const {
1225   DataRefImpl Sym =
1226       toDRI(DotSymtabSec,
1227             DotSymtabSec && DotSymtabSec->sh_size >= sizeof(Elf_Sym) ? 1 : 0);
1228   return basic_symbol_iterator(SymbolRef(Sym, this));
1229 }
1230 
1231 template <class ELFT>
1232 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_end() const {
1233   const Elf_Shdr *SymTab = DotSymtabSec;
1234   if (!SymTab)
1235     return symbol_begin();
1236   DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
1237   return basic_symbol_iterator(SymbolRef(Sym, this));
1238 }
1239 
1240 template <class ELFT>
1241 elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_begin() const {
1242   if (!DotDynSymSec || DotDynSymSec->sh_size < sizeof(Elf_Sym))
1243     // Ignore errors here where the dynsym is empty or sh_size less than the
1244     // size of one symbol. These should be handled elsewhere.
1245     return symbol_iterator(SymbolRef(toDRI(DotDynSymSec, 0), this));
1246   // Skip 0-index NULL symbol.
1247   return symbol_iterator(SymbolRef(toDRI(DotDynSymSec, 1), this));
1248 }
1249 
1250 template <class ELFT>
1251 elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_end() const {
1252   const Elf_Shdr *SymTab = DotDynSymSec;
1253   if (!SymTab)
1254     return dynamic_symbol_begin();
1255   DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
1256   return basic_symbol_iterator(SymbolRef(Sym, this));
1257 }
1258 
1259 template <class ELFT>
1260 section_iterator ELFObjectFile<ELFT>::section_begin() const {
1261   auto SectionsOrErr = EF.sections();
1262   if (!SectionsOrErr)
1263     return section_iterator(SectionRef());
1264   return section_iterator(SectionRef(toDRI((*SectionsOrErr).begin()), this));
1265 }
1266 
1267 template <class ELFT>
1268 section_iterator ELFObjectFile<ELFT>::section_end() const {
1269   auto SectionsOrErr = EF.sections();
1270   if (!SectionsOrErr)
1271     return section_iterator(SectionRef());
1272   return section_iterator(SectionRef(toDRI((*SectionsOrErr).end()), this));
1273 }
1274 
1275 template <class ELFT>
1276 uint8_t ELFObjectFile<ELFT>::getBytesInAddress() const {
1277   return ELFT::Is64Bits ? 8 : 4;
1278 }
1279 
1280 template <class ELFT>
1281 StringRef ELFObjectFile<ELFT>::getFileFormatName() const {
1282   constexpr bool IsLittleEndian = ELFT::Endianness == llvm::endianness::little;
1283   switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1284   case ELF::ELFCLASS32:
1285     switch (EF.getHeader().e_machine) {
1286     case ELF::EM_68K:
1287       return "elf32-m68k";
1288     case ELF::EM_386:
1289       return "elf32-i386";
1290     case ELF::EM_IAMCU:
1291       return "elf32-iamcu";
1292     case ELF::EM_X86_64:
1293       return "elf32-x86-64";
1294     case ELF::EM_ARM:
1295       return (IsLittleEndian ? "elf32-littlearm" : "elf32-bigarm");
1296     case ELF::EM_AVR:
1297       return "elf32-avr";
1298     case ELF::EM_HEXAGON:
1299       return "elf32-hexagon";
1300     case ELF::EM_LANAI:
1301       return "elf32-lanai";
1302     case ELF::EM_MIPS:
1303       return "elf32-mips";
1304     case ELF::EM_MSP430:
1305       return "elf32-msp430";
1306     case ELF::EM_PPC:
1307       return (IsLittleEndian ? "elf32-powerpcle" : "elf32-powerpc");
1308     case ELF::EM_RISCV:
1309       return "elf32-littleriscv";
1310     case ELF::EM_CSKY:
1311       return "elf32-csky";
1312     case ELF::EM_SPARC:
1313     case ELF::EM_SPARC32PLUS:
1314       return "elf32-sparc";
1315     case ELF::EM_AMDGPU:
1316       return "elf32-amdgpu";
1317     case ELF::EM_LOONGARCH:
1318       return "elf32-loongarch";
1319     case ELF::EM_XTENSA:
1320       return "elf32-xtensa";
1321     default:
1322       return "elf32-unknown";
1323     }
1324   case ELF::ELFCLASS64:
1325     switch (EF.getHeader().e_machine) {
1326     case ELF::EM_386:
1327       return "elf64-i386";
1328     case ELF::EM_X86_64:
1329       return "elf64-x86-64";
1330     case ELF::EM_AARCH64:
1331       return (IsLittleEndian ? "elf64-littleaarch64" : "elf64-bigaarch64");
1332     case ELF::EM_PPC64:
1333       return (IsLittleEndian ? "elf64-powerpcle" : "elf64-powerpc");
1334     case ELF::EM_RISCV:
1335       return "elf64-littleriscv";
1336     case ELF::EM_S390:
1337       return "elf64-s390";
1338     case ELF::EM_SPARCV9:
1339       return "elf64-sparc";
1340     case ELF::EM_MIPS:
1341       return "elf64-mips";
1342     case ELF::EM_AMDGPU:
1343       return "elf64-amdgpu";
1344     case ELF::EM_BPF:
1345       return "elf64-bpf";
1346     case ELF::EM_VE:
1347       return "elf64-ve";
1348     case ELF::EM_LOONGARCH:
1349       return "elf64-loongarch";
1350     default:
1351       return "elf64-unknown";
1352     }
1353   default:
1354     // FIXME: Proper error handling.
1355     report_fatal_error("Invalid ELFCLASS!");
1356   }
1357 }
1358 
1359 template <class ELFT> Triple::ArchType ELFObjectFile<ELFT>::getArch() const {
1360   bool IsLittleEndian = ELFT::Endianness == llvm::endianness::little;
1361   switch (EF.getHeader().e_machine) {
1362   case ELF::EM_68K:
1363     return Triple::m68k;
1364   case ELF::EM_386:
1365   case ELF::EM_IAMCU:
1366     return Triple::x86;
1367   case ELF::EM_X86_64:
1368     return Triple::x86_64;
1369   case ELF::EM_AARCH64:
1370     return IsLittleEndian ? Triple::aarch64 : Triple::aarch64_be;
1371   case ELF::EM_ARM:
1372     return Triple::arm;
1373   case ELF::EM_AVR:
1374     return Triple::avr;
1375   case ELF::EM_HEXAGON:
1376     return Triple::hexagon;
1377   case ELF::EM_LANAI:
1378     return Triple::lanai;
1379   case ELF::EM_MIPS:
1380     switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1381     case ELF::ELFCLASS32:
1382       return IsLittleEndian ? Triple::mipsel : Triple::mips;
1383     case ELF::ELFCLASS64:
1384       return IsLittleEndian ? Triple::mips64el : Triple::mips64;
1385     default:
1386       report_fatal_error("Invalid ELFCLASS!");
1387     }
1388   case ELF::EM_MSP430:
1389     return Triple::msp430;
1390   case ELF::EM_PPC:
1391     return IsLittleEndian ? Triple::ppcle : Triple::ppc;
1392   case ELF::EM_PPC64:
1393     return IsLittleEndian ? Triple::ppc64le : Triple::ppc64;
1394   case ELF::EM_RISCV:
1395     switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1396     case ELF::ELFCLASS32:
1397       return Triple::riscv32;
1398     case ELF::ELFCLASS64:
1399       return Triple::riscv64;
1400     default:
1401       report_fatal_error("Invalid ELFCLASS!");
1402     }
1403   case ELF::EM_S390:
1404     return Triple::systemz;
1405 
1406   case ELF::EM_SPARC:
1407   case ELF::EM_SPARC32PLUS:
1408     return IsLittleEndian ? Triple::sparcel : Triple::sparc;
1409   case ELF::EM_SPARCV9:
1410     return Triple::sparcv9;
1411 
1412   case ELF::EM_AMDGPU: {
1413     if (!IsLittleEndian)
1414       return Triple::UnknownArch;
1415 
1416     unsigned MACH = EF.getHeader().e_flags & ELF::EF_AMDGPU_MACH;
1417     if (MACH >= ELF::EF_AMDGPU_MACH_R600_FIRST &&
1418         MACH <= ELF::EF_AMDGPU_MACH_R600_LAST)
1419       return Triple::r600;
1420     if (MACH >= ELF::EF_AMDGPU_MACH_AMDGCN_FIRST &&
1421         MACH <= ELF::EF_AMDGPU_MACH_AMDGCN_LAST)
1422       return Triple::amdgcn;
1423 
1424     return Triple::UnknownArch;
1425   }
1426 
1427   case ELF::EM_CUDA: {
1428     if (EF.getHeader().e_ident[ELF::EI_CLASS] == ELF::ELFCLASS32)
1429       return Triple::nvptx;
1430     return Triple::nvptx64;
1431   }
1432 
1433   case ELF::EM_BPF:
1434     return IsLittleEndian ? Triple::bpfel : Triple::bpfeb;
1435 
1436   case ELF::EM_VE:
1437     return Triple::ve;
1438   case ELF::EM_CSKY:
1439     return Triple::csky;
1440 
1441   case ELF::EM_LOONGARCH:
1442     switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1443     case ELF::ELFCLASS32:
1444       return Triple::loongarch32;
1445     case ELF::ELFCLASS64:
1446       return Triple::loongarch64;
1447     default:
1448       report_fatal_error("Invalid ELFCLASS!");
1449     }
1450 
1451   case ELF::EM_XTENSA:
1452     return Triple::xtensa;
1453 
1454   default:
1455     return Triple::UnknownArch;
1456   }
1457 }
1458 
1459 template <class ELFT> Triple::OSType ELFObjectFile<ELFT>::getOS() const {
1460   switch (EF.getHeader().e_ident[ELF::EI_OSABI]) {
1461   case ELF::ELFOSABI_NETBSD:
1462     return Triple::NetBSD;
1463   case ELF::ELFOSABI_LINUX:
1464     return Triple::Linux;
1465   case ELF::ELFOSABI_HURD:
1466     return Triple::Hurd;
1467   case ELF::ELFOSABI_SOLARIS:
1468     return Triple::Solaris;
1469   case ELF::ELFOSABI_AIX:
1470     return Triple::AIX;
1471   case ELF::ELFOSABI_FREEBSD:
1472     return Triple::FreeBSD;
1473   case ELF::ELFOSABI_OPENBSD:
1474     return Triple::OpenBSD;
1475   case ELF::ELFOSABI_CUDA:
1476     return Triple::CUDA;
1477   case ELF::ELFOSABI_AMDGPU_HSA:
1478     return Triple::AMDHSA;
1479   case ELF::ELFOSABI_AMDGPU_PAL:
1480     return Triple::AMDPAL;
1481   case ELF::ELFOSABI_AMDGPU_MESA3D:
1482     return Triple::Mesa3D;
1483   default:
1484     return Triple::UnknownOS;
1485   }
1486 }
1487 
1488 template <class ELFT>
1489 Expected<uint64_t> ELFObjectFile<ELFT>::getStartAddress() const {
1490   return EF.getHeader().e_entry;
1491 }
1492 
1493 template <class ELFT>
1494 ELFObjectFileBase::elf_symbol_iterator_range
1495 ELFObjectFile<ELFT>::getDynamicSymbolIterators() const {
1496   return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
1497 }
1498 
1499 template <class ELFT> bool ELFObjectFile<ELFT>::isRelocatableObject() const {
1500   return EF.getHeader().e_type == ELF::ET_REL;
1501 }
1502 
1503 template <class ELFT>
1504 StringRef ELFObjectFile<ELFT>::getCrelDecodeProblem(DataRefImpl Sec) const {
1505   uintptr_t SHT = reinterpret_cast<uintptr_t>(cantFail(EF.sections()).begin());
1506   auto I = (Sec.p - SHT) / EF.getHeader().e_shentsize;
1507   if (I < CrelDecodeProblems.size())
1508     return CrelDecodeProblems[I];
1509   return "";
1510 }
1511 
1512 } // end namespace object
1513 } // end namespace llvm
1514 
1515 #endif // LLVM_OBJECT_ELFOBJECTFILE_H