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