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