[Object]
[oota-llvm.git] / include / llvm / Object / ELF.h
1 //===- ELF.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_ELF_H
15 #define LLVM_OBJECT_ELF_H
16
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/ELF.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 #include <limits>
30 #include <utility>
31
32 namespace llvm {
33 namespace object {
34
35 // Templates to choose Elf_Addr and Elf_Off depending on is64Bits.
36 template<support::endianness target_endianness>
37 struct ELFDataTypeTypedefHelperCommon {
38   typedef support::detail::packed_endian_specific_integral
39     <uint16_t, target_endianness, support::aligned> Elf_Half;
40   typedef support::detail::packed_endian_specific_integral
41     <uint32_t, target_endianness, support::aligned> Elf_Word;
42   typedef support::detail::packed_endian_specific_integral
43     <int32_t, target_endianness, support::aligned> Elf_Sword;
44   typedef support::detail::packed_endian_specific_integral
45     <uint64_t, target_endianness, support::aligned> Elf_Xword;
46   typedef support::detail::packed_endian_specific_integral
47     <int64_t, target_endianness, support::aligned> Elf_Sxword;
48 };
49
50 template<support::endianness target_endianness, bool is64Bits>
51 struct ELFDataTypeTypedefHelper;
52
53 /// ELF 32bit types.
54 template<support::endianness target_endianness>
55 struct ELFDataTypeTypedefHelper<target_endianness, false>
56   : ELFDataTypeTypedefHelperCommon<target_endianness> {
57   typedef uint32_t value_type;
58   typedef support::detail::packed_endian_specific_integral
59     <value_type, target_endianness, support::aligned> Elf_Addr;
60   typedef support::detail::packed_endian_specific_integral
61     <value_type, target_endianness, support::aligned> Elf_Off;
62 };
63
64 /// ELF 64bit types.
65 template<support::endianness target_endianness>
66 struct ELFDataTypeTypedefHelper<target_endianness, true>
67   : ELFDataTypeTypedefHelperCommon<target_endianness>{
68   typedef uint64_t value_type;
69   typedef support::detail::packed_endian_specific_integral
70     <value_type, target_endianness, support::aligned> Elf_Addr;
71   typedef support::detail::packed_endian_specific_integral
72     <value_type, target_endianness, support::aligned> Elf_Off;
73 };
74
75 // I really don't like doing this, but the alternative is copypasta.
76 #define LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits) \
77 typedef typename \
78   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Addr Elf_Addr; \
79 typedef typename \
80   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Off Elf_Off; \
81 typedef typename \
82   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Half Elf_Half; \
83 typedef typename \
84   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Word Elf_Word; \
85 typedef typename \
86   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sword Elf_Sword; \
87 typedef typename \
88   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Xword Elf_Xword; \
89 typedef typename \
90   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sxword Elf_Sxword;
91
92   // Section header.
93 template<support::endianness target_endianness, bool is64Bits>
94 struct Elf_Shdr_Base;
95
96 template<support::endianness target_endianness>
97 struct Elf_Shdr_Base<target_endianness, false> {
98   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
99   Elf_Word sh_name;     // Section name (index into string table)
100   Elf_Word sh_type;     // Section type (SHT_*)
101   Elf_Word sh_flags;    // Section flags (SHF_*)
102   Elf_Addr sh_addr;     // Address where section is to be loaded
103   Elf_Off  sh_offset;   // File offset of section data, in bytes
104   Elf_Word sh_size;     // Size of section, in bytes
105   Elf_Word sh_link;     // Section type-specific header table index link
106   Elf_Word sh_info;     // Section type-specific extra information
107   Elf_Word sh_addralign;// Section address alignment
108   Elf_Word sh_entsize;  // Size of records contained within the section
109 };
110
111 template<support::endianness target_endianness>
112 struct Elf_Shdr_Base<target_endianness, true> {
113   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
114   Elf_Word  sh_name;     // Section name (index into string table)
115   Elf_Word  sh_type;     // Section type (SHT_*)
116   Elf_Xword sh_flags;    // Section flags (SHF_*)
117   Elf_Addr  sh_addr;     // Address where section is to be loaded
118   Elf_Off   sh_offset;   // File offset of section data, in bytes
119   Elf_Xword sh_size;     // Size of section, in bytes
120   Elf_Word  sh_link;     // Section type-specific header table index link
121   Elf_Word  sh_info;     // Section type-specific extra information
122   Elf_Xword sh_addralign;// Section address alignment
123   Elf_Xword sh_entsize;  // Size of records contained within the section
124 };
125
126 template<support::endianness target_endianness, bool is64Bits>
127 struct Elf_Shdr_Impl : Elf_Shdr_Base<target_endianness, is64Bits> {
128   using Elf_Shdr_Base<target_endianness, is64Bits>::sh_entsize;
129   using Elf_Shdr_Base<target_endianness, is64Bits>::sh_size;
130
131   /// @brief Get the number of entities this section contains if it has any.
132   unsigned getEntityCount() const {
133     if (sh_entsize == 0)
134       return 0;
135     return sh_size / sh_entsize;
136   }
137 };
138
139 template<support::endianness target_endianness, bool is64Bits>
140 struct Elf_Sym_Base;
141
142 template<support::endianness target_endianness>
143 struct Elf_Sym_Base<target_endianness, false> {
144   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
145   Elf_Word      st_name;  // Symbol name (index into string table)
146   Elf_Addr      st_value; // Value or address associated with the symbol
147   Elf_Word      st_size;  // Size of the symbol
148   unsigned char st_info;  // Symbol's type and binding attributes
149   unsigned char st_other; // Must be zero; reserved
150   Elf_Half      st_shndx; // Which section (header table index) it's defined in
151 };
152
153 template<support::endianness target_endianness>
154 struct Elf_Sym_Base<target_endianness, true> {
155   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
156   Elf_Word      st_name;  // Symbol name (index into string table)
157   unsigned char st_info;  // Symbol's type and binding attributes
158   unsigned char st_other; // Must be zero; reserved
159   Elf_Half      st_shndx; // Which section (header table index) it's defined in
160   Elf_Addr      st_value; // Value or address associated with the symbol
161   Elf_Xword     st_size;  // Size of the symbol
162 };
163
164 template<support::endianness target_endianness, bool is64Bits>
165 struct Elf_Sym_Impl : Elf_Sym_Base<target_endianness, is64Bits> {
166   using Elf_Sym_Base<target_endianness, is64Bits>::st_info;
167
168   // These accessors and mutators correspond to the ELF32_ST_BIND,
169   // ELF32_ST_TYPE, and ELF32_ST_INFO macros defined in the ELF specification:
170   unsigned char getBinding() const { return st_info >> 4; }
171   unsigned char getType() const { return st_info & 0x0f; }
172   void setBinding(unsigned char b) { setBindingAndType(b, getType()); }
173   void setType(unsigned char t) { setBindingAndType(getBinding(), t); }
174   void setBindingAndType(unsigned char b, unsigned char t) {
175     st_info = (b << 4) + (t & 0x0f);
176   }
177 };
178
179 // Elf_Dyn: Entry in the dynamic table
180 template<support::endianness target_endianness, bool is64Bits>
181 struct Elf_Dyn_Base;
182
183 template<support::endianness target_endianness>
184 struct Elf_Dyn_Base<target_endianness, false> {
185   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
186   Elf_Sword d_tag;
187   union {
188     Elf_Word d_val;
189     Elf_Addr d_ptr;
190   } d_un;
191 };
192
193 template<support::endianness target_endianness>
194 struct Elf_Dyn_Base<target_endianness, true> {
195   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
196   Elf_Sxword d_tag;
197   union {
198     Elf_Xword d_val;
199     Elf_Addr d_ptr;
200   } d_un;
201 };
202
203 template<support::endianness target_endianness, bool is64Bits>
204 struct Elf_Dyn_Impl : Elf_Dyn_Base<target_endianness, is64Bits> {
205   using Elf_Dyn_Base<target_endianness, is64Bits>::d_tag;
206   using Elf_Dyn_Base<target_endianness, is64Bits>::d_un;
207   int64_t getTag() const { return d_tag; }
208   uint64_t getVal() const { return d_un.d_val; }
209   uint64_t getPtr() const { return d_un.ptr; }
210 };
211
212 template<support::endianness target_endianness, bool is64Bits>
213 class ELFObjectFile;
214
215 // DynRefImpl: Reference to an entry in the dynamic table
216 // This is an ELF-specific interface.
217 template<support::endianness target_endianness, bool is64Bits>
218 class DynRefImpl {
219   typedef Elf_Dyn_Impl<target_endianness, is64Bits> Elf_Dyn;
220   typedef ELFObjectFile<target_endianness, is64Bits> OwningType;
221
222   DataRefImpl DynPimpl;
223   const OwningType *OwningObject;
224
225 public:
226   DynRefImpl() : OwningObject(NULL) {
227     std::memset(&DynPimpl, 0, sizeof(DynPimpl));
228   }
229
230   DynRefImpl(DataRefImpl DynP, const OwningType *Owner);
231
232   bool operator==(const DynRefImpl &Other) const;
233   bool operator <(const DynRefImpl &Other) const;
234
235   error_code getNext(DynRefImpl &Result) const;
236   int64_t getTag() const;
237   uint64_t getVal() const;
238   uint64_t getPtr() const;
239
240   DataRefImpl getRawDataRefImpl() const;
241 };
242
243 // Elf_Rel: Elf Relocation
244 template<support::endianness target_endianness, bool is64Bits, bool isRela>
245 struct Elf_Rel_Base;
246
247 template<support::endianness target_endianness>
248 struct Elf_Rel_Base<target_endianness, false, false> {
249   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
250   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
251   Elf_Word      r_info;  // Symbol table index and type of relocation to apply
252 };
253
254 template<support::endianness target_endianness>
255 struct Elf_Rel_Base<target_endianness, true, false> {
256   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
257   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
258   Elf_Xword     r_info;   // Symbol table index and type of relocation to apply
259 };
260
261 template<support::endianness target_endianness>
262 struct Elf_Rel_Base<target_endianness, false, true> {
263   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
264   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
265   Elf_Word      r_info;   // Symbol table index and type of relocation to apply
266   Elf_Sword     r_addend; // Compute value for relocatable field by adding this
267 };
268
269 template<support::endianness target_endianness>
270 struct Elf_Rel_Base<target_endianness, true, true> {
271   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
272   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
273   Elf_Xword     r_info;   // Symbol table index and type of relocation to apply
274   Elf_Sxword    r_addend; // Compute value for relocatable field by adding this.
275 };
276
277 template<support::endianness target_endianness, bool is64Bits, bool isRela>
278 struct Elf_Rel_Impl;
279
280 template<support::endianness target_endianness, bool isRela>
281 struct Elf_Rel_Impl<target_endianness, true, isRela>
282        : Elf_Rel_Base<target_endianness, true, isRela> {
283   using Elf_Rel_Base<target_endianness, true, isRela>::r_info;
284   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
285
286   // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_TYPE,
287   // and ELF64_R_INFO macros defined in the ELF specification:
288   uint64_t getSymbol() const { return (r_info >> 32); }
289   unsigned char getType() const {
290     return (unsigned char) (r_info & 0xffffffffL);
291   }
292   void setSymbol(uint64_t s) { setSymbolAndType(s, getType()); }
293   void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
294   void setSymbolAndType(uint64_t s, unsigned char t) {
295     r_info = (s << 32) + (t&0xffffffffL);
296   }
297 };
298
299 template<support::endianness target_endianness, bool isRela>
300 struct Elf_Rel_Impl<target_endianness, false, isRela>
301        : Elf_Rel_Base<target_endianness, false, isRela> {
302   using Elf_Rel_Base<target_endianness, false, isRela>::r_info;
303   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
304
305   // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_TYPE,
306   // and ELF32_R_INFO macros defined in the ELF specification:
307   uint32_t getSymbol() const { return (r_info >> 8); }
308   unsigned char getType() const { return (unsigned char) (r_info & 0x0ff); }
309   void setSymbol(uint32_t s) { setSymbolAndType(s, getType()); }
310   void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
311   void setSymbolAndType(uint32_t s, unsigned char t) {
312     r_info = (s << 8) + t;
313   }
314 };
315
316
317 template<support::endianness target_endianness, bool is64Bits>
318 class ELFObjectFile : public ObjectFile {
319   LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
320
321   typedef Elf_Shdr_Impl<target_endianness, is64Bits> Elf_Shdr;
322   typedef Elf_Sym_Impl<target_endianness, is64Bits> Elf_Sym;
323   typedef Elf_Dyn_Impl<target_endianness, is64Bits> Elf_Dyn;
324   typedef Elf_Rel_Impl<target_endianness, is64Bits, false> Elf_Rel;
325   typedef Elf_Rel_Impl<target_endianness, is64Bits, true> Elf_Rela;
326   typedef DynRefImpl<target_endianness, is64Bits> DynRef;
327   typedef content_iterator<DynRef> dyn_iterator;
328
329 protected:
330   struct Elf_Ehdr {
331     unsigned char e_ident[ELF::EI_NIDENT]; // ELF Identification bytes
332     Elf_Half e_type;     // Type of file (see ET_*)
333     Elf_Half e_machine;  // Required architecture for this file (see EM_*)
334     Elf_Word e_version;  // Must be equal to 1
335     Elf_Addr e_entry;    // Address to jump to in order to start program
336     Elf_Off  e_phoff;    // Program header table's file offset, in bytes
337     Elf_Off  e_shoff;    // Section header table's file offset, in bytes
338     Elf_Word e_flags;    // Processor-specific flags
339     Elf_Half e_ehsize;   // Size of ELF header, in bytes
340     Elf_Half e_phentsize;// Size of an entry in the program header table
341     Elf_Half e_phnum;    // Number of entries in the program header table
342     Elf_Half e_shentsize;// Size of an entry in the section header table
343     Elf_Half e_shnum;    // Number of entries in the section header table
344     Elf_Half e_shstrndx; // Section header table index of section name
345                                   // string table
346     bool checkMagic() const {
347       return (memcmp(e_ident, ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
348     }
349     unsigned char getFileClass() const { return e_ident[ELF::EI_CLASS]; }
350     unsigned char getDataEncoding() const { return e_ident[ELF::EI_DATA]; }
351   };
352   // This flag is used for classof, to distinguish ELFObjectFile from
353   // its subclass. If more subclasses will be created, this flag will
354   // have to become an enum.
355   bool isDyldELFObject;
356
357 private:
358   typedef SmallVector<const Elf_Shdr*, 1> Sections_t;
359   typedef DenseMap<unsigned, unsigned> IndexMap_t;
360   typedef DenseMap<const Elf_Shdr*, SmallVector<uint32_t, 1> > RelocMap_t;
361
362   const Elf_Ehdr *Header;
363   const Elf_Shdr *SectionHeaderTable;
364   const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
365   const Elf_Shdr *dot_strtab_sec;   // Symbol header string table.
366   const Elf_Shdr *dot_dynstr_sec;   // Dynamic symbol string table.
367   Sections_t SymbolTableSections;
368   IndexMap_t SymbolTableSectionsIndexMap;
369   DenseMap<const Elf_Sym*, ELF::Elf64_Word> ExtendedSymbolTable;
370
371   const Elf_Shdr *dot_dynamic_sec; // .dynamic
372
373   /// @brief Map sections to an array of relocation sections that reference
374   ///        them sorted by section index.
375   RelocMap_t SectionRelocMap;
376
377   /// @brief Get the relocation section that contains \a Rel.
378   const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
379     return getSection(Rel.w.b);
380   }
381
382   bool            isRelocationHasAddend(DataRefImpl Rel) const;
383   template<typename T>
384   const T        *getEntry(uint16_t Section, uint32_t Entry) const;
385   template<typename T>
386   const T        *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
387   const Elf_Shdr *getSection(DataRefImpl index) const;
388   const Elf_Shdr *getSection(uint32_t index) const;
389   const Elf_Rel  *getRel(DataRefImpl Rel) const;
390   const Elf_Rela *getRela(DataRefImpl Rela) const;
391   const char     *getString(uint32_t section, uint32_t offset) const;
392   const char     *getString(const Elf_Shdr *section, uint32_t offset) const;
393   error_code      getSymbolName(const Elf_Shdr *section,
394                                 const Elf_Sym *Symb,
395                                 StringRef &Res) const;
396   void VerifyStrTab(const Elf_Shdr *sh) const;
397
398 protected:
399   const Elf_Sym  *getSymbol(DataRefImpl Symb) const; // FIXME: Should be private?
400   void            validateSymbol(DataRefImpl Symb) const;
401
402 public:
403   const Elf_Dyn  *getDyn(DataRefImpl DynData) const;
404
405 protected:
406   virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
407   virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
408   virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) const;
409   virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const;
410   virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
411   virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const;
412   virtual error_code getSymbolFlags(DataRefImpl Symb, uint32_t &Res) const;
413   virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res) const;
414   virtual error_code getSymbolSection(DataRefImpl Symb,
415                                       section_iterator &Res) const;
416
417   friend class DynRefImpl<target_endianness, is64Bits>;
418   virtual error_code getDynNext(DataRefImpl DynData, DynRef &Result) const;
419
420   virtual error_code getLibraryNext(DataRefImpl Data, LibraryRef &Result) const;
421   virtual error_code getLibraryPath(DataRefImpl Data, StringRef &Res) const;
422
423   virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
424   virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
425   virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
426   virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
427   virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
428   virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const;
429   virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
430   virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
431   virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
432   virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
433                                            bool &Result) const;
434   virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
435   virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;
436
437   virtual error_code getRelocationNext(DataRefImpl Rel,
438                                        RelocationRef &Res) const;
439   virtual error_code getRelocationAddress(DataRefImpl Rel,
440                                           uint64_t &Res) const;
441   virtual error_code getRelocationOffset(DataRefImpl Rel,
442                                          uint64_t &Res) const;
443   virtual error_code getRelocationSymbol(DataRefImpl Rel,
444                                          SymbolRef &Res) const;
445   virtual error_code getRelocationType(DataRefImpl Rel,
446                                        uint64_t &Res) const;
447   virtual error_code getRelocationTypeName(DataRefImpl Rel,
448                                            SmallVectorImpl<char> &Result) const;
449   virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
450                                                  int64_t &Res) const;
451   virtual error_code getRelocationValueString(DataRefImpl Rel,
452                                            SmallVectorImpl<char> &Result) const;
453
454 public:
455   ELFObjectFile(MemoryBuffer *Object, error_code &ec);
456   virtual symbol_iterator begin_symbols() const;
457   virtual symbol_iterator end_symbols() const;
458
459   virtual symbol_iterator begin_dynamic_symbols() const;
460   virtual symbol_iterator end_dynamic_symbols() const;
461
462   virtual section_iterator begin_sections() const;
463   virtual section_iterator end_sections() const;
464
465   virtual library_iterator begin_libraries_needed() const;
466   virtual library_iterator end_libraries_needed() const;
467
468   virtual dyn_iterator begin_dynamic_table() const;
469   virtual dyn_iterator end_dynamic_table() const;
470
471   virtual uint8_t getBytesInAddress() const;
472   virtual StringRef getFileFormatName() const;
473   virtual unsigned getArch() const;
474
475   uint64_t getNumSections() const;
476   uint64_t getStringTableIndex() const;
477   ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
478   const Elf_Shdr *getSection(const Elf_Sym *symb) const;
479
480   // Methods for type inquiry through isa, cast, and dyn_cast
481   bool isDyldType() const { return isDyldELFObject; }
482   static inline bool classof(const Binary *v) {
483     return v->getType() == Binary::isELF;
484   }
485   static inline bool classof(const ELFObjectFile *v) { return true; }
486 };
487
488 template<support::endianness target_endianness, bool is64Bits>
489 void ELFObjectFile<target_endianness, is64Bits>
490                   ::validateSymbol(DataRefImpl Symb) const {
491   const Elf_Sym  *symb = getSymbol(Symb);
492   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
493   // FIXME: We really need to do proper error handling in the case of an invalid
494   //        input file. Because we don't use exceptions, I think we'll just pass
495   //        an error object around.
496   if (!(  symb
497         && SymbolTableSection
498         && symb >= (const Elf_Sym*)(base()
499                    + SymbolTableSection->sh_offset)
500         && symb <  (const Elf_Sym*)(base()
501                    + SymbolTableSection->sh_offset
502                    + SymbolTableSection->sh_size)))
503     // FIXME: Proper error handling.
504     report_fatal_error("Symb must point to a valid symbol!");
505 }
506
507 template<support::endianness target_endianness, bool is64Bits>
508 error_code ELFObjectFile<target_endianness, is64Bits>
509                         ::getSymbolNext(DataRefImpl Symb,
510                                         SymbolRef &Result) const {
511   validateSymbol(Symb);
512   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
513
514   ++Symb.d.a;
515   // Check to see if we are at the end of this symbol table.
516   if (Symb.d.a >= SymbolTableSection->getEntityCount()) {
517     // We are at the end. If there are other symbol tables, jump to them.
518     // If the symbol table is .dynsym, we are iterating dynamic symbols,
519     // and there is only one table of these.
520     if (Symb.d.b != 0) {
521       ++Symb.d.b;
522       Symb.d.a = 1; // The 0th symbol in ELF is fake.
523     }
524     // Otherwise return the terminator.
525     if (Symb.d.b == 0 || Symb.d.b >= SymbolTableSections.size()) {
526       Symb.d.a = std::numeric_limits<uint32_t>::max();
527       Symb.d.b = std::numeric_limits<uint32_t>::max();
528     }
529   }
530
531   Result = SymbolRef(Symb, this);
532   return object_error::success;
533 }
534
535 template<support::endianness target_endianness, bool is64Bits>
536 error_code ELFObjectFile<target_endianness, is64Bits>
537                         ::getSymbolName(DataRefImpl Symb,
538                                         StringRef &Result) const {
539   validateSymbol(Symb);
540   const Elf_Sym *symb = getSymbol(Symb);
541   return getSymbolName(SymbolTableSections[Symb.d.b], symb, Result);
542 }
543
544 template<support::endianness target_endianness, bool is64Bits>
545 ELF::Elf64_Word ELFObjectFile<target_endianness, is64Bits>
546                       ::getSymbolTableIndex(const Elf_Sym *symb) const {
547   if (symb->st_shndx == ELF::SHN_XINDEX)
548     return ExtendedSymbolTable.lookup(symb);
549   return symb->st_shndx;
550 }
551
552 template<support::endianness target_endianness, bool is64Bits>
553 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
554 ELFObjectFile<target_endianness, is64Bits>
555                              ::getSection(const Elf_Sym *symb) const {
556   if (symb->st_shndx == ELF::SHN_XINDEX)
557     return getSection(ExtendedSymbolTable.lookup(symb));
558   if (symb->st_shndx >= ELF::SHN_LORESERVE)
559     return 0;
560   return getSection(symb->st_shndx);
561 }
562
563 template<support::endianness target_endianness, bool is64Bits>
564 error_code ELFObjectFile<target_endianness, is64Bits>
565                         ::getSymbolFileOffset(DataRefImpl Symb,
566                                           uint64_t &Result) const {
567   validateSymbol(Symb);
568   const Elf_Sym  *symb = getSymbol(Symb);
569   const Elf_Shdr *Section;
570   switch (getSymbolTableIndex(symb)) {
571   case ELF::SHN_COMMON:
572    // Unintialized symbols have no offset in the object file
573   case ELF::SHN_UNDEF:
574     Result = UnknownAddressOrSize;
575     return object_error::success;
576   case ELF::SHN_ABS:
577     Result = symb->st_value;
578     return object_error::success;
579   default: Section = getSection(symb);
580   }
581
582   switch (symb->getType()) {
583   case ELF::STT_SECTION:
584     Result = Section ? Section->sh_addr : UnknownAddressOrSize;
585     return object_error::success;
586   case ELF::STT_FUNC:
587   case ELF::STT_OBJECT:
588   case ELF::STT_NOTYPE:
589     Result = symb->st_value +
590              (Section ? Section->sh_offset : 0);
591     return object_error::success;
592   default:
593     Result = UnknownAddressOrSize;
594     return object_error::success;
595   }
596 }
597
598 template<support::endianness target_endianness, bool is64Bits>
599 error_code ELFObjectFile<target_endianness, is64Bits>
600                         ::getSymbolAddress(DataRefImpl Symb,
601                                            uint64_t &Result) const {
602   validateSymbol(Symb);
603   const Elf_Sym  *symb = getSymbol(Symb);
604   const Elf_Shdr *Section;
605   switch (getSymbolTableIndex(symb)) {
606   case ELF::SHN_COMMON:
607   case ELF::SHN_UNDEF:
608     Result = UnknownAddressOrSize;
609     return object_error::success;
610   case ELF::SHN_ABS:
611     Result = symb->st_value;
612     return object_error::success;
613   default: Section = getSection(symb);
614   }
615
616   switch (symb->getType()) {
617   case ELF::STT_SECTION:
618     Result = Section ? Section->sh_addr : UnknownAddressOrSize;
619     return object_error::success;
620   case ELF::STT_FUNC:
621   case ELF::STT_OBJECT:
622   case ELF::STT_NOTYPE:
623     Result = symb->st_value + (Section ? Section->sh_addr : 0);
624     return object_error::success;
625   default:
626     Result = UnknownAddressOrSize;
627     return object_error::success;
628   }
629 }
630
631 template<support::endianness target_endianness, bool is64Bits>
632 error_code ELFObjectFile<target_endianness, is64Bits>
633                         ::getSymbolSize(DataRefImpl Symb,
634                                         uint64_t &Result) const {
635   validateSymbol(Symb);
636   const Elf_Sym  *symb = getSymbol(Symb);
637   if (symb->st_size == 0)
638     Result = UnknownAddressOrSize;
639   Result = symb->st_size;
640   return object_error::success;
641 }
642
643 template<support::endianness target_endianness, bool is64Bits>
644 error_code ELFObjectFile<target_endianness, is64Bits>
645                         ::getSymbolNMTypeChar(DataRefImpl Symb,
646                                               char &Result) const {
647   validateSymbol(Symb);
648   const Elf_Sym  *symb = getSymbol(Symb);
649   const Elf_Shdr *Section = getSection(symb);
650
651   char ret = '?';
652
653   if (Section) {
654     switch (Section->sh_type) {
655     case ELF::SHT_PROGBITS:
656     case ELF::SHT_DYNAMIC:
657       switch (Section->sh_flags) {
658       case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
659         ret = 't'; break;
660       case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
661         ret = 'd'; break;
662       case ELF::SHF_ALLOC:
663       case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
664       case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
665         ret = 'r'; break;
666       }
667       break;
668     case ELF::SHT_NOBITS: ret = 'b';
669     }
670   }
671
672   switch (getSymbolTableIndex(symb)) {
673   case ELF::SHN_UNDEF:
674     if (ret == '?')
675       ret = 'U';
676     break;
677   case ELF::SHN_ABS: ret = 'a'; break;
678   case ELF::SHN_COMMON: ret = 'c'; break;
679   }
680
681   switch (symb->getBinding()) {
682   case ELF::STB_GLOBAL: ret = ::toupper(ret); break;
683   case ELF::STB_WEAK:
684     if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF)
685       ret = 'w';
686     else
687       if (symb->getType() == ELF::STT_OBJECT)
688         ret = 'V';
689       else
690         ret = 'W';
691   }
692
693   if (ret == '?' && symb->getType() == ELF::STT_SECTION) {
694     StringRef name;
695     if (error_code ec = getSymbolName(Symb, name))
696       return ec;
697     Result = StringSwitch<char>(name)
698       .StartsWith(".debug", 'N')
699       .StartsWith(".note", 'n')
700       .Default('?');
701     return object_error::success;
702   }
703
704   Result = ret;
705   return object_error::success;
706 }
707
708 template<support::endianness target_endianness, bool is64Bits>
709 error_code ELFObjectFile<target_endianness, is64Bits>
710                         ::getSymbolType(DataRefImpl Symb,
711                                         SymbolRef::Type &Result) const {
712   validateSymbol(Symb);
713   const Elf_Sym  *symb = getSymbol(Symb);
714
715   switch (symb->getType()) {
716   case ELF::STT_NOTYPE:
717     Result = SymbolRef::ST_Unknown;
718     break;
719   case ELF::STT_SECTION:
720     Result = SymbolRef::ST_Debug;
721     break;
722   case ELF::STT_FILE:
723     Result = SymbolRef::ST_File;
724     break;
725   case ELF::STT_FUNC:
726     Result = SymbolRef::ST_Function;
727     break;
728   case ELF::STT_OBJECT:
729   case ELF::STT_COMMON:
730   case ELF::STT_TLS:
731     Result = SymbolRef::ST_Data;
732     break;
733   default:
734     Result = SymbolRef::ST_Other;
735     break;
736   }
737   return object_error::success;
738 }
739
740 template<support::endianness target_endianness, bool is64Bits>
741 error_code ELFObjectFile<target_endianness, is64Bits>
742                         ::getSymbolFlags(DataRefImpl Symb,
743                                          uint32_t &Result) const {
744   validateSymbol(Symb);
745   const Elf_Sym  *symb = getSymbol(Symb);
746
747   Result = SymbolRef::SF_None;
748
749   if (symb->getBinding() != ELF::STB_LOCAL)
750     Result |= SymbolRef::SF_Global;
751
752   if (symb->getBinding() == ELF::STB_WEAK)
753     Result |= SymbolRef::SF_Weak;
754
755   if (symb->st_shndx == ELF::SHN_ABS)
756     Result |= SymbolRef::SF_Absolute;
757
758   if (symb->getType() == ELF::STT_FILE ||
759       symb->getType() == ELF::STT_SECTION)
760     Result |= SymbolRef::SF_FormatSpecific;
761
762   if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF)
763     Result |= SymbolRef::SF_Undefined;
764
765   if (symb->getType() == ELF::STT_COMMON ||
766       getSymbolTableIndex(symb) == ELF::SHN_COMMON)
767     Result |= SymbolRef::SF_Common;
768
769   if (symb->getType() == ELF::STT_TLS)
770     Result |= SymbolRef::SF_ThreadLocal;
771
772   return object_error::success;
773 }
774
775 template<support::endianness target_endianness, bool is64Bits>
776 error_code ELFObjectFile<target_endianness, is64Bits>
777                         ::getSymbolSection(DataRefImpl Symb,
778                                            section_iterator &Res) const {
779   validateSymbol(Symb);
780   const Elf_Sym  *symb = getSymbol(Symb);
781   const Elf_Shdr *sec = getSection(symb);
782   if (!sec)
783     Res = end_sections();
784   else {
785     DataRefImpl Sec;
786     Sec.p = reinterpret_cast<intptr_t>(sec);
787     Res = section_iterator(SectionRef(Sec, this));
788   }
789   return object_error::success;
790 }
791
792 template<support::endianness target_endianness, bool is64Bits>
793 error_code ELFObjectFile<target_endianness, is64Bits>
794                         ::getSectionNext(DataRefImpl Sec, SectionRef &Result) const {
795   const uint8_t *sec = reinterpret_cast<const uint8_t *>(Sec.p);
796   sec += Header->e_shentsize;
797   Sec.p = reinterpret_cast<intptr_t>(sec);
798   Result = SectionRef(Sec, this);
799   return object_error::success;
800 }
801
802 template<support::endianness target_endianness, bool is64Bits>
803 error_code ELFObjectFile<target_endianness, is64Bits>
804                         ::getSectionName(DataRefImpl Sec,
805                                          StringRef &Result) const {
806   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
807   Result = StringRef(getString(dot_shstrtab_sec, sec->sh_name));
808   return object_error::success;
809 }
810
811 template<support::endianness target_endianness, bool is64Bits>
812 error_code ELFObjectFile<target_endianness, is64Bits>
813                         ::getSectionAddress(DataRefImpl Sec,
814                                             uint64_t &Result) const {
815   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
816   Result = sec->sh_addr;
817   return object_error::success;
818 }
819
820 template<support::endianness target_endianness, bool is64Bits>
821 error_code ELFObjectFile<target_endianness, is64Bits>
822                         ::getSectionSize(DataRefImpl Sec,
823                                          uint64_t &Result) const {
824   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
825   Result = sec->sh_size;
826   return object_error::success;
827 }
828
829 template<support::endianness target_endianness, bool is64Bits>
830 error_code ELFObjectFile<target_endianness, is64Bits>
831                         ::getSectionContents(DataRefImpl Sec,
832                                              StringRef &Result) const {
833   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
834   const char *start = (const char*)base() + sec->sh_offset;
835   Result = StringRef(start, sec->sh_size);
836   return object_error::success;
837 }
838
839 template<support::endianness target_endianness, bool is64Bits>
840 error_code ELFObjectFile<target_endianness, is64Bits>
841                         ::getSectionAlignment(DataRefImpl Sec,
842                                               uint64_t &Result) const {
843   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
844   Result = sec->sh_addralign;
845   return object_error::success;
846 }
847
848 template<support::endianness target_endianness, bool is64Bits>
849 error_code ELFObjectFile<target_endianness, is64Bits>
850                         ::isSectionText(DataRefImpl Sec,
851                                         bool &Result) const {
852   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
853   if (sec->sh_flags & ELF::SHF_EXECINSTR)
854     Result = true;
855   else
856     Result = false;
857   return object_error::success;
858 }
859
860 template<support::endianness target_endianness, bool is64Bits>
861 error_code ELFObjectFile<target_endianness, is64Bits>
862                         ::isSectionData(DataRefImpl Sec,
863                                         bool &Result) const {
864   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
865   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
866       && sec->sh_type == ELF::SHT_PROGBITS)
867     Result = true;
868   else
869     Result = false;
870   return object_error::success;
871 }
872
873 template<support::endianness target_endianness, bool is64Bits>
874 error_code ELFObjectFile<target_endianness, is64Bits>
875                         ::isSectionBSS(DataRefImpl Sec,
876                                        bool &Result) const {
877   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
878   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
879       && sec->sh_type == ELF::SHT_NOBITS)
880     Result = true;
881   else
882     Result = false;
883   return object_error::success;
884 }
885
886 template<support::endianness target_endianness, bool is64Bits>
887 error_code ELFObjectFile<target_endianness, is64Bits>
888                           ::sectionContainsSymbol(DataRefImpl Sec,
889                                                   DataRefImpl Symb,
890                                                   bool &Result) const {
891   // FIXME: Unimplemented.
892   Result = false;
893   return object_error::success;
894 }
895
896 template<support::endianness target_endianness, bool is64Bits>
897 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
898                                  ::getSectionRelBegin(DataRefImpl Sec) const {
899   DataRefImpl RelData;
900   memset(&RelData, 0, sizeof(RelData));
901   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
902   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
903   if (sec != 0 && ittr != SectionRelocMap.end()) {
904     RelData.w.a = getSection(ittr->second[0])->sh_info;
905     RelData.w.b = ittr->second[0];
906     RelData.w.c = 0;
907   }
908   return relocation_iterator(RelocationRef(RelData, this));
909 }
910
911 template<support::endianness target_endianness, bool is64Bits>
912 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
913                                  ::getSectionRelEnd(DataRefImpl Sec) const {
914   DataRefImpl RelData;
915   memset(&RelData, 0, sizeof(RelData));
916   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
917   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
918   if (sec != 0 && ittr != SectionRelocMap.end()) {
919     // Get the index of the last relocation section for this section.
920     std::size_t relocsecindex = ittr->second[ittr->second.size() - 1];
921     const Elf_Shdr *relocsec = getSection(relocsecindex);
922     RelData.w.a = relocsec->sh_info;
923     RelData.w.b = relocsecindex;
924     RelData.w.c = relocsec->sh_size / relocsec->sh_entsize;
925   }
926   return relocation_iterator(RelocationRef(RelData, this));
927 }
928
929 // Relocations
930 template<support::endianness target_endianness, bool is64Bits>
931 error_code ELFObjectFile<target_endianness, is64Bits>
932                         ::getRelocationNext(DataRefImpl Rel,
933                                             RelocationRef &Result) const {
934   ++Rel.w.c;
935   const Elf_Shdr *relocsec = getSection(Rel.w.b);
936   if (Rel.w.c >= (relocsec->sh_size / relocsec->sh_entsize)) {
937     // We have reached the end of the relocations for this section. See if there
938     // is another relocation section.
939     typename RelocMap_t::mapped_type relocseclist =
940       SectionRelocMap.lookup(getSection(Rel.w.a));
941
942     // Do a binary search for the current reloc section index (which must be
943     // present). Then get the next one.
944     typename RelocMap_t::mapped_type::const_iterator loc =
945       std::lower_bound(relocseclist.begin(), relocseclist.end(), Rel.w.b);
946     ++loc;
947
948     // If there is no next one, don't do anything. The ++Rel.w.c above sets Rel
949     // to the end iterator.
950     if (loc != relocseclist.end()) {
951       Rel.w.b = *loc;
952       Rel.w.a = 0;
953     }
954   }
955   Result = RelocationRef(Rel, this);
956   return object_error::success;
957 }
958
959 template<support::endianness target_endianness, bool is64Bits>
960 error_code ELFObjectFile<target_endianness, is64Bits>
961                         ::getRelocationSymbol(DataRefImpl Rel,
962                                               SymbolRef &Result) const {
963   uint32_t symbolIdx;
964   const Elf_Shdr *sec = getSection(Rel.w.b);
965   switch (sec->sh_type) {
966     default :
967       report_fatal_error("Invalid section type in Rel!");
968     case ELF::SHT_REL : {
969       symbolIdx = getRel(Rel)->getSymbol();
970       break;
971     }
972     case ELF::SHT_RELA : {
973       symbolIdx = getRela(Rel)->getSymbol();
974       break;
975     }
976   }
977   DataRefImpl SymbolData;
978   IndexMap_t::const_iterator it = SymbolTableSectionsIndexMap.find(sec->sh_link);
979   if (it == SymbolTableSectionsIndexMap.end())
980     report_fatal_error("Relocation symbol table not found!");
981   SymbolData.d.a = symbolIdx;
982   SymbolData.d.b = it->second;
983   Result = SymbolRef(SymbolData, this);
984   return object_error::success;
985 }
986
987 template<support::endianness target_endianness, bool is64Bits>
988 error_code ELFObjectFile<target_endianness, is64Bits>
989                         ::getRelocationAddress(DataRefImpl Rel,
990                                                uint64_t &Result) const {
991   uint64_t offset;
992   const Elf_Shdr *sec = getSection(Rel.w.b);
993   switch (sec->sh_type) {
994     default :
995       report_fatal_error("Invalid section type in Rel!");
996     case ELF::SHT_REL : {
997       offset = getRel(Rel)->r_offset;
998       break;
999     }
1000     case ELF::SHT_RELA : {
1001       offset = getRela(Rel)->r_offset;
1002       break;
1003     }
1004   }
1005
1006   Result = offset;
1007   return object_error::success;
1008 }
1009
1010 template<support::endianness target_endianness, bool is64Bits>
1011 error_code ELFObjectFile<target_endianness, is64Bits>
1012                         ::getRelocationOffset(DataRefImpl Rel,
1013                                               uint64_t &Result) const {
1014   uint64_t offset;
1015   const Elf_Shdr *sec = getSection(Rel.w.b);
1016   switch (sec->sh_type) {
1017     default :
1018       report_fatal_error("Invalid section type in Rel!");
1019     case ELF::SHT_REL : {
1020       offset = getRel(Rel)->r_offset;
1021       break;
1022     }
1023     case ELF::SHT_RELA : {
1024       offset = getRela(Rel)->r_offset;
1025       break;
1026     }
1027   }
1028
1029   Result = offset - sec->sh_addr;
1030   return object_error::success;
1031 }
1032
1033 template<support::endianness target_endianness, bool is64Bits>
1034 error_code ELFObjectFile<target_endianness, is64Bits>
1035                         ::getRelocationType(DataRefImpl Rel,
1036                                             uint64_t &Result) const {
1037   const Elf_Shdr *sec = getSection(Rel.w.b);
1038   switch (sec->sh_type) {
1039     default :
1040       report_fatal_error("Invalid section type in Rel!");
1041     case ELF::SHT_REL : {
1042       Result = getRel(Rel)->getType();
1043       break;
1044     }
1045     case ELF::SHT_RELA : {
1046       Result = getRela(Rel)->getType();
1047       break;
1048     }
1049   }
1050   return object_error::success;
1051 }
1052
1053 #define LLVM_ELF_SWITCH_RELOC_TYPE_NAME(enum) \
1054   case ELF::enum: res = #enum; break;
1055
1056 template<support::endianness target_endianness, bool is64Bits>
1057 error_code ELFObjectFile<target_endianness, is64Bits>
1058                         ::getRelocationTypeName(DataRefImpl Rel,
1059                                           SmallVectorImpl<char> &Result) const {
1060   const Elf_Shdr *sec = getSection(Rel.w.b);
1061   uint8_t type;
1062   StringRef res;
1063   switch (sec->sh_type) {
1064     default :
1065       return object_error::parse_failed;
1066     case ELF::SHT_REL : {
1067       type = getRel(Rel)->getType();
1068       break;
1069     }
1070     case ELF::SHT_RELA : {
1071       type = getRela(Rel)->getType();
1072       break;
1073     }
1074   }
1075   switch (Header->e_machine) {
1076   case ELF::EM_X86_64:
1077     switch (type) {
1078       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_NONE);
1079       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_64);
1080       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC32);
1081       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOT32);
1082       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PLT32);
1083       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_COPY);
1084       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GLOB_DAT);
1085       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_JUMP_SLOT);
1086       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_RELATIVE);
1087       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPCREL);
1088       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32);
1089       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32S);
1090       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_16);
1091       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC16);
1092       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_8);
1093       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC8);
1094       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPMOD64);
1095       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF64);
1096       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF64);
1097       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSGD);
1098       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSLD);
1099       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF32);
1100       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTTPOFF);
1101       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF32);
1102       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC64);
1103       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTOFF64);
1104       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32);
1105       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE32);
1106       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE64);
1107       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32_TLSDESC);
1108       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC_CALL);
1109       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC);
1110     default:
1111       res = "Unknown";
1112     }
1113     break;
1114   case ELF::EM_386:
1115     switch (type) {
1116       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_NONE);
1117       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32);
1118       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC32);
1119       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOT32);
1120       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PLT32);
1121       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_COPY);
1122       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GLOB_DAT);
1123       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_JUMP_SLOT);
1124       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_RELATIVE);
1125       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTOFF);
1126       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTPC);
1127       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32PLT);
1128       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF);
1129       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE);
1130       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTIE);
1131       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE);
1132       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD);
1133       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM);
1134       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_16);
1135       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC16);
1136       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_8);
1137       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC8);
1138       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_32);
1139       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_PUSH);
1140       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_CALL);
1141       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_POP);
1142       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_32);
1143       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_PUSH);
1144       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_CALL);
1145       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_POP);
1146       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDO_32);
1147       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE_32);
1148       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE_32);
1149       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPMOD32);
1150       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPOFF32);
1151       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF32);
1152       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTDESC);
1153       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC_CALL);
1154       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC);
1155       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_IRELATIVE);
1156     default:
1157       res = "Unknown";
1158     }
1159     break;
1160   default:
1161     res = "Unknown";
1162   }
1163   Result.append(res.begin(), res.end());
1164   return object_error::success;
1165 }
1166
1167 #undef LLVM_ELF_SWITCH_RELOC_TYPE_NAME
1168
1169 template<support::endianness target_endianness, bool is64Bits>
1170 error_code ELFObjectFile<target_endianness, is64Bits>
1171                         ::getRelocationAdditionalInfo(DataRefImpl Rel,
1172                                                       int64_t &Result) const {
1173   const Elf_Shdr *sec = getSection(Rel.w.b);
1174   switch (sec->sh_type) {
1175     default :
1176       report_fatal_error("Invalid section type in Rel!");
1177     case ELF::SHT_REL : {
1178       Result = 0;
1179       return object_error::success;
1180     }
1181     case ELF::SHT_RELA : {
1182       Result = getRela(Rel)->r_addend;
1183       return object_error::success;
1184     }
1185   }
1186 }
1187
1188 template<support::endianness target_endianness, bool is64Bits>
1189 error_code ELFObjectFile<target_endianness, is64Bits>
1190                         ::getRelocationValueString(DataRefImpl Rel,
1191                                           SmallVectorImpl<char> &Result) const {
1192   const Elf_Shdr *sec = getSection(Rel.w.b);
1193   uint8_t type;
1194   StringRef res;
1195   int64_t addend = 0;
1196   uint16_t symbol_index = 0;
1197   switch (sec->sh_type) {
1198     default :
1199       return object_error::parse_failed;
1200     case ELF::SHT_REL : {
1201       type = getRel(Rel)->getType();
1202       symbol_index = getRel(Rel)->getSymbol();
1203       // TODO: Read implicit addend from section data.
1204       break;
1205     }
1206     case ELF::SHT_RELA : {
1207       type = getRela(Rel)->getType();
1208       symbol_index = getRela(Rel)->getSymbol();
1209       addend = getRela(Rel)->r_addend;
1210       break;
1211     }
1212   }
1213   const Elf_Sym *symb = getEntry<Elf_Sym>(sec->sh_link, symbol_index);
1214   StringRef symname;
1215   if (error_code ec = getSymbolName(getSection(sec->sh_link), symb, symname))
1216     return ec;
1217   switch (Header->e_machine) {
1218   case ELF::EM_X86_64:
1219     switch (type) {
1220     case ELF::R_X86_64_32S:
1221       res = symname;
1222       break;
1223     case ELF::R_X86_64_PC32: {
1224         std::string fmtbuf;
1225         raw_string_ostream fmt(fmtbuf);
1226         fmt << symname << (addend < 0 ? "" : "+") << addend << "-P";
1227         fmt.flush();
1228         Result.append(fmtbuf.begin(), fmtbuf.end());
1229       }
1230       break;
1231     default:
1232       res = "Unknown";
1233     }
1234     break;
1235   default:
1236     res = "Unknown";
1237   }
1238   if (Result.empty())
1239     Result.append(res.begin(), res.end());
1240   return object_error::success;
1241 }
1242
1243 // Verify that the last byte in the string table in a null.
1244 template<support::endianness target_endianness, bool is64Bits>
1245 void ELFObjectFile<target_endianness, is64Bits>
1246                   ::VerifyStrTab(const Elf_Shdr *sh) const {
1247   const char *strtab = (const char*)base() + sh->sh_offset;
1248   if (strtab[sh->sh_size - 1] != 0)
1249     // FIXME: Proper error handling.
1250     report_fatal_error("String table must end with a null terminator!");
1251 }
1252
1253 template<support::endianness target_endianness, bool is64Bits>
1254 ELFObjectFile<target_endianness, is64Bits>::ELFObjectFile(MemoryBuffer *Object
1255                                                           , error_code &ec)
1256   : ObjectFile(Binary::isELF, Object, ec)
1257   , isDyldELFObject(false)
1258   , SectionHeaderTable(0)
1259   , dot_shstrtab_sec(0)
1260   , dot_strtab_sec(0)
1261   , dot_dynstr_sec(0)
1262   , dot_dynamic_sec(0) {
1263
1264   const uint64_t FileSize = Data->getBufferSize();
1265
1266   if (sizeof(Elf_Ehdr) > FileSize)
1267     // FIXME: Proper error handling.
1268     report_fatal_error("File too short!");
1269
1270   Header = reinterpret_cast<const Elf_Ehdr *>(base());
1271
1272   if (Header->e_shoff == 0)
1273     return;
1274
1275   const uint64_t SectionTableOffset = Header->e_shoff;
1276
1277   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
1278     // FIXME: Proper error handling.
1279     report_fatal_error("Section header table goes past end of file!");
1280
1281   // The getNumSections() call below depends on SectionHeaderTable being set.
1282   SectionHeaderTable =
1283     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
1284   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
1285
1286   if (SectionTableOffset + SectionTableSize > FileSize)
1287     // FIXME: Proper error handling.
1288     report_fatal_error("Section table goes past end of file!");
1289
1290   // To find the symbol tables we walk the section table to find SHT_SYMTAB.
1291   const Elf_Shdr* SymbolTableSectionHeaderIndex = 0;
1292   const Elf_Shdr* sh = SectionHeaderTable;
1293
1294   // Reserve SymbolTableSections[0] for .dynsym
1295   SymbolTableSections.push_back(NULL);
1296
1297   for (uint64_t i = 0, e = getNumSections(); i != e; ++i) {
1298     if (sh->sh_type == ELF::SHT_SYMTAB_SHNDX) {
1299       if (SymbolTableSectionHeaderIndex)
1300         // FIXME: Proper error handling.
1301         report_fatal_error("More than one .symtab_shndx!");
1302       SymbolTableSectionHeaderIndex = sh;
1303     }
1304     if (sh->sh_type == ELF::SHT_SYMTAB) {
1305       SymbolTableSectionsIndexMap[i] = SymbolTableSections.size();
1306       SymbolTableSections.push_back(sh);
1307     }
1308     if (sh->sh_type == ELF::SHT_DYNSYM) {
1309       if (SymbolTableSections[0] != NULL)
1310         // FIXME: Proper error handling.
1311         report_fatal_error("More than one .dynsym!");
1312       SymbolTableSectionsIndexMap[i] = 0;
1313       SymbolTableSections[0] = sh;
1314     }
1315     if (sh->sh_type == ELF::SHT_REL || sh->sh_type == ELF::SHT_RELA) {
1316       SectionRelocMap[getSection(sh->sh_info)].push_back(i);
1317     }
1318     if (sh->sh_type == ELF::SHT_DYNAMIC) {
1319       if (dot_dynamic_sec != NULL)
1320         // FIXME: Proper error handling.
1321         report_fatal_error("More than one .dynamic!");
1322       dot_dynamic_sec = sh;
1323     }
1324     ++sh;
1325   }
1326
1327   // Sort section relocation lists by index.
1328   for (typename RelocMap_t::iterator i = SectionRelocMap.begin(),
1329                                      e = SectionRelocMap.end(); i != e; ++i) {
1330     std::sort(i->second.begin(), i->second.end());
1331   }
1332
1333   // Get string table sections.
1334   dot_shstrtab_sec = getSection(getStringTableIndex());
1335   if (dot_shstrtab_sec) {
1336     // Verify that the last byte in the string table in a null.
1337     VerifyStrTab(dot_shstrtab_sec);
1338   }
1339
1340   // Merge this into the above loop.
1341   for (const char *i = reinterpret_cast<const char *>(SectionHeaderTable),
1342                   *e = i + getNumSections() * Header->e_shentsize;
1343                    i != e; i += Header->e_shentsize) {
1344     const Elf_Shdr *sh = reinterpret_cast<const Elf_Shdr*>(i);
1345     if (sh->sh_type == ELF::SHT_STRTAB) {
1346       StringRef SectionName(getString(dot_shstrtab_sec, sh->sh_name));
1347       if (SectionName == ".strtab") {
1348         if (dot_strtab_sec != 0)
1349           // FIXME: Proper error handling.
1350           report_fatal_error("Already found section named .strtab!");
1351         dot_strtab_sec = sh;
1352         VerifyStrTab(dot_strtab_sec);
1353       } else if (SectionName == ".dynstr") {
1354         if (dot_dynstr_sec != 0)
1355           // FIXME: Proper error handling.
1356           report_fatal_error("Already found section named .dynstr!");
1357         dot_dynstr_sec = sh;
1358         VerifyStrTab(dot_dynstr_sec);
1359       }
1360     }
1361   }
1362
1363   // Build symbol name side-mapping if there is one.
1364   if (SymbolTableSectionHeaderIndex) {
1365     const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
1366                                       SymbolTableSectionHeaderIndex->sh_offset);
1367     error_code ec;
1368     for (symbol_iterator si = begin_symbols(),
1369                          se = end_symbols(); si != se; si.increment(ec)) {
1370       if (ec)
1371         report_fatal_error("Fewer extended symbol table entries than symbols!");
1372       if (*ShndxTable != ELF::SHN_UNDEF)
1373         ExtendedSymbolTable[getSymbol(si->getRawDataRefImpl())] = *ShndxTable;
1374       ++ShndxTable;
1375     }
1376   }
1377 }
1378
1379 template<support::endianness target_endianness, bool is64Bits>
1380 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1381                              ::begin_symbols() const {
1382   DataRefImpl SymbolData;
1383   memset(&SymbolData, 0, sizeof(SymbolData));
1384   if (SymbolTableSections.size() <= 1) {
1385     SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1386     SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1387   } else {
1388     SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
1389     SymbolData.d.b = 1; // The 0th table is .dynsym
1390   }
1391   return symbol_iterator(SymbolRef(SymbolData, this));
1392 }
1393
1394 template<support::endianness target_endianness, bool is64Bits>
1395 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1396                              ::end_symbols() const {
1397   DataRefImpl SymbolData;
1398   memset(&SymbolData, 0, sizeof(SymbolData));
1399   SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1400   SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1401   return symbol_iterator(SymbolRef(SymbolData, this));
1402 }
1403
1404 template<support::endianness target_endianness, bool is64Bits>
1405 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1406                              ::begin_dynamic_symbols() const {
1407   DataRefImpl SymbolData;
1408   memset(&SymbolData, 0, sizeof(SymbolData));
1409   if (SymbolTableSections[0] == NULL) {
1410     SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1411     SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1412   } else {
1413     SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
1414     SymbolData.d.b = 0; // The 0th table is .dynsym
1415   }
1416   return symbol_iterator(SymbolRef(SymbolData, this));
1417 }
1418
1419 template<support::endianness target_endianness, bool is64Bits>
1420 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1421                              ::end_dynamic_symbols() const {
1422   DataRefImpl SymbolData;
1423   memset(&SymbolData, 0, sizeof(SymbolData));
1424   SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1425   SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1426   return symbol_iterator(SymbolRef(SymbolData, this));
1427 }
1428
1429 template<support::endianness target_endianness, bool is64Bits>
1430 section_iterator ELFObjectFile<target_endianness, is64Bits>
1431                               ::begin_sections() const {
1432   DataRefImpl ret;
1433   memset(&ret, 0, sizeof(DataRefImpl));
1434   ret.p = reinterpret_cast<intptr_t>(base() + Header->e_shoff);
1435   return section_iterator(SectionRef(ret, this));
1436 }
1437
1438 template<support::endianness target_endianness, bool is64Bits>
1439 section_iterator ELFObjectFile<target_endianness, is64Bits>
1440                               ::end_sections() const {
1441   DataRefImpl ret;
1442   memset(&ret, 0, sizeof(DataRefImpl));
1443   ret.p = reinterpret_cast<intptr_t>(base()
1444                                      + Header->e_shoff
1445                                      + (Header->e_shentsize*getNumSections()));
1446   return section_iterator(SectionRef(ret, this));
1447 }
1448
1449 template<support::endianness target_endianness, bool is64Bits>
1450 typename ELFObjectFile<target_endianness, is64Bits>::dyn_iterator
1451 ELFObjectFile<target_endianness, is64Bits>::begin_dynamic_table() const {
1452   DataRefImpl DynData;
1453   memset(&DynData, 0, sizeof(DynData));
1454   if (dot_dynamic_sec == NULL || dot_dynamic_sec->sh_size == 0) {
1455     DynData.d.a = std::numeric_limits<uint32_t>::max();
1456   } else {
1457     DynData.d.a = 0;
1458   }
1459   return dyn_iterator(DynRef(DynData, this));
1460 }
1461
1462 template<support::endianness target_endianness, bool is64Bits>
1463 typename ELFObjectFile<target_endianness, is64Bits>::dyn_iterator
1464 ELFObjectFile<target_endianness, is64Bits>
1465                           ::end_dynamic_table() const {
1466   DataRefImpl DynData;
1467   memset(&DynData, 0, sizeof(DynData));
1468   DynData.d.a = std::numeric_limits<uint32_t>::max();
1469   return dyn_iterator(DynRef(DynData, this));
1470 }
1471
1472 template<support::endianness target_endianness, bool is64Bits>
1473 error_code ELFObjectFile<target_endianness, is64Bits>
1474                         ::getDynNext(DataRefImpl DynData,
1475                                      DynRef &Result) const {
1476   ++DynData.d.a;
1477
1478   // Check to see if we are at the end of .dynamic
1479   if (DynData.d.a >= dot_dynamic_sec->getEntityCount()) {
1480     // We are at the end. Return the terminator.
1481     DynData.d.a = std::numeric_limits<uint32_t>::max();
1482   }
1483
1484   Result = DynRef(DynData, this);
1485   return object_error::success;
1486 }
1487
1488 template<support::endianness target_endianness, bool is64Bits>
1489 library_iterator ELFObjectFile<target_endianness, is64Bits>
1490                              ::begin_libraries_needed() const {
1491   // Find the first DT_NEEDED entry
1492   dyn_iterator i = begin_dynamic_table();
1493   dyn_iterator e = end_dynamic_table();
1494   error_code ec;
1495   while (i != e) {
1496     if (i->getTag() == ELF::DT_NEEDED)
1497       break;
1498     i.increment(ec);
1499     if (ec)
1500       report_fatal_error("dynamic table iteration failed");
1501   }
1502   // Use the same DataRefImpl format as DynRef.
1503   return library_iterator(LibraryRef(i->getRawDataRefImpl(), this));
1504 }
1505
1506 template<support::endianness target_endianness, bool is64Bits>
1507 error_code ELFObjectFile<target_endianness, is64Bits>
1508                         ::getLibraryNext(DataRefImpl Data,
1509                                          LibraryRef &Result) const {
1510   // Use the same DataRefImpl format as DynRef.
1511   dyn_iterator i = dyn_iterator(DynRef(Data, this));
1512   dyn_iterator e = end_dynamic_table();
1513
1514   // Skip the current dynamic table entry.
1515   error_code ec;
1516   if (i != e) {
1517     i.increment(ec);
1518     // TODO: proper error handling
1519     if (ec)
1520       report_fatal_error("dynamic table iteration failed");
1521   }
1522
1523   // Find the next DT_NEEDED entry.
1524   while (i != e) {
1525     if (i->getTag() == ELF::DT_NEEDED)
1526       break;
1527     i.increment(ec);
1528     if (ec)
1529       report_fatal_error("dynamic table iteration failed");
1530   }
1531   Result = LibraryRef(i->getRawDataRefImpl(), this);
1532   return object_error::success;
1533 }
1534
1535 template<support::endianness target_endianness, bool is64Bits>
1536 error_code ELFObjectFile<target_endianness, is64Bits>
1537          ::getLibraryPath(DataRefImpl Data, StringRef &Res) const {
1538   dyn_iterator i = dyn_iterator(DynRef(Data, this));
1539   if (i == end_dynamic_table())
1540     report_fatal_error("getLibraryPath() called on iterator end");
1541
1542   if (i->getTag() != ELF::DT_NEEDED)
1543     report_fatal_error("Invalid library_iterator");
1544
1545   // This uses .dynstr to lookup the name of the DT_NEEDED entry.
1546   // THis works as long as DT_STRTAB == .dynstr. This is true most of
1547   // the time, but the specification allows exceptions.
1548   // TODO: This should really use DT_STRTAB instead. Doing this requires
1549   // reading the program headers.
1550   if (dot_dynstr_sec == NULL)
1551     report_fatal_error("Dynamic string table is missing");
1552   Res = getString(dot_dynstr_sec, i->getVal());
1553   return object_error::success;
1554 }
1555
1556 template<support::endianness target_endianness, bool is64Bits>
1557 library_iterator ELFObjectFile<target_endianness, is64Bits>
1558                              ::end_libraries_needed() const {
1559   dyn_iterator e = end_dynamic_table();
1560   // Use the same DataRefImpl format as DynRef.
1561   return library_iterator(LibraryRef(e->getRawDataRefImpl(), this));
1562 }
1563
1564 template<support::endianness target_endianness, bool is64Bits>
1565 uint8_t ELFObjectFile<target_endianness, is64Bits>::getBytesInAddress() const {
1566   return is64Bits ? 8 : 4;
1567 }
1568
1569 template<support::endianness target_endianness, bool is64Bits>
1570 StringRef ELFObjectFile<target_endianness, is64Bits>
1571                        ::getFileFormatName() const {
1572   switch(Header->e_ident[ELF::EI_CLASS]) {
1573   case ELF::ELFCLASS32:
1574     switch(Header->e_machine) {
1575     case ELF::EM_386:
1576       return "ELF32-i386";
1577     case ELF::EM_X86_64:
1578       return "ELF32-x86-64";
1579     case ELF::EM_ARM:
1580       return "ELF32-arm";
1581     default:
1582       return "ELF32-unknown";
1583     }
1584   case ELF::ELFCLASS64:
1585     switch(Header->e_machine) {
1586     case ELF::EM_386:
1587       return "ELF64-i386";
1588     case ELF::EM_X86_64:
1589       return "ELF64-x86-64";
1590     default:
1591       return "ELF64-unknown";
1592     }
1593   default:
1594     // FIXME: Proper error handling.
1595     report_fatal_error("Invalid ELFCLASS!");
1596   }
1597 }
1598
1599 template<support::endianness target_endianness, bool is64Bits>
1600 unsigned ELFObjectFile<target_endianness, is64Bits>::getArch() const {
1601   switch(Header->e_machine) {
1602   case ELF::EM_386:
1603     return Triple::x86;
1604   case ELF::EM_X86_64:
1605     return Triple::x86_64;
1606   case ELF::EM_ARM:
1607     return Triple::arm;
1608   default:
1609     return Triple::UnknownArch;
1610   }
1611 }
1612
1613 template<support::endianness target_endianness, bool is64Bits>
1614 uint64_t ELFObjectFile<target_endianness, is64Bits>::getNumSections() const {
1615   assert(Header && "Header not initialized!");
1616   if (Header->e_shnum == ELF::SHN_UNDEF) {
1617     assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
1618     return SectionHeaderTable->sh_size;
1619   }
1620   return Header->e_shnum;
1621 }
1622
1623 template<support::endianness target_endianness, bool is64Bits>
1624 uint64_t
1625 ELFObjectFile<target_endianness, is64Bits>::getStringTableIndex() const {
1626   if (Header->e_shnum == ELF::SHN_UNDEF) {
1627     if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
1628       return SectionHeaderTable->sh_link;
1629     if (Header->e_shstrndx >= getNumSections())
1630       return 0;
1631   }
1632   return Header->e_shstrndx;
1633 }
1634
1635
1636 template<support::endianness target_endianness, bool is64Bits>
1637 template<typename T>
1638 inline const T *
1639 ELFObjectFile<target_endianness, is64Bits>::getEntry(uint16_t Section,
1640                                                      uint32_t Entry) const {
1641   return getEntry<T>(getSection(Section), Entry);
1642 }
1643
1644 template<support::endianness target_endianness, bool is64Bits>
1645 template<typename T>
1646 inline const T *
1647 ELFObjectFile<target_endianness, is64Bits>::getEntry(const Elf_Shdr * Section,
1648                                                      uint32_t Entry) const {
1649   return reinterpret_cast<const T *>(
1650            base()
1651            + Section->sh_offset
1652            + (Entry * Section->sh_entsize));
1653 }
1654
1655 template<support::endianness target_endianness, bool is64Bits>
1656 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
1657 ELFObjectFile<target_endianness, is64Bits>::getSymbol(DataRefImpl Symb) const {
1658   return getEntry<Elf_Sym>(SymbolTableSections[Symb.d.b], Symb.d.a);
1659 }
1660
1661 template<support::endianness target_endianness, bool is64Bits>
1662 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Dyn *
1663 ELFObjectFile<target_endianness, is64Bits>::getDyn(DataRefImpl DynData) const {
1664   return getEntry<Elf_Dyn>(dot_dynamic_sec, DynData.d.a);
1665 }
1666
1667 template<support::endianness target_endianness, bool is64Bits>
1668 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rel *
1669 ELFObjectFile<target_endianness, is64Bits>::getRel(DataRefImpl Rel) const {
1670   return getEntry<Elf_Rel>(Rel.w.b, Rel.w.c);
1671 }
1672
1673 template<support::endianness target_endianness, bool is64Bits>
1674 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rela *
1675 ELFObjectFile<target_endianness, is64Bits>::getRela(DataRefImpl Rela) const {
1676   return getEntry<Elf_Rela>(Rela.w.b, Rela.w.c);
1677 }
1678
1679 template<support::endianness target_endianness, bool is64Bits>
1680 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
1681 ELFObjectFile<target_endianness, is64Bits>::getSection(DataRefImpl Symb) const {
1682   const Elf_Shdr *sec = getSection(Symb.d.b);
1683   if (sec->sh_type != ELF::SHT_SYMTAB || sec->sh_type != ELF::SHT_DYNSYM)
1684     // FIXME: Proper error handling.
1685     report_fatal_error("Invalid symbol table section!");
1686   return sec;
1687 }
1688
1689 template<support::endianness target_endianness, bool is64Bits>
1690 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
1691 ELFObjectFile<target_endianness, is64Bits>::getSection(uint32_t index) const {
1692   if (index == 0)
1693     return 0;
1694   if (!SectionHeaderTable || index >= getNumSections())
1695     // FIXME: Proper error handling.
1696     report_fatal_error("Invalid section index!");
1697
1698   return reinterpret_cast<const Elf_Shdr *>(
1699          reinterpret_cast<const char *>(SectionHeaderTable)
1700          + (index * Header->e_shentsize));
1701 }
1702
1703 template<support::endianness target_endianness, bool is64Bits>
1704 const char *ELFObjectFile<target_endianness, is64Bits>
1705                          ::getString(uint32_t section,
1706                                      ELF::Elf32_Word offset) const {
1707   return getString(getSection(section), offset);
1708 }
1709
1710 template<support::endianness target_endianness, bool is64Bits>
1711 const char *ELFObjectFile<target_endianness, is64Bits>
1712                          ::getString(const Elf_Shdr *section,
1713                                      ELF::Elf32_Word offset) const {
1714   assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
1715   if (offset >= section->sh_size)
1716     // FIXME: Proper error handling.
1717     report_fatal_error("Symbol name offset outside of string table!");
1718   return (const char *)base() + section->sh_offset + offset;
1719 }
1720
1721 template<support::endianness target_endianness, bool is64Bits>
1722 error_code ELFObjectFile<target_endianness, is64Bits>
1723                         ::getSymbolName(const Elf_Shdr *section,
1724                                         const Elf_Sym *symb,
1725                                         StringRef &Result) const {
1726   if (symb->st_name == 0) {
1727     const Elf_Shdr *section = getSection(symb);
1728     if (!section)
1729       Result = "";
1730     else
1731       Result = getString(dot_shstrtab_sec, section->sh_name);
1732     return object_error::success;
1733   }
1734
1735   if (section == SymbolTableSections[0]) {
1736     // Symbol is in .dynsym, use .dynstr string table
1737     Result = getString(dot_dynstr_sec, symb->st_name);
1738   } else {
1739     // Use the default symbol table name section.
1740     Result = getString(dot_strtab_sec, symb->st_name);
1741   }
1742   return object_error::success;
1743 }
1744
1745 template<support::endianness target_endianness, bool is64Bits>
1746 inline DynRefImpl<target_endianness, is64Bits>
1747                  ::DynRefImpl(DataRefImpl DynP, const OwningType *Owner)
1748   : DynPimpl(DynP)
1749   , OwningObject(Owner) {}
1750
1751 template<support::endianness target_endianness, bool is64Bits>
1752 inline bool DynRefImpl<target_endianness, is64Bits>
1753                       ::operator==(const DynRefImpl &Other) const {
1754   return DynPimpl == Other.DynPimpl;
1755 }
1756
1757 template<support::endianness target_endianness, bool is64Bits>
1758 inline bool DynRefImpl<target_endianness, is64Bits>
1759                       ::operator <(const DynRefImpl &Other) const {
1760   return DynPimpl < Other.DynPimpl;
1761 }
1762
1763 template<support::endianness target_endianness, bool is64Bits>
1764 inline error_code DynRefImpl<target_endianness, is64Bits>
1765                             ::getNext(DynRefImpl &Result) const {
1766   return OwningObject->getDynNext(DynPimpl, Result);
1767 }
1768
1769 template<support::endianness target_endianness, bool is64Bits>
1770 inline int64_t DynRefImpl<target_endianness, is64Bits>
1771                             ::getTag() const {
1772   return OwningObject->getDyn(DynPimpl)->d_tag;
1773 }
1774
1775 template<support::endianness target_endianness, bool is64Bits>
1776 inline uint64_t DynRefImpl<target_endianness, is64Bits>
1777                             ::getVal() const {
1778   return OwningObject->getDyn(DynPimpl)->d_un.d_val;
1779 }
1780
1781 template<support::endianness target_endianness, bool is64Bits>
1782 inline uint64_t DynRefImpl<target_endianness, is64Bits>
1783                             ::getPtr() const {
1784   return OwningObject->getDyn(DynPimpl)->d_un.d_ptr;
1785 }
1786
1787 template<support::endianness target_endianness, bool is64Bits>
1788 inline DataRefImpl DynRefImpl<target_endianness, is64Bits>
1789                              ::getRawDataRefImpl() const {
1790   return DynPimpl;
1791 }
1792
1793 }
1794 }
1795
1796 #endif