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