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