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