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