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