1 //===- ELFObjectFile.h - ELF object file implementation ---------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the ELFObjectFile template class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_OBJECT_ELFOBJECTFILE_H
14 #define LLVM_OBJECT_ELFOBJECTFILE_H
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/Object/Binary.h"
22 #include "llvm/Object/ELF.h"
23 #include "llvm/Object/ELFTypes.h"
24 #include "llvm/Object/Error.h"
25 #include "llvm/Object/ObjectFile.h"
26 #include "llvm/Object/SymbolicFile.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/ELFAttributeParser.h"
29 #include "llvm/Support/ELFAttributes.h"
30 #include "llvm/Support/Error.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MemoryBufferRef.h"
33 #include "llvm/Support/ScopedPrinter.h"
34 #include "llvm/TargetParser/SubtargetFeature.h"
35 #include "llvm/TargetParser/Triple.h"
36 #include <cassert>
37 #include <cstdint>
38 
39 namespace llvm {
40 
41 template <typename T> class SmallVectorImpl;
42 
43 namespace object {
44 
45 constexpr int NumElfSymbolTypes = 16;
46 extern const llvm::EnumEntry<unsigned> ElfSymbolTypes[NumElfSymbolTypes];
47 
48 class elf_symbol_iterator;
49 
50 struct ELFPltEntry {
51   StringRef Section;
52   std::optional<DataRefImpl> Symbol;
53   uint64_t Address;
54 };
55 
56 class ELFObjectFileBase : public ObjectFile {
57   friend class ELFRelocationRef;
58   friend class ELFSectionRef;
59   friend class ELFSymbolRef;
60 
61   SubtargetFeatures getMIPSFeatures() const;
62   SubtargetFeatures getARMFeatures() const;
63   SubtargetFeatures getHexagonFeatures() const;
64   Expected<SubtargetFeatures> getRISCVFeatures() const;
65   SubtargetFeatures getLoongArchFeatures() const;
66 
67   StringRef getAMDGPUCPUName() const;
68   StringRef getNVPTXCPUName() const;
69 
70 protected:
71   ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source);
72 
73   virtual uint64_t getSymbolSize(DataRefImpl Symb) const = 0;
74   virtual uint8_t getSymbolBinding(DataRefImpl Symb) const = 0;
75   virtual uint8_t getSymbolOther(DataRefImpl Symb) const = 0;
76   virtual uint8_t getSymbolELFType(DataRefImpl Symb) const = 0;
77 
78   virtual uint32_t getSectionType(DataRefImpl Sec) const = 0;
79   virtual uint64_t getSectionFlags(DataRefImpl Sec) const = 0;
80   virtual uint64_t getSectionOffset(DataRefImpl Sec) const = 0;
81 
82   virtual Expected<int64_t> getRelocationAddend(DataRefImpl Rel) const = 0;
83   virtual Error getBuildAttributes(ELFAttributeParser &Attributes) const = 0;
84 
85 public:
86   using elf_symbol_iterator_range = iterator_range<elf_symbol_iterator>;
87 
88   virtual elf_symbol_iterator_range getDynamicSymbolIterators() const = 0;
89 
90   /// Returns platform-specific object flags, if any.
91   virtual unsigned getPlatformFlags() const = 0;
92 
93   elf_symbol_iterator_range symbols() const;
94 
classof(const Binary * v)95   static bool classof(const Binary *v) { return v->isELF(); }
96 
97   Expected<SubtargetFeatures> getFeatures() const override;
98 
99   std::optional<StringRef> tryGetCPUName() const override;
100 
101   void setARMSubArch(Triple &TheTriple) const override;
102 
103   virtual uint16_t getEType() const = 0;
104 
105   virtual uint16_t getEMachine() const = 0;
106 
107   virtual uint8_t getEIdentABIVersion() const = 0;
108 
109   std::vector<ELFPltEntry> getPltEntries() const;
110 
111   /// Returns a vector containing a symbol version for each dynamic symbol.
112   /// Returns an empty vector if version sections do not exist.
113   Expected<std::vector<VersionEntry>> readDynsymVersions() const;
114 
115   /// Returns a vector of all BB address maps in the object file. When
116   /// `TextSectionIndex` is specified, only returns the BB address maps
117   /// corresponding to the section with that index. When `PGOAnalyses`is
118   /// specified (PGOAnalyses is not nullptr), the vector is cleared then filled
119   /// with extra PGO data. `PGOAnalyses` will always be the same length as the
120   /// return value when it is requested assuming no error occurs. Upon failure,
121   /// `PGOAnalyses` will be emptied.
122   Expected<std::vector<BBAddrMap>>
123   readBBAddrMap(std::optional<unsigned> TextSectionIndex = std::nullopt,
124                 std::vector<PGOAnalysisMap> *PGOAnalyses = nullptr) const;
125 };
126 
127 class ELFSectionRef : public SectionRef {
128 public:
ELFSectionRef(const SectionRef & B)129   ELFSectionRef(const SectionRef &B) : SectionRef(B) {
130     assert(isa<ELFObjectFileBase>(SectionRef::getObject()));
131   }
132 
getObject()133   const ELFObjectFileBase *getObject() const {
134     return cast<ELFObjectFileBase>(SectionRef::getObject());
135   }
136 
getType()137   uint32_t getType() const {
138     return getObject()->getSectionType(getRawDataRefImpl());
139   }
140 
getFlags()141   uint64_t getFlags() const {
142     return getObject()->getSectionFlags(getRawDataRefImpl());
143   }
144 
getOffset()145   uint64_t getOffset() const {
146     return getObject()->getSectionOffset(getRawDataRefImpl());
147   }
148 };
149 
150 class elf_section_iterator : public section_iterator {
151 public:
elf_section_iterator(const section_iterator & B)152   elf_section_iterator(const section_iterator &B) : section_iterator(B) {
153     assert(isa<ELFObjectFileBase>(B->getObject()));
154   }
155 
156   const ELFSectionRef *operator->() const {
157     return static_cast<const ELFSectionRef *>(section_iterator::operator->());
158   }
159 
160   const ELFSectionRef &operator*() const {
161     return static_cast<const ELFSectionRef &>(section_iterator::operator*());
162   }
163 };
164 
165 class ELFSymbolRef : public SymbolRef {
166 public:
ELFSymbolRef(const SymbolRef & B)167   ELFSymbolRef(const SymbolRef &B) : SymbolRef(B) {
168     assert(isa<ELFObjectFileBase>(SymbolRef::getObject()));
169   }
170 
getObject()171   const ELFObjectFileBase *getObject() const {
172     return cast<ELFObjectFileBase>(BasicSymbolRef::getObject());
173   }
174 
getSize()175   uint64_t getSize() const {
176     return getObject()->getSymbolSize(getRawDataRefImpl());
177   }
178 
getBinding()179   uint8_t getBinding() const {
180     return getObject()->getSymbolBinding(getRawDataRefImpl());
181   }
182 
getOther()183   uint8_t getOther() const {
184     return getObject()->getSymbolOther(getRawDataRefImpl());
185   }
186 
getELFType()187   uint8_t getELFType() const {
188     return getObject()->getSymbolELFType(getRawDataRefImpl());
189   }
190 
getELFTypeName()191   StringRef getELFTypeName() const {
192     uint8_t Type = getELFType();
193     for (const auto &EE : ElfSymbolTypes) {
194       if (EE.Value == Type) {
195         return EE.AltName;
196       }
197     }
198     return "";
199   }
200 };
201 
202 inline bool operator<(const ELFSymbolRef &A, const ELFSymbolRef &B) {
203   const DataRefImpl &DRIA = A.getRawDataRefImpl();
204   const DataRefImpl &DRIB = B.getRawDataRefImpl();
205   if (DRIA.d.a == DRIB.d.a)
206     return DRIA.d.b < DRIB.d.b;
207   return DRIA.d.a < DRIB.d.a;
208 }
209 
210 class elf_symbol_iterator : public symbol_iterator {
211 public:
elf_symbol_iterator(const basic_symbol_iterator & B)212   elf_symbol_iterator(const basic_symbol_iterator &B)
213       : symbol_iterator(SymbolRef(B->getRawDataRefImpl(),
214                                   cast<ELFObjectFileBase>(B->getObject()))) {}
215 
216   const ELFSymbolRef *operator->() const {
217     return static_cast<const ELFSymbolRef *>(symbol_iterator::operator->());
218   }
219 
220   const ELFSymbolRef &operator*() const {
221     return static_cast<const ELFSymbolRef &>(symbol_iterator::operator*());
222   }
223 };
224 
225 class ELFRelocationRef : public RelocationRef {
226 public:
ELFRelocationRef(const RelocationRef & B)227   ELFRelocationRef(const RelocationRef &B) : RelocationRef(B) {
228     assert(isa<ELFObjectFileBase>(RelocationRef::getObject()));
229   }
230 
getObject()231   const ELFObjectFileBase *getObject() const {
232     return cast<ELFObjectFileBase>(RelocationRef::getObject());
233   }
234 
getAddend()235   Expected<int64_t> getAddend() const {
236     return getObject()->getRelocationAddend(getRawDataRefImpl());
237   }
238 };
239 
240 class elf_relocation_iterator : public relocation_iterator {
241 public:
elf_relocation_iterator(const relocation_iterator & B)242   elf_relocation_iterator(const relocation_iterator &B)
243       : relocation_iterator(RelocationRef(
244             B->getRawDataRefImpl(), cast<ELFObjectFileBase>(B->getObject()))) {}
245 
246   const ELFRelocationRef *operator->() const {
247     return static_cast<const ELFRelocationRef *>(
248         relocation_iterator::operator->());
249   }
250 
251   const ELFRelocationRef &operator*() const {
252     return static_cast<const ELFRelocationRef &>(
253         relocation_iterator::operator*());
254   }
255 };
256 
257 inline ELFObjectFileBase::elf_symbol_iterator_range
symbols()258 ELFObjectFileBase::symbols() const {
259   return elf_symbol_iterator_range(symbol_begin(), symbol_end());
260 }
261 
262 template <class ELFT> class ELFObjectFile : public ELFObjectFileBase {
263   uint16_t getEMachine() const override;
264   uint16_t getEType() const override;
265   uint8_t getEIdentABIVersion() const override;
266   uint64_t getSymbolSize(DataRefImpl Sym) const override;
267 
268 public:
LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)269   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
270 
271   SectionRef toSectionRef(const Elf_Shdr *Sec) const {
272     return SectionRef(toDRI(Sec), this);
273   }
274 
toSymbolRef(const Elf_Shdr * SymTable,unsigned SymbolNum)275   ELFSymbolRef toSymbolRef(const Elf_Shdr *SymTable, unsigned SymbolNum) const {
276     return ELFSymbolRef({toDRI(SymTable, SymbolNum), this});
277   }
278 
IsContentValid()279   bool IsContentValid() const { return ContentValid; }
280 
281 private:
282   ELFObjectFile(MemoryBufferRef Object, ELFFile<ELFT> EF,
283                 const Elf_Shdr *DotDynSymSec, const Elf_Shdr *DotSymtabSec,
284                 const Elf_Shdr *DotSymtabShndxSec);
285 
286   bool ContentValid = false;
287 
288 protected:
289   ELFFile<ELFT> EF;
290 
291   const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
292   const Elf_Shdr *DotSymtabSec = nullptr; // Symbol table section.
293   const Elf_Shdr *DotSymtabShndxSec = nullptr; // SHT_SYMTAB_SHNDX section.
294 
295   Error initContent() override;
296 
297   void moveSymbolNext(DataRefImpl &Symb) const override;
298   Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
299   Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
300   uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
301   uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
302   uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
303   Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
304   uint8_t getSymbolBinding(DataRefImpl Symb) const override;
305   uint8_t getSymbolOther(DataRefImpl Symb) const override;
306   uint8_t getSymbolELFType(DataRefImpl Symb) const override;
307   Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
308   Expected<section_iterator> getSymbolSection(const Elf_Sym *Symb,
309                                               const Elf_Shdr *SymTab) const;
310   Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
311 
312   void moveSectionNext(DataRefImpl &Sec) const override;
313   Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
314   uint64_t getSectionAddress(DataRefImpl Sec) const override;
315   uint64_t getSectionIndex(DataRefImpl Sec) const override;
316   uint64_t getSectionSize(DataRefImpl Sec) const override;
317   Expected<ArrayRef<uint8_t>>
318   getSectionContents(DataRefImpl Sec) const override;
319   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
320   bool isSectionCompressed(DataRefImpl Sec) const override;
321   bool isSectionText(DataRefImpl Sec) const override;
322   bool isSectionData(DataRefImpl Sec) const override;
323   bool isSectionBSS(DataRefImpl Sec) const override;
324   bool isSectionVirtual(DataRefImpl Sec) const override;
325   bool isBerkeleyText(DataRefImpl Sec) const override;
326   bool isBerkeleyData(DataRefImpl Sec) const override;
327   bool isDebugSection(DataRefImpl Sec) const override;
328   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
329   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
330   std::vector<SectionRef> dynamic_relocation_sections() const override;
331   Expected<section_iterator>
332   getRelocatedSection(DataRefImpl Sec) const override;
333 
334   void moveRelocationNext(DataRefImpl &Rel) const override;
335   uint64_t getRelocationOffset(DataRefImpl Rel) const override;
336   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
337   uint64_t getRelocationType(DataRefImpl Rel) const override;
338   void getRelocationTypeName(DataRefImpl Rel,
339                              SmallVectorImpl<char> &Result) const override;
340 
341   uint32_t getSectionType(DataRefImpl Sec) const override;
342   uint64_t getSectionFlags(DataRefImpl Sec) const override;
343   uint64_t getSectionOffset(DataRefImpl Sec) const override;
344   StringRef getRelocationTypeName(uint32_t Type) const;
345 
toDRI(const Elf_Shdr * SymTable,unsigned SymbolNum)346   DataRefImpl toDRI(const Elf_Shdr *SymTable, unsigned SymbolNum) const {
347     DataRefImpl DRI;
348     if (!SymTable) {
349       DRI.d.a = 0;
350       DRI.d.b = 0;
351       return DRI;
352     }
353     assert(SymTable->sh_type == ELF::SHT_SYMTAB ||
354            SymTable->sh_type == ELF::SHT_DYNSYM);
355 
356     auto SectionsOrErr = EF.sections();
357     if (!SectionsOrErr) {
358       DRI.d.a = 0;
359       DRI.d.b = 0;
360       return DRI;
361     }
362     uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
363     unsigned SymTableIndex =
364         (reinterpret_cast<uintptr_t>(SymTable) - SHT) / sizeof(Elf_Shdr);
365 
366     DRI.d.a = SymTableIndex;
367     DRI.d.b = SymbolNum;
368     return DRI;
369   }
370 
toELFShdrIter(DataRefImpl Sec)371   const Elf_Shdr *toELFShdrIter(DataRefImpl Sec) const {
372     return reinterpret_cast<const Elf_Shdr *>(Sec.p);
373   }
374 
toDRI(const Elf_Shdr * Sec)375   DataRefImpl toDRI(const Elf_Shdr *Sec) const {
376     DataRefImpl DRI;
377     DRI.p = reinterpret_cast<uintptr_t>(Sec);
378     return DRI;
379   }
380 
toDRI(const Elf_Dyn * Dyn)381   DataRefImpl toDRI(const Elf_Dyn *Dyn) const {
382     DataRefImpl DRI;
383     DRI.p = reinterpret_cast<uintptr_t>(Dyn);
384     return DRI;
385   }
386 
isExportedToOtherDSO(const Elf_Sym * ESym)387   bool isExportedToOtherDSO(const Elf_Sym *ESym) const {
388     unsigned char Binding = ESym->getBinding();
389     unsigned char Visibility = ESym->getVisibility();
390 
391     // A symbol is exported if its binding is either GLOBAL or WEAK, and its
392     // visibility is either DEFAULT or PROTECTED. All other symbols are not
393     // exported.
394     return (
395         (Binding == ELF::STB_GLOBAL || Binding == ELF::STB_WEAK ||
396          Binding == ELF::STB_GNU_UNIQUE) &&
397         (Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_PROTECTED));
398   }
399 
getBuildAttributes(ELFAttributeParser & Attributes)400   Error getBuildAttributes(ELFAttributeParser &Attributes) const override {
401     uint32_t Type;
402     switch (getEMachine()) {
403     case ELF::EM_ARM:
404       Type = ELF::SHT_ARM_ATTRIBUTES;
405       break;
406     case ELF::EM_RISCV:
407       Type = ELF::SHT_RISCV_ATTRIBUTES;
408       break;
409     case ELF::EM_HEXAGON:
410       Type = ELF::SHT_HEXAGON_ATTRIBUTES;
411       break;
412     default:
413       return Error::success();
414     }
415 
416     auto SectionsOrErr = EF.sections();
417     if (!SectionsOrErr)
418       return SectionsOrErr.takeError();
419     for (const Elf_Shdr &Sec : *SectionsOrErr) {
420       if (Sec.sh_type != Type)
421         continue;
422       auto ErrorOrContents = EF.getSectionContents(Sec);
423       if (!ErrorOrContents)
424         return ErrorOrContents.takeError();
425 
426       auto Contents = ErrorOrContents.get();
427       if (Contents[0] != ELFAttrs::Format_Version || Contents.size() == 1)
428         return Error::success();
429 
430       if (Error E = Attributes.parse(Contents, ELFT::Endianness))
431         return E;
432       break;
433     }
434     return Error::success();
435   }
436 
437   // This flag is used for classof, to distinguish ELFObjectFile from
438   // its subclass. If more subclasses will be created, this flag will
439   // have to become an enum.
440   bool isDyldELFObject = false;
441 
442 public:
443   ELFObjectFile(ELFObjectFile<ELFT> &&Other);
444   static Expected<ELFObjectFile<ELFT>> create(MemoryBufferRef Object,
445                                               bool InitContent = true);
446 
447   const Elf_Rel *getRel(DataRefImpl Rel) const;
448   const Elf_Rela *getRela(DataRefImpl Rela) const;
449 
getSymbol(DataRefImpl Sym)450   Expected<const Elf_Sym *> getSymbol(DataRefImpl Sym) const {
451     return EF.template getEntry<Elf_Sym>(Sym.d.a, Sym.d.b);
452   }
453 
454   /// Get the relocation section that contains \a Rel.
getRelSection(DataRefImpl Rel)455   const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
456     auto RelSecOrErr = EF.getSection(Rel.d.a);
457     if (!RelSecOrErr)
458       report_fatal_error(
459           Twine(errorToErrorCode(RelSecOrErr.takeError()).message()));
460     return *RelSecOrErr;
461   }
462 
getSection(DataRefImpl Sec)463   const Elf_Shdr *getSection(DataRefImpl Sec) const {
464     return reinterpret_cast<const Elf_Shdr *>(Sec.p);
465   }
466 
467   basic_symbol_iterator symbol_begin() const override;
468   basic_symbol_iterator symbol_end() const override;
469 
is64Bit()470   bool is64Bit() const override { return getBytesInAddress() == 8; }
471 
472   elf_symbol_iterator dynamic_symbol_begin() const;
473   elf_symbol_iterator dynamic_symbol_end() const;
474 
475   section_iterator section_begin() const override;
476   section_iterator section_end() const override;
477 
478   Expected<int64_t> getRelocationAddend(DataRefImpl Rel) const override;
479 
480   uint8_t getBytesInAddress() const override;
481   StringRef getFileFormatName() const override;
482   Triple::ArchType getArch() const override;
483   Triple::OSType getOS() const override;
484   Expected<uint64_t> getStartAddress() const override;
485 
getPlatformFlags()486   unsigned getPlatformFlags() const override { return EF.getHeader().e_flags; }
487 
getELFFile()488   const ELFFile<ELFT> &getELFFile() const { return EF; }
489 
isDyldType()490   bool isDyldType() const { return isDyldELFObject; }
classof(const Binary * v)491   static bool classof(const Binary *v) {
492     return v->getType() ==
493            getELFType(ELFT::Endianness == llvm::endianness::little,
494                       ELFT::Is64Bits);
495   }
496 
497   elf_symbol_iterator_range getDynamicSymbolIterators() const override;
498 
499   bool isRelocatableObject() const override;
500 
createFakeSections()501   void createFakeSections() { EF.createFakeSections(); }
502 };
503 
504 using ELF32LEObjectFile = ELFObjectFile<ELF32LE>;
505 using ELF64LEObjectFile = ELFObjectFile<ELF64LE>;
506 using ELF32BEObjectFile = ELFObjectFile<ELF32BE>;
507 using ELF64BEObjectFile = ELFObjectFile<ELF64BE>;
508 
509 template <class ELFT>
moveSymbolNext(DataRefImpl & Sym)510 void ELFObjectFile<ELFT>::moveSymbolNext(DataRefImpl &Sym) const {
511   ++Sym.d.b;
512 }
513 
initContent()514 template <class ELFT> Error ELFObjectFile<ELFT>::initContent() {
515   auto SectionsOrErr = EF.sections();
516   if (!SectionsOrErr)
517     return SectionsOrErr.takeError();
518 
519   for (const Elf_Shdr &Sec : *SectionsOrErr) {
520     switch (Sec.sh_type) {
521     case ELF::SHT_DYNSYM: {
522       if (!DotDynSymSec)
523         DotDynSymSec = &Sec;
524       break;
525     }
526     case ELF::SHT_SYMTAB: {
527       if (!DotSymtabSec)
528         DotSymtabSec = &Sec;
529       break;
530     }
531     case ELF::SHT_SYMTAB_SHNDX: {
532       if (!DotSymtabShndxSec)
533         DotSymtabShndxSec = &Sec;
534       break;
535     }
536     }
537   }
538 
539   ContentValid = true;
540   return Error::success();
541 }
542 
543 template <class ELFT>
getSymbolName(DataRefImpl Sym)544 Expected<StringRef> ELFObjectFile<ELFT>::getSymbolName(DataRefImpl Sym) const {
545   Expected<const Elf_Sym *> SymOrErr = getSymbol(Sym);
546   if (!SymOrErr)
547     return SymOrErr.takeError();
548   auto SymTabOrErr = EF.getSection(Sym.d.a);
549   if (!SymTabOrErr)
550     return SymTabOrErr.takeError();
551   const Elf_Shdr *SymTableSec = *SymTabOrErr;
552   auto StrTabOrErr = EF.getSection(SymTableSec->sh_link);
553   if (!StrTabOrErr)
554     return StrTabOrErr.takeError();
555   const Elf_Shdr *StringTableSec = *StrTabOrErr;
556   auto SymStrTabOrErr = EF.getStringTable(*StringTableSec);
557   if (!SymStrTabOrErr)
558     return SymStrTabOrErr.takeError();
559   Expected<StringRef> Name = (*SymOrErr)->getName(*SymStrTabOrErr);
560   if (Name && !Name->empty())
561     return Name;
562 
563   // If the symbol name is empty use the section name.
564   if ((*SymOrErr)->getType() == ELF::STT_SECTION) {
565     Expected<section_iterator> SecOrErr = getSymbolSection(Sym);
566     if (SecOrErr)
567       return (*SecOrErr)->getName();
568     return SecOrErr.takeError();
569   }
570   return Name;
571 }
572 
573 template <class ELFT>
getSectionFlags(DataRefImpl Sec)574 uint64_t ELFObjectFile<ELFT>::getSectionFlags(DataRefImpl Sec) const {
575   return getSection(Sec)->sh_flags;
576 }
577 
578 template <class ELFT>
getSectionType(DataRefImpl Sec)579 uint32_t ELFObjectFile<ELFT>::getSectionType(DataRefImpl Sec) const {
580   return getSection(Sec)->sh_type;
581 }
582 
583 template <class ELFT>
getSectionOffset(DataRefImpl Sec)584 uint64_t ELFObjectFile<ELFT>::getSectionOffset(DataRefImpl Sec) const {
585   return getSection(Sec)->sh_offset;
586 }
587 
588 template <class ELFT>
getSymbolValueImpl(DataRefImpl Symb)589 uint64_t ELFObjectFile<ELFT>::getSymbolValueImpl(DataRefImpl Symb) const {
590   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
591   if (!SymOrErr)
592     report_fatal_error(SymOrErr.takeError());
593 
594   uint64_t Ret = (*SymOrErr)->st_value;
595   if ((*SymOrErr)->st_shndx == ELF::SHN_ABS)
596     return Ret;
597 
598   const Elf_Ehdr &Header = EF.getHeader();
599   // Clear the ARM/Thumb or microMIPS indicator flag.
600   if ((Header.e_machine == ELF::EM_ARM || Header.e_machine == ELF::EM_MIPS) &&
601       (*SymOrErr)->getType() == ELF::STT_FUNC)
602     Ret &= ~1;
603 
604   return Ret;
605 }
606 
607 template <class ELFT>
608 Expected<uint64_t>
getSymbolAddress(DataRefImpl Symb)609 ELFObjectFile<ELFT>::getSymbolAddress(DataRefImpl Symb) const {
610   Expected<uint64_t> SymbolValueOrErr = getSymbolValue(Symb);
611   if (!SymbolValueOrErr)
612     // TODO: Test this error.
613     return SymbolValueOrErr.takeError();
614 
615   uint64_t Result = *SymbolValueOrErr;
616   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
617   if (!SymOrErr)
618     return SymOrErr.takeError();
619 
620   switch ((*SymOrErr)->st_shndx) {
621   case ELF::SHN_COMMON:
622   case ELF::SHN_UNDEF:
623   case ELF::SHN_ABS:
624     return Result;
625   }
626 
627   auto SymTabOrErr = EF.getSection(Symb.d.a);
628   if (!SymTabOrErr)
629     return SymTabOrErr.takeError();
630 
631   if (EF.getHeader().e_type == ELF::ET_REL) {
632     ArrayRef<Elf_Word> ShndxTable;
633     if (DotSymtabShndxSec) {
634       // TODO: Test this error.
635       if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
636               EF.getSHNDXTable(*DotSymtabShndxSec))
637         ShndxTable = *ShndxTableOrErr;
638       else
639         return ShndxTableOrErr.takeError();
640     }
641 
642     Expected<const Elf_Shdr *> SectionOrErr =
643         EF.getSection(**SymOrErr, *SymTabOrErr, ShndxTable);
644     if (!SectionOrErr)
645       return SectionOrErr.takeError();
646     const Elf_Shdr *Section = *SectionOrErr;
647     if (Section)
648       Result += Section->sh_addr;
649   }
650 
651   return Result;
652 }
653 
654 template <class ELFT>
getSymbolAlignment(DataRefImpl Symb)655 uint32_t ELFObjectFile<ELFT>::getSymbolAlignment(DataRefImpl Symb) const {
656   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
657   if (!SymOrErr)
658     report_fatal_error(SymOrErr.takeError());
659   if ((*SymOrErr)->st_shndx == ELF::SHN_COMMON)
660     return (*SymOrErr)->st_value;
661   return 0;
662 }
663 
664 template <class ELFT>
getEMachine()665 uint16_t ELFObjectFile<ELFT>::getEMachine() const {
666   return EF.getHeader().e_machine;
667 }
668 
getEType()669 template <class ELFT> uint16_t ELFObjectFile<ELFT>::getEType() const {
670   return EF.getHeader().e_type;
671 }
672 
getEIdentABIVersion()673 template <class ELFT> uint8_t ELFObjectFile<ELFT>::getEIdentABIVersion() const {
674   return EF.getHeader().e_ident[ELF::EI_ABIVERSION];
675 }
676 
677 template <class ELFT>
getSymbolSize(DataRefImpl Sym)678 uint64_t ELFObjectFile<ELFT>::getSymbolSize(DataRefImpl Sym) const {
679   Expected<const Elf_Sym *> SymOrErr = getSymbol(Sym);
680   if (!SymOrErr)
681     report_fatal_error(SymOrErr.takeError());
682   return (*SymOrErr)->st_size;
683 }
684 
685 template <class ELFT>
getCommonSymbolSizeImpl(DataRefImpl Symb)686 uint64_t ELFObjectFile<ELFT>::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
687   return getSymbolSize(Symb);
688 }
689 
690 template <class ELFT>
getSymbolBinding(DataRefImpl Symb)691 uint8_t ELFObjectFile<ELFT>::getSymbolBinding(DataRefImpl Symb) const {
692   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
693   if (!SymOrErr)
694     report_fatal_error(SymOrErr.takeError());
695   return (*SymOrErr)->getBinding();
696 }
697 
698 template <class ELFT>
getSymbolOther(DataRefImpl Symb)699 uint8_t ELFObjectFile<ELFT>::getSymbolOther(DataRefImpl Symb) const {
700   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
701   if (!SymOrErr)
702     report_fatal_error(SymOrErr.takeError());
703   return (*SymOrErr)->st_other;
704 }
705 
706 template <class ELFT>
getSymbolELFType(DataRefImpl Symb)707 uint8_t ELFObjectFile<ELFT>::getSymbolELFType(DataRefImpl Symb) const {
708   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
709   if (!SymOrErr)
710     report_fatal_error(SymOrErr.takeError());
711   return (*SymOrErr)->getType();
712 }
713 
714 template <class ELFT>
715 Expected<SymbolRef::Type>
getSymbolType(DataRefImpl Symb)716 ELFObjectFile<ELFT>::getSymbolType(DataRefImpl Symb) const {
717   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
718   if (!SymOrErr)
719     return SymOrErr.takeError();
720 
721   switch ((*SymOrErr)->getType()) {
722   case ELF::STT_NOTYPE:
723     return SymbolRef::ST_Unknown;
724   case ELF::STT_SECTION:
725     return SymbolRef::ST_Debug;
726   case ELF::STT_FILE:
727     return SymbolRef::ST_File;
728   case ELF::STT_FUNC:
729     return SymbolRef::ST_Function;
730   case ELF::STT_OBJECT:
731   case ELF::STT_COMMON:
732     return SymbolRef::ST_Data;
733   case ELF::STT_TLS:
734   default:
735     return SymbolRef::ST_Other;
736   }
737 }
738 
739 template <class ELFT>
getSymbolFlags(DataRefImpl Sym)740 Expected<uint32_t> ELFObjectFile<ELFT>::getSymbolFlags(DataRefImpl Sym) const {
741   Expected<const Elf_Sym *> SymOrErr = getSymbol(Sym);
742   if (!SymOrErr)
743     return SymOrErr.takeError();
744 
745   const Elf_Sym *ESym = *SymOrErr;
746   uint32_t Result = SymbolRef::SF_None;
747 
748   if (ESym->getBinding() != ELF::STB_LOCAL)
749     Result |= SymbolRef::SF_Global;
750 
751   if (ESym->getBinding() == ELF::STB_WEAK)
752     Result |= SymbolRef::SF_Weak;
753 
754   if (ESym->st_shndx == ELF::SHN_ABS)
755     Result |= SymbolRef::SF_Absolute;
756 
757   if (ESym->getType() == ELF::STT_FILE || ESym->getType() == ELF::STT_SECTION)
758     Result |= SymbolRef::SF_FormatSpecific;
759 
760   if (Expected<typename ELFT::SymRange> SymbolsOrErr =
761           EF.symbols(DotSymtabSec)) {
762     // Set the SF_FormatSpecific flag for the 0-index null symbol.
763     if (ESym == SymbolsOrErr->begin())
764       Result |= SymbolRef::SF_FormatSpecific;
765   } else
766     // TODO: Test this error.
767     return SymbolsOrErr.takeError();
768 
769   if (Expected<typename ELFT::SymRange> SymbolsOrErr =
770           EF.symbols(DotDynSymSec)) {
771     // Set the SF_FormatSpecific flag for the 0-index null symbol.
772     if (ESym == SymbolsOrErr->begin())
773       Result |= SymbolRef::SF_FormatSpecific;
774   } else
775     // TODO: Test this error.
776     return SymbolsOrErr.takeError();
777 
778   if (EF.getHeader().e_machine == ELF::EM_AARCH64) {
779     if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
780       StringRef Name = *NameOrErr;
781       if (Name.starts_with("$d") || Name.starts_with("$x"))
782         Result |= SymbolRef::SF_FormatSpecific;
783     } else {
784       // TODO: Actually report errors helpfully.
785       consumeError(NameOrErr.takeError());
786     }
787   } else if (EF.getHeader().e_machine == ELF::EM_ARM) {
788     if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
789       StringRef Name = *NameOrErr;
790       // TODO Investigate why empty name symbols need to be marked.
791       if (Name.empty() || Name.starts_with("$d") || Name.starts_with("$t") ||
792           Name.starts_with("$a"))
793         Result |= SymbolRef::SF_FormatSpecific;
794     } else {
795       // TODO: Actually report errors helpfully.
796       consumeError(NameOrErr.takeError());
797     }
798     if (ESym->getType() == ELF::STT_FUNC && (ESym->st_value & 1) == 1)
799       Result |= SymbolRef::SF_Thumb;
800   } else if (EF.getHeader().e_machine == ELF::EM_CSKY) {
801     if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
802       StringRef Name = *NameOrErr;
803       if (Name.starts_with("$d") || Name.starts_with("$t"))
804         Result |= SymbolRef::SF_FormatSpecific;
805     } else {
806       // TODO: Actually report errors helpfully.
807       consumeError(NameOrErr.takeError());
808     }
809   } else if (EF.getHeader().e_machine == ELF::EM_RISCV) {
810     if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
811       StringRef Name = *NameOrErr;
812       // Mark fake labels (used for label differences) and mapping symbols.
813       if (Name == ".L0 " || Name.starts_with("$d") || Name.starts_with("$x"))
814         Result |= SymbolRef::SF_FormatSpecific;
815     } else {
816       // TODO: Actually report errors helpfully.
817       consumeError(NameOrErr.takeError());
818     }
819   }
820 
821   if (ESym->st_shndx == ELF::SHN_UNDEF)
822     Result |= SymbolRef::SF_Undefined;
823 
824   if (ESym->getType() == ELF::STT_COMMON || ESym->st_shndx == ELF::SHN_COMMON)
825     Result |= SymbolRef::SF_Common;
826 
827   if (isExportedToOtherDSO(ESym))
828     Result |= SymbolRef::SF_Exported;
829 
830   if (ESym->getType() == ELF::STT_GNU_IFUNC)
831     Result |= SymbolRef::SF_Indirect;
832 
833   if (ESym->getVisibility() == ELF::STV_HIDDEN)
834     Result |= SymbolRef::SF_Hidden;
835 
836   return Result;
837 }
838 
839 template <class ELFT>
840 Expected<section_iterator>
getSymbolSection(const Elf_Sym * ESym,const Elf_Shdr * SymTab)841 ELFObjectFile<ELFT>::getSymbolSection(const Elf_Sym *ESym,
842                                       const Elf_Shdr *SymTab) const {
843   ArrayRef<Elf_Word> ShndxTable;
844   if (DotSymtabShndxSec) {
845     // TODO: Test this error.
846     Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
847         EF.getSHNDXTable(*DotSymtabShndxSec);
848     if (!ShndxTableOrErr)
849       return ShndxTableOrErr.takeError();
850     ShndxTable = *ShndxTableOrErr;
851   }
852 
853   auto ESecOrErr = EF.getSection(*ESym, SymTab, ShndxTable);
854   if (!ESecOrErr)
855     return ESecOrErr.takeError();
856 
857   const Elf_Shdr *ESec = *ESecOrErr;
858   if (!ESec)
859     return section_end();
860 
861   DataRefImpl Sec;
862   Sec.p = reinterpret_cast<intptr_t>(ESec);
863   return section_iterator(SectionRef(Sec, this));
864 }
865 
866 template <class ELFT>
867 Expected<section_iterator>
getSymbolSection(DataRefImpl Symb)868 ELFObjectFile<ELFT>::getSymbolSection(DataRefImpl Symb) const {
869   Expected<const Elf_Sym *> SymOrErr = getSymbol(Symb);
870   if (!SymOrErr)
871     return SymOrErr.takeError();
872 
873   auto SymTabOrErr = EF.getSection(Symb.d.a);
874   if (!SymTabOrErr)
875     return SymTabOrErr.takeError();
876   return getSymbolSection(*SymOrErr, *SymTabOrErr);
877 }
878 
879 template <class ELFT>
moveSectionNext(DataRefImpl & Sec)880 void ELFObjectFile<ELFT>::moveSectionNext(DataRefImpl &Sec) const {
881   const Elf_Shdr *ESec = getSection(Sec);
882   Sec = toDRI(++ESec);
883 }
884 
885 template <class ELFT>
getSectionName(DataRefImpl Sec)886 Expected<StringRef> ELFObjectFile<ELFT>::getSectionName(DataRefImpl Sec) const {
887   return EF.getSectionName(*getSection(Sec));
888 }
889 
890 template <class ELFT>
getSectionAddress(DataRefImpl Sec)891 uint64_t ELFObjectFile<ELFT>::getSectionAddress(DataRefImpl Sec) const {
892   return getSection(Sec)->sh_addr;
893 }
894 
895 template <class ELFT>
getSectionIndex(DataRefImpl Sec)896 uint64_t ELFObjectFile<ELFT>::getSectionIndex(DataRefImpl Sec) const {
897   auto SectionsOrErr = EF.sections();
898   handleAllErrors(std::move(SectionsOrErr.takeError()),
899                   [](const ErrorInfoBase &) {
900                     llvm_unreachable("unable to get section index");
901                   });
902   const Elf_Shdr *First = SectionsOrErr->begin();
903   return getSection(Sec) - First;
904 }
905 
906 template <class ELFT>
getSectionSize(DataRefImpl Sec)907 uint64_t ELFObjectFile<ELFT>::getSectionSize(DataRefImpl Sec) const {
908   return getSection(Sec)->sh_size;
909 }
910 
911 template <class ELFT>
912 Expected<ArrayRef<uint8_t>>
getSectionContents(DataRefImpl Sec)913 ELFObjectFile<ELFT>::getSectionContents(DataRefImpl Sec) const {
914   const Elf_Shdr *EShdr = getSection(Sec);
915   if (EShdr->sh_type == ELF::SHT_NOBITS)
916     return ArrayRef((const uint8_t *)base(), (size_t)0);
917   if (Error E =
918           checkOffset(getMemoryBufferRef(),
919                       (uintptr_t)base() + EShdr->sh_offset, EShdr->sh_size))
920     return std::move(E);
921   return ArrayRef((const uint8_t *)base() + EShdr->sh_offset, EShdr->sh_size);
922 }
923 
924 template <class ELFT>
getSectionAlignment(DataRefImpl Sec)925 uint64_t ELFObjectFile<ELFT>::getSectionAlignment(DataRefImpl Sec) const {
926   return getSection(Sec)->sh_addralign;
927 }
928 
929 template <class ELFT>
isSectionCompressed(DataRefImpl Sec)930 bool ELFObjectFile<ELFT>::isSectionCompressed(DataRefImpl Sec) const {
931   return getSection(Sec)->sh_flags & ELF::SHF_COMPRESSED;
932 }
933 
934 template <class ELFT>
isSectionText(DataRefImpl Sec)935 bool ELFObjectFile<ELFT>::isSectionText(DataRefImpl Sec) const {
936   return getSection(Sec)->sh_flags & ELF::SHF_EXECINSTR;
937 }
938 
939 template <class ELFT>
isSectionData(DataRefImpl Sec)940 bool ELFObjectFile<ELFT>::isSectionData(DataRefImpl Sec) const {
941   const Elf_Shdr *EShdr = getSection(Sec);
942   return EShdr->sh_type == ELF::SHT_PROGBITS &&
943          EShdr->sh_flags & ELF::SHF_ALLOC &&
944          !(EShdr->sh_flags & ELF::SHF_EXECINSTR);
945 }
946 
947 template <class ELFT>
isSectionBSS(DataRefImpl Sec)948 bool ELFObjectFile<ELFT>::isSectionBSS(DataRefImpl Sec) const {
949   const Elf_Shdr *EShdr = getSection(Sec);
950   return EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
951          EShdr->sh_type == ELF::SHT_NOBITS;
952 }
953 
954 template <class ELFT>
955 std::vector<SectionRef>
dynamic_relocation_sections()956 ELFObjectFile<ELFT>::dynamic_relocation_sections() const {
957   std::vector<SectionRef> Res;
958   std::vector<uintptr_t> Offsets;
959 
960   auto SectionsOrErr = EF.sections();
961   if (!SectionsOrErr)
962     return Res;
963 
964   for (const Elf_Shdr &Sec : *SectionsOrErr) {
965     if (Sec.sh_type != ELF::SHT_DYNAMIC)
966       continue;
967     Elf_Dyn *Dynamic =
968         reinterpret_cast<Elf_Dyn *>((uintptr_t)base() + Sec.sh_offset);
969     for (; Dynamic->d_tag != ELF::DT_NULL; Dynamic++) {
970       if (Dynamic->d_tag == ELF::DT_REL || Dynamic->d_tag == ELF::DT_RELA ||
971           Dynamic->d_tag == ELF::DT_JMPREL) {
972         Offsets.push_back(Dynamic->d_un.d_val);
973       }
974     }
975   }
976   for (const Elf_Shdr &Sec : *SectionsOrErr) {
977     if (is_contained(Offsets, Sec.sh_addr))
978       Res.emplace_back(toDRI(&Sec), this);
979   }
980   return Res;
981 }
982 
983 template <class ELFT>
isSectionVirtual(DataRefImpl Sec)984 bool ELFObjectFile<ELFT>::isSectionVirtual(DataRefImpl Sec) const {
985   return getSection(Sec)->sh_type == ELF::SHT_NOBITS;
986 }
987 
988 template <class ELFT>
isBerkeleyText(DataRefImpl Sec)989 bool ELFObjectFile<ELFT>::isBerkeleyText(DataRefImpl Sec) const {
990   return getSection(Sec)->sh_flags & ELF::SHF_ALLOC &&
991          (getSection(Sec)->sh_flags & ELF::SHF_EXECINSTR ||
992           !(getSection(Sec)->sh_flags & ELF::SHF_WRITE));
993 }
994 
995 template <class ELFT>
isBerkeleyData(DataRefImpl Sec)996 bool ELFObjectFile<ELFT>::isBerkeleyData(DataRefImpl Sec) const {
997   const Elf_Shdr *EShdr = getSection(Sec);
998   return !isBerkeleyText(Sec) && EShdr->sh_type != ELF::SHT_NOBITS &&
999          EShdr->sh_flags & ELF::SHF_ALLOC;
1000 }
1001 
1002 template <class ELFT>
isDebugSection(DataRefImpl Sec)1003 bool ELFObjectFile<ELFT>::isDebugSection(DataRefImpl Sec) const {
1004   Expected<StringRef> SectionNameOrErr = getSectionName(Sec);
1005   if (!SectionNameOrErr) {
1006     // TODO: Report the error message properly.
1007     consumeError(SectionNameOrErr.takeError());
1008     return false;
1009   }
1010   StringRef SectionName = SectionNameOrErr.get();
1011   return SectionName.starts_with(".debug") ||
1012          SectionName.starts_with(".zdebug") || SectionName == ".gdb_index";
1013 }
1014 
1015 template <class ELFT>
1016 relocation_iterator
section_rel_begin(DataRefImpl Sec)1017 ELFObjectFile<ELFT>::section_rel_begin(DataRefImpl Sec) const {
1018   DataRefImpl RelData;
1019   auto SectionsOrErr = EF.sections();
1020   if (!SectionsOrErr)
1021     return relocation_iterator(RelocationRef());
1022   uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
1023   RelData.d.a = (Sec.p - SHT) / EF.getHeader().e_shentsize;
1024   RelData.d.b = 0;
1025   return relocation_iterator(RelocationRef(RelData, this));
1026 }
1027 
1028 template <class ELFT>
1029 relocation_iterator
section_rel_end(DataRefImpl Sec)1030 ELFObjectFile<ELFT>::section_rel_end(DataRefImpl Sec) const {
1031   const Elf_Shdr *S = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1032   relocation_iterator Begin = section_rel_begin(Sec);
1033   if (S->sh_type != ELF::SHT_RELA && S->sh_type != ELF::SHT_REL)
1034     return Begin;
1035   DataRefImpl RelData = Begin->getRawDataRefImpl();
1036   const Elf_Shdr *RelSec = getRelSection(RelData);
1037 
1038   // Error check sh_link here so that getRelocationSymbol can just use it.
1039   auto SymSecOrErr = EF.getSection(RelSec->sh_link);
1040   if (!SymSecOrErr)
1041     report_fatal_error(
1042         Twine(errorToErrorCode(SymSecOrErr.takeError()).message()));
1043 
1044   RelData.d.b += S->sh_size / S->sh_entsize;
1045   return relocation_iterator(RelocationRef(RelData, this));
1046 }
1047 
1048 template <class ELFT>
1049 Expected<section_iterator>
getRelocatedSection(DataRefImpl Sec)1050 ELFObjectFile<ELFT>::getRelocatedSection(DataRefImpl Sec) const {
1051   const Elf_Shdr *EShdr = getSection(Sec);
1052   uintX_t Type = EShdr->sh_type;
1053   if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1054     return section_end();
1055 
1056   Expected<const Elf_Shdr *> SecOrErr = EF.getSection(EShdr->sh_info);
1057   if (!SecOrErr)
1058     return SecOrErr.takeError();
1059   return section_iterator(SectionRef(toDRI(*SecOrErr), this));
1060 }
1061 
1062 // Relocations
1063 template <class ELFT>
moveRelocationNext(DataRefImpl & Rel)1064 void ELFObjectFile<ELFT>::moveRelocationNext(DataRefImpl &Rel) const {
1065   ++Rel.d.b;
1066 }
1067 
1068 template <class ELFT>
1069 symbol_iterator
getRelocationSymbol(DataRefImpl Rel)1070 ELFObjectFile<ELFT>::getRelocationSymbol(DataRefImpl Rel) const {
1071   uint32_t symbolIdx;
1072   const Elf_Shdr *sec = getRelSection(Rel);
1073   if (sec->sh_type == ELF::SHT_REL)
1074     symbolIdx = getRel(Rel)->getSymbol(EF.isMips64EL());
1075   else
1076     symbolIdx = getRela(Rel)->getSymbol(EF.isMips64EL());
1077   if (!symbolIdx)
1078     return symbol_end();
1079 
1080   // FIXME: error check symbolIdx
1081   DataRefImpl SymbolData;
1082   SymbolData.d.a = sec->sh_link;
1083   SymbolData.d.b = symbolIdx;
1084   return symbol_iterator(SymbolRef(SymbolData, this));
1085 }
1086 
1087 template <class ELFT>
getRelocationOffset(DataRefImpl Rel)1088 uint64_t ELFObjectFile<ELFT>::getRelocationOffset(DataRefImpl Rel) const {
1089   const Elf_Shdr *sec = getRelSection(Rel);
1090   if (sec->sh_type == ELF::SHT_REL)
1091     return getRel(Rel)->r_offset;
1092 
1093   return getRela(Rel)->r_offset;
1094 }
1095 
1096 template <class ELFT>
getRelocationType(DataRefImpl Rel)1097 uint64_t ELFObjectFile<ELFT>::getRelocationType(DataRefImpl Rel) const {
1098   const Elf_Shdr *sec = getRelSection(Rel);
1099   if (sec->sh_type == ELF::SHT_REL)
1100     return getRel(Rel)->getType(EF.isMips64EL());
1101   else
1102     return getRela(Rel)->getType(EF.isMips64EL());
1103 }
1104 
1105 template <class ELFT>
getRelocationTypeName(uint32_t Type)1106 StringRef ELFObjectFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
1107   return getELFRelocationTypeName(EF.getHeader().e_machine, Type);
1108 }
1109 
1110 template <class ELFT>
getRelocationTypeName(DataRefImpl Rel,SmallVectorImpl<char> & Result)1111 void ELFObjectFile<ELFT>::getRelocationTypeName(
1112     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1113   uint32_t type = getRelocationType(Rel);
1114   EF.getRelocationTypeName(type, Result);
1115 }
1116 
1117 template <class ELFT>
1118 Expected<int64_t>
getRelocationAddend(DataRefImpl Rel)1119 ELFObjectFile<ELFT>::getRelocationAddend(DataRefImpl Rel) const {
1120   if (getRelSection(Rel)->sh_type != ELF::SHT_RELA)
1121     return createError("Section is not SHT_RELA");
1122   return (int64_t)getRela(Rel)->r_addend;
1123 }
1124 
1125 template <class ELFT>
1126 const typename ELFObjectFile<ELFT>::Elf_Rel *
getRel(DataRefImpl Rel)1127 ELFObjectFile<ELFT>::getRel(DataRefImpl Rel) const {
1128   assert(getRelSection(Rel)->sh_type == ELF::SHT_REL);
1129   auto Ret = EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
1130   if (!Ret)
1131     report_fatal_error(Twine(errorToErrorCode(Ret.takeError()).message()));
1132   return *Ret;
1133 }
1134 
1135 template <class ELFT>
1136 const typename ELFObjectFile<ELFT>::Elf_Rela *
getRela(DataRefImpl Rela)1137 ELFObjectFile<ELFT>::getRela(DataRefImpl Rela) const {
1138   assert(getRelSection(Rela)->sh_type == ELF::SHT_RELA);
1139   auto Ret = EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
1140   if (!Ret)
1141     report_fatal_error(Twine(errorToErrorCode(Ret.takeError()).message()));
1142   return *Ret;
1143 }
1144 
1145 template <class ELFT>
1146 Expected<ELFObjectFile<ELFT>>
create(MemoryBufferRef Object,bool InitContent)1147 ELFObjectFile<ELFT>::create(MemoryBufferRef Object, bool InitContent) {
1148   auto EFOrErr = ELFFile<ELFT>::create(Object.getBuffer());
1149   if (Error E = EFOrErr.takeError())
1150     return std::move(E);
1151 
1152   ELFObjectFile<ELFT> Obj = {Object, std::move(*EFOrErr), nullptr, nullptr,
1153                              nullptr};
1154   if (InitContent)
1155     if (Error E = Obj.initContent())
1156       return std::move(E);
1157   return std::move(Obj);
1158 }
1159 
1160 template <class ELFT>
ELFObjectFile(MemoryBufferRef Object,ELFFile<ELFT> EF,const Elf_Shdr * DotDynSymSec,const Elf_Shdr * DotSymtabSec,const Elf_Shdr * DotSymtabShndx)1161 ELFObjectFile<ELFT>::ELFObjectFile(MemoryBufferRef Object, ELFFile<ELFT> EF,
1162                                    const Elf_Shdr *DotDynSymSec,
1163                                    const Elf_Shdr *DotSymtabSec,
1164                                    const Elf_Shdr *DotSymtabShndx)
1165     : ELFObjectFileBase(getELFType(ELFT::Endianness == llvm::endianness::little,
1166                                    ELFT::Is64Bits),
1167                         Object),
1168       EF(EF), DotDynSymSec(DotDynSymSec), DotSymtabSec(DotSymtabSec),
1169       DotSymtabShndxSec(DotSymtabShndx) {}
1170 
1171 template <class ELFT>
ELFObjectFile(ELFObjectFile<ELFT> && Other)1172 ELFObjectFile<ELFT>::ELFObjectFile(ELFObjectFile<ELFT> &&Other)
1173     : ELFObjectFile(Other.Data, Other.EF, Other.DotDynSymSec,
1174                     Other.DotSymtabSec, Other.DotSymtabShndxSec) {}
1175 
1176 template <class ELFT>
symbol_begin()1177 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_begin() const {
1178   DataRefImpl Sym =
1179       toDRI(DotSymtabSec,
1180             DotSymtabSec && DotSymtabSec->sh_size >= sizeof(Elf_Sym) ? 1 : 0);
1181   return basic_symbol_iterator(SymbolRef(Sym, this));
1182 }
1183 
1184 template <class ELFT>
symbol_end()1185 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_end() const {
1186   const Elf_Shdr *SymTab = DotSymtabSec;
1187   if (!SymTab)
1188     return symbol_begin();
1189   DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
1190   return basic_symbol_iterator(SymbolRef(Sym, this));
1191 }
1192 
1193 template <class ELFT>
dynamic_symbol_begin()1194 elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_begin() const {
1195   if (!DotDynSymSec || DotDynSymSec->sh_size < sizeof(Elf_Sym))
1196     // Ignore errors here where the dynsym is empty or sh_size less than the
1197     // size of one symbol. These should be handled elsewhere.
1198     return symbol_iterator(SymbolRef(toDRI(DotDynSymSec, 0), this));
1199   // Skip 0-index NULL symbol.
1200   return symbol_iterator(SymbolRef(toDRI(DotDynSymSec, 1), this));
1201 }
1202 
1203 template <class ELFT>
dynamic_symbol_end()1204 elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_end() const {
1205   const Elf_Shdr *SymTab = DotDynSymSec;
1206   if (!SymTab)
1207     return dynamic_symbol_begin();
1208   DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
1209   return basic_symbol_iterator(SymbolRef(Sym, this));
1210 }
1211 
1212 template <class ELFT>
section_begin()1213 section_iterator ELFObjectFile<ELFT>::section_begin() const {
1214   auto SectionsOrErr = EF.sections();
1215   if (!SectionsOrErr)
1216     return section_iterator(SectionRef());
1217   return section_iterator(SectionRef(toDRI((*SectionsOrErr).begin()), this));
1218 }
1219 
1220 template <class ELFT>
section_end()1221 section_iterator ELFObjectFile<ELFT>::section_end() const {
1222   auto SectionsOrErr = EF.sections();
1223   if (!SectionsOrErr)
1224     return section_iterator(SectionRef());
1225   return section_iterator(SectionRef(toDRI((*SectionsOrErr).end()), this));
1226 }
1227 
1228 template <class ELFT>
getBytesInAddress()1229 uint8_t ELFObjectFile<ELFT>::getBytesInAddress() const {
1230   return ELFT::Is64Bits ? 8 : 4;
1231 }
1232 
1233 template <class ELFT>
getFileFormatName()1234 StringRef ELFObjectFile<ELFT>::getFileFormatName() const {
1235   constexpr bool IsLittleEndian = ELFT::Endianness == llvm::endianness::little;
1236   switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1237   case ELF::ELFCLASS32:
1238     switch (EF.getHeader().e_machine) {
1239     case ELF::EM_68K:
1240       return "elf32-m68k";
1241     case ELF::EM_386:
1242       return "elf32-i386";
1243     case ELF::EM_IAMCU:
1244       return "elf32-iamcu";
1245     case ELF::EM_X86_64:
1246       return "elf32-x86-64";
1247     case ELF::EM_ARM:
1248       return (IsLittleEndian ? "elf32-littlearm" : "elf32-bigarm");
1249     case ELF::EM_AVR:
1250       return "elf32-avr";
1251     case ELF::EM_HEXAGON:
1252       return "elf32-hexagon";
1253     case ELF::EM_LANAI:
1254       return "elf32-lanai";
1255     case ELF::EM_MIPS:
1256       return "elf32-mips";
1257     case ELF::EM_MSP430:
1258       return "elf32-msp430";
1259     case ELF::EM_PPC:
1260       return (IsLittleEndian ? "elf32-powerpcle" : "elf32-powerpc");
1261     case ELF::EM_RISCV:
1262       return "elf32-littleriscv";
1263     case ELF::EM_CSKY:
1264       return "elf32-csky";
1265     case ELF::EM_SPARC:
1266     case ELF::EM_SPARC32PLUS:
1267       return "elf32-sparc";
1268     case ELF::EM_AMDGPU:
1269       return "elf32-amdgpu";
1270     case ELF::EM_LOONGARCH:
1271       return "elf32-loongarch";
1272     case ELF::EM_XTENSA:
1273       return "elf32-xtensa";
1274     default:
1275       return "elf32-unknown";
1276     }
1277   case ELF::ELFCLASS64:
1278     switch (EF.getHeader().e_machine) {
1279     case ELF::EM_386:
1280       return "elf64-i386";
1281     case ELF::EM_X86_64:
1282       return "elf64-x86-64";
1283     case ELF::EM_AARCH64:
1284       return (IsLittleEndian ? "elf64-littleaarch64" : "elf64-bigaarch64");
1285     case ELF::EM_PPC64:
1286       return (IsLittleEndian ? "elf64-powerpcle" : "elf64-powerpc");
1287     case ELF::EM_RISCV:
1288       return "elf64-littleriscv";
1289     case ELF::EM_S390:
1290       return "elf64-s390";
1291     case ELF::EM_SPARCV9:
1292       return "elf64-sparc";
1293     case ELF::EM_MIPS:
1294       return "elf64-mips";
1295     case ELF::EM_AMDGPU:
1296       return "elf64-amdgpu";
1297     case ELF::EM_BPF:
1298       return "elf64-bpf";
1299     case ELF::EM_VE:
1300       return "elf64-ve";
1301     case ELF::EM_LOONGARCH:
1302       return "elf64-loongarch";
1303     default:
1304       return "elf64-unknown";
1305     }
1306   default:
1307     // FIXME: Proper error handling.
1308     report_fatal_error("Invalid ELFCLASS!");
1309   }
1310 }
1311 
getArch()1312 template <class ELFT> Triple::ArchType ELFObjectFile<ELFT>::getArch() const {
1313   bool IsLittleEndian = ELFT::Endianness == llvm::endianness::little;
1314   switch (EF.getHeader().e_machine) {
1315   case ELF::EM_68K:
1316     return Triple::m68k;
1317   case ELF::EM_386:
1318   case ELF::EM_IAMCU:
1319     return Triple::x86;
1320   case ELF::EM_X86_64:
1321     return Triple::x86_64;
1322   case ELF::EM_AARCH64:
1323     return IsLittleEndian ? Triple::aarch64 : Triple::aarch64_be;
1324   case ELF::EM_ARM:
1325     return Triple::arm;
1326   case ELF::EM_AVR:
1327     return Triple::avr;
1328   case ELF::EM_HEXAGON:
1329     return Triple::hexagon;
1330   case ELF::EM_LANAI:
1331     return Triple::lanai;
1332   case ELF::EM_MIPS:
1333     switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1334     case ELF::ELFCLASS32:
1335       return IsLittleEndian ? Triple::mipsel : Triple::mips;
1336     case ELF::ELFCLASS64:
1337       return IsLittleEndian ? Triple::mips64el : Triple::mips64;
1338     default:
1339       report_fatal_error("Invalid ELFCLASS!");
1340     }
1341   case ELF::EM_MSP430:
1342     return Triple::msp430;
1343   case ELF::EM_PPC:
1344     return IsLittleEndian ? Triple::ppcle : Triple::ppc;
1345   case ELF::EM_PPC64:
1346     return IsLittleEndian ? Triple::ppc64le : Triple::ppc64;
1347   case ELF::EM_RISCV:
1348     switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1349     case ELF::ELFCLASS32:
1350       return Triple::riscv32;
1351     case ELF::ELFCLASS64:
1352       return Triple::riscv64;
1353     default:
1354       report_fatal_error("Invalid ELFCLASS!");
1355     }
1356   case ELF::EM_S390:
1357     return Triple::systemz;
1358 
1359   case ELF::EM_SPARC:
1360   case ELF::EM_SPARC32PLUS:
1361     return IsLittleEndian ? Triple::sparcel : Triple::sparc;
1362   case ELF::EM_SPARCV9:
1363     return Triple::sparcv9;
1364 
1365   case ELF::EM_AMDGPU: {
1366     if (!IsLittleEndian)
1367       return Triple::UnknownArch;
1368 
1369     unsigned MACH = EF.getHeader().e_flags & ELF::EF_AMDGPU_MACH;
1370     if (MACH >= ELF::EF_AMDGPU_MACH_R600_FIRST &&
1371         MACH <= ELF::EF_AMDGPU_MACH_R600_LAST)
1372       return Triple::r600;
1373     if (MACH >= ELF::EF_AMDGPU_MACH_AMDGCN_FIRST &&
1374         MACH <= ELF::EF_AMDGPU_MACH_AMDGCN_LAST)
1375       return Triple::amdgcn;
1376 
1377     return Triple::UnknownArch;
1378   }
1379 
1380   case ELF::EM_CUDA: {
1381     if (EF.getHeader().e_ident[ELF::EI_CLASS] == ELF::ELFCLASS32)
1382       return Triple::nvptx;
1383     return Triple::nvptx64;
1384   }
1385 
1386   case ELF::EM_BPF:
1387     return IsLittleEndian ? Triple::bpfel : Triple::bpfeb;
1388 
1389   case ELF::EM_VE:
1390     return Triple::ve;
1391   case ELF::EM_CSKY:
1392     return Triple::csky;
1393 
1394   case ELF::EM_LOONGARCH:
1395     switch (EF.getHeader().e_ident[ELF::EI_CLASS]) {
1396     case ELF::ELFCLASS32:
1397       return Triple::loongarch32;
1398     case ELF::ELFCLASS64:
1399       return Triple::loongarch64;
1400     default:
1401       report_fatal_error("Invalid ELFCLASS!");
1402     }
1403 
1404   case ELF::EM_XTENSA:
1405     return Triple::xtensa;
1406 
1407   default:
1408     return Triple::UnknownArch;
1409   }
1410 }
1411 
getOS()1412 template <class ELFT> Triple::OSType ELFObjectFile<ELFT>::getOS() const {
1413   switch (EF.getHeader().e_ident[ELF::EI_OSABI]) {
1414   case ELF::ELFOSABI_NETBSD:
1415     return Triple::NetBSD;
1416   case ELF::ELFOSABI_LINUX:
1417     return Triple::Linux;
1418   case ELF::ELFOSABI_HURD:
1419     return Triple::Hurd;
1420   case ELF::ELFOSABI_SOLARIS:
1421     return Triple::Solaris;
1422   case ELF::ELFOSABI_AIX:
1423     return Triple::AIX;
1424   case ELF::ELFOSABI_FREEBSD:
1425     return Triple::FreeBSD;
1426   case ELF::ELFOSABI_OPENBSD:
1427     return Triple::OpenBSD;
1428   case ELF::ELFOSABI_CUDA:
1429     return Triple::CUDA;
1430   case ELF::ELFOSABI_AMDGPU_HSA:
1431     return Triple::AMDHSA;
1432   case ELF::ELFOSABI_AMDGPU_PAL:
1433     return Triple::AMDPAL;
1434   case ELF::ELFOSABI_AMDGPU_MESA3D:
1435     return Triple::Mesa3D;
1436   default:
1437     return Triple::UnknownOS;
1438   }
1439 }
1440 
1441 template <class ELFT>
getStartAddress()1442 Expected<uint64_t> ELFObjectFile<ELFT>::getStartAddress() const {
1443   return EF.getHeader().e_entry;
1444 }
1445 
1446 template <class ELFT>
1447 ELFObjectFileBase::elf_symbol_iterator_range
getDynamicSymbolIterators()1448 ELFObjectFile<ELFT>::getDynamicSymbolIterators() const {
1449   return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
1450 }
1451 
isRelocatableObject()1452 template <class ELFT> bool ELFObjectFile<ELFT>::isRelocatableObject() const {
1453   return EF.getHeader().e_type == ELF::ET_REL;
1454 }
1455 
1456 } // end namespace object
1457 } // end namespace llvm
1458 
1459 #endif // LLVM_OBJECT_ELFOBJECTFILE_H
1460