[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   // Pointer to SONAME entry in dynamic string table
373   // This is set the first time getLoadName is called.
374   mutable const char *dt_soname;
375
376   /// @brief Map sections to an array of relocation sections that reference
377   ///        them sorted by section index.
378   RelocMap_t SectionRelocMap;
379
380   /// @brief Get the relocation section that contains \a Rel.
381   const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
382     return getSection(Rel.w.b);
383   }
384
385   bool            isRelocationHasAddend(DataRefImpl Rel) const;
386   template<typename T>
387   const T        *getEntry(uint16_t Section, uint32_t Entry) const;
388   template<typename T>
389   const T        *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
390   const Elf_Shdr *getSection(DataRefImpl index) const;
391   const Elf_Shdr *getSection(uint32_t index) const;
392   const Elf_Rel  *getRel(DataRefImpl Rel) const;
393   const Elf_Rela *getRela(DataRefImpl Rela) const;
394   const char     *getString(uint32_t section, uint32_t offset) const;
395   const char     *getString(const Elf_Shdr *section, uint32_t offset) const;
396   error_code      getSymbolName(const Elf_Shdr *section,
397                                 const Elf_Sym *Symb,
398                                 StringRef &Res) const;
399   void VerifyStrTab(const Elf_Shdr *sh) const;
400
401 protected:
402   const Elf_Sym  *getSymbol(DataRefImpl Symb) const; // FIXME: Should be private?
403   void            validateSymbol(DataRefImpl Symb) const;
404
405 public:
406   const Elf_Dyn  *getDyn(DataRefImpl DynData) const;
407
408 protected:
409   virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
410   virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
411   virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) const;
412   virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const;
413   virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
414   virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const;
415   virtual error_code getSymbolFlags(DataRefImpl Symb, uint32_t &Res) const;
416   virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res) const;
417   virtual error_code getSymbolSection(DataRefImpl Symb,
418                                       section_iterator &Res) const;
419
420   friend class DynRefImpl<target_endianness, is64Bits>;
421   virtual error_code getDynNext(DataRefImpl DynData, DynRef &Result) const;
422
423   virtual error_code getLibraryNext(DataRefImpl Data, LibraryRef &Result) const;
424   virtual error_code getLibraryPath(DataRefImpl Data, StringRef &Res) const;
425
426   virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
427   virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
428   virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
429   virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
430   virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
431   virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const;
432   virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
433   virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
434   virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
435   virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
436                                            bool &Result) const;
437   virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
438   virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;
439
440   virtual error_code getRelocationNext(DataRefImpl Rel,
441                                        RelocationRef &Res) const;
442   virtual error_code getRelocationAddress(DataRefImpl Rel,
443                                           uint64_t &Res) const;
444   virtual error_code getRelocationOffset(DataRefImpl Rel,
445                                          uint64_t &Res) const;
446   virtual error_code getRelocationSymbol(DataRefImpl Rel,
447                                          SymbolRef &Res) const;
448   virtual error_code getRelocationType(DataRefImpl Rel,
449                                        uint64_t &Res) const;
450   virtual error_code getRelocationTypeName(DataRefImpl Rel,
451                                            SmallVectorImpl<char> &Result) const;
452   virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
453                                                  int64_t &Res) const;
454   virtual error_code getRelocationValueString(DataRefImpl Rel,
455                                            SmallVectorImpl<char> &Result) const;
456
457 public:
458   ELFObjectFile(MemoryBuffer *Object, error_code &ec);
459   virtual symbol_iterator begin_symbols() const;
460   virtual symbol_iterator end_symbols() const;
461
462   virtual symbol_iterator begin_dynamic_symbols() const;
463   virtual symbol_iterator end_dynamic_symbols() const;
464
465   virtual section_iterator begin_sections() const;
466   virtual section_iterator end_sections() const;
467
468   virtual library_iterator begin_libraries_needed() const;
469   virtual library_iterator end_libraries_needed() const;
470
471   virtual dyn_iterator begin_dynamic_table() const;
472   virtual dyn_iterator end_dynamic_table() const;
473
474   virtual uint8_t getBytesInAddress() const;
475   virtual StringRef getFileFormatName() const;
476   virtual unsigned getArch() const;
477   virtual StringRef getLoadName() const;
478
479   uint64_t getNumSections() const;
480   uint64_t getStringTableIndex() const;
481   ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
482   const Elf_Shdr *getSection(const Elf_Sym *symb) const;
483
484   // Methods for type inquiry through isa, cast, and dyn_cast
485   bool isDyldType() const { return isDyldELFObject; }
486   static inline bool classof(const Binary *v) {
487     return v->getType() == getELFType(target_endianness == support::little,
488                                       is64Bits);
489   }
490   static inline bool classof(const ELFObjectFile *v) { return true; }
491 };
492
493 template<support::endianness target_endianness, bool is64Bits>
494 void ELFObjectFile<target_endianness, is64Bits>
495                   ::validateSymbol(DataRefImpl Symb) const {
496   const Elf_Sym  *symb = getSymbol(Symb);
497   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
498   // FIXME: We really need to do proper error handling in the case of an invalid
499   //        input file. Because we don't use exceptions, I think we'll just pass
500   //        an error object around.
501   if (!(  symb
502         && SymbolTableSection
503         && symb >= (const Elf_Sym*)(base()
504                    + SymbolTableSection->sh_offset)
505         && symb <  (const Elf_Sym*)(base()
506                    + SymbolTableSection->sh_offset
507                    + SymbolTableSection->sh_size)))
508     // FIXME: Proper error handling.
509     report_fatal_error("Symb must point to a valid symbol!");
510 }
511
512 template<support::endianness target_endianness, bool is64Bits>
513 error_code ELFObjectFile<target_endianness, is64Bits>
514                         ::getSymbolNext(DataRefImpl Symb,
515                                         SymbolRef &Result) const {
516   validateSymbol(Symb);
517   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
518
519   ++Symb.d.a;
520   // Check to see if we are at the end of this symbol table.
521   if (Symb.d.a >= SymbolTableSection->getEntityCount()) {
522     // We are at the end. If there are other symbol tables, jump to them.
523     // If the symbol table is .dynsym, we are iterating dynamic symbols,
524     // and there is only one table of these.
525     if (Symb.d.b != 0) {
526       ++Symb.d.b;
527       Symb.d.a = 1; // The 0th symbol in ELF is fake.
528     }
529     // Otherwise return the terminator.
530     if (Symb.d.b == 0 || Symb.d.b >= SymbolTableSections.size()) {
531       Symb.d.a = std::numeric_limits<uint32_t>::max();
532       Symb.d.b = std::numeric_limits<uint32_t>::max();
533     }
534   }
535
536   Result = SymbolRef(Symb, this);
537   return object_error::success;
538 }
539
540 template<support::endianness target_endianness, bool is64Bits>
541 error_code ELFObjectFile<target_endianness, is64Bits>
542                         ::getSymbolName(DataRefImpl Symb,
543                                         StringRef &Result) const {
544   validateSymbol(Symb);
545   const Elf_Sym *symb = getSymbol(Symb);
546   return getSymbolName(SymbolTableSections[Symb.d.b], symb, Result);
547 }
548
549 template<support::endianness target_endianness, bool is64Bits>
550 ELF::Elf64_Word ELFObjectFile<target_endianness, is64Bits>
551                       ::getSymbolTableIndex(const Elf_Sym *symb) const {
552   if (symb->st_shndx == ELF::SHN_XINDEX)
553     return ExtendedSymbolTable.lookup(symb);
554   return symb->st_shndx;
555 }
556
557 template<support::endianness target_endianness, bool is64Bits>
558 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
559 ELFObjectFile<target_endianness, is64Bits>
560                              ::getSection(const Elf_Sym *symb) const {
561   if (symb->st_shndx == ELF::SHN_XINDEX)
562     return getSection(ExtendedSymbolTable.lookup(symb));
563   if (symb->st_shndx >= ELF::SHN_LORESERVE)
564     return 0;
565   return getSection(symb->st_shndx);
566 }
567
568 template<support::endianness target_endianness, bool is64Bits>
569 error_code ELFObjectFile<target_endianness, is64Bits>
570                         ::getSymbolFileOffset(DataRefImpl Symb,
571                                           uint64_t &Result) const {
572   validateSymbol(Symb);
573   const Elf_Sym  *symb = getSymbol(Symb);
574   const Elf_Shdr *Section;
575   switch (getSymbolTableIndex(symb)) {
576   case ELF::SHN_COMMON:
577    // Unintialized symbols have no offset in the object file
578   case ELF::SHN_UNDEF:
579     Result = UnknownAddressOrSize;
580     return object_error::success;
581   case ELF::SHN_ABS:
582     Result = symb->st_value;
583     return object_error::success;
584   default: Section = getSection(symb);
585   }
586
587   switch (symb->getType()) {
588   case ELF::STT_SECTION:
589     Result = Section ? Section->sh_addr : UnknownAddressOrSize;
590     return object_error::success;
591   case ELF::STT_FUNC:
592   case ELF::STT_OBJECT:
593   case ELF::STT_NOTYPE:
594     Result = symb->st_value +
595              (Section ? Section->sh_offset : 0);
596     return object_error::success;
597   default:
598     Result = UnknownAddressOrSize;
599     return object_error::success;
600   }
601 }
602
603 template<support::endianness target_endianness, bool is64Bits>
604 error_code ELFObjectFile<target_endianness, is64Bits>
605                         ::getSymbolAddress(DataRefImpl Symb,
606                                            uint64_t &Result) const {
607   validateSymbol(Symb);
608   const Elf_Sym  *symb = getSymbol(Symb);
609   const Elf_Shdr *Section;
610   switch (getSymbolTableIndex(symb)) {
611   case ELF::SHN_COMMON:
612   case ELF::SHN_UNDEF:
613     Result = UnknownAddressOrSize;
614     return object_error::success;
615   case ELF::SHN_ABS:
616     Result = symb->st_value;
617     return object_error::success;
618   default: Section = getSection(symb);
619   }
620
621   switch (symb->getType()) {
622   case ELF::STT_SECTION:
623     Result = Section ? Section->sh_addr : UnknownAddressOrSize;
624     return object_error::success;
625   case ELF::STT_FUNC:
626   case ELF::STT_OBJECT:
627   case ELF::STT_NOTYPE:
628     Result = symb->st_value + (Section ? Section->sh_addr : 0);
629     return object_error::success;
630   default:
631     Result = UnknownAddressOrSize;
632     return object_error::success;
633   }
634 }
635
636 template<support::endianness target_endianness, bool is64Bits>
637 error_code ELFObjectFile<target_endianness, is64Bits>
638                         ::getSymbolSize(DataRefImpl Symb,
639                                         uint64_t &Result) const {
640   validateSymbol(Symb);
641   const Elf_Sym  *symb = getSymbol(Symb);
642   if (symb->st_size == 0)
643     Result = UnknownAddressOrSize;
644   Result = symb->st_size;
645   return object_error::success;
646 }
647
648 template<support::endianness target_endianness, bool is64Bits>
649 error_code ELFObjectFile<target_endianness, is64Bits>
650                         ::getSymbolNMTypeChar(DataRefImpl Symb,
651                                               char &Result) const {
652   validateSymbol(Symb);
653   const Elf_Sym  *symb = getSymbol(Symb);
654   const Elf_Shdr *Section = getSection(symb);
655
656   char ret = '?';
657
658   if (Section) {
659     switch (Section->sh_type) {
660     case ELF::SHT_PROGBITS:
661     case ELF::SHT_DYNAMIC:
662       switch (Section->sh_flags) {
663       case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
664         ret = 't'; break;
665       case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
666         ret = 'd'; break;
667       case ELF::SHF_ALLOC:
668       case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
669       case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
670         ret = 'r'; break;
671       }
672       break;
673     case ELF::SHT_NOBITS: ret = 'b';
674     }
675   }
676
677   switch (getSymbolTableIndex(symb)) {
678   case ELF::SHN_UNDEF:
679     if (ret == '?')
680       ret = 'U';
681     break;
682   case ELF::SHN_ABS: ret = 'a'; break;
683   case ELF::SHN_COMMON: ret = 'c'; break;
684   }
685
686   switch (symb->getBinding()) {
687   case ELF::STB_GLOBAL: ret = ::toupper(ret); break;
688   case ELF::STB_WEAK:
689     if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF)
690       ret = 'w';
691     else
692       if (symb->getType() == ELF::STT_OBJECT)
693         ret = 'V';
694       else
695         ret = 'W';
696   }
697
698   if (ret == '?' && symb->getType() == ELF::STT_SECTION) {
699     StringRef name;
700     if (error_code ec = getSymbolName(Symb, name))
701       return ec;
702     Result = StringSwitch<char>(name)
703       .StartsWith(".debug", 'N')
704       .StartsWith(".note", 'n')
705       .Default('?');
706     return object_error::success;
707   }
708
709   Result = ret;
710   return object_error::success;
711 }
712
713 template<support::endianness target_endianness, bool is64Bits>
714 error_code ELFObjectFile<target_endianness, is64Bits>
715                         ::getSymbolType(DataRefImpl Symb,
716                                         SymbolRef::Type &Result) const {
717   validateSymbol(Symb);
718   const Elf_Sym  *symb = getSymbol(Symb);
719
720   switch (symb->getType()) {
721   case ELF::STT_NOTYPE:
722     Result = SymbolRef::ST_Unknown;
723     break;
724   case ELF::STT_SECTION:
725     Result = SymbolRef::ST_Debug;
726     break;
727   case ELF::STT_FILE:
728     Result = SymbolRef::ST_File;
729     break;
730   case ELF::STT_FUNC:
731     Result = SymbolRef::ST_Function;
732     break;
733   case ELF::STT_OBJECT:
734   case ELF::STT_COMMON:
735   case ELF::STT_TLS:
736     Result = SymbolRef::ST_Data;
737     break;
738   default:
739     Result = SymbolRef::ST_Other;
740     break;
741   }
742   return object_error::success;
743 }
744
745 template<support::endianness target_endianness, bool is64Bits>
746 error_code ELFObjectFile<target_endianness, is64Bits>
747                         ::getSymbolFlags(DataRefImpl Symb,
748                                          uint32_t &Result) const {
749   validateSymbol(Symb);
750   const Elf_Sym  *symb = getSymbol(Symb);
751
752   Result = SymbolRef::SF_None;
753
754   if (symb->getBinding() != ELF::STB_LOCAL)
755     Result |= SymbolRef::SF_Global;
756
757   if (symb->getBinding() == ELF::STB_WEAK)
758     Result |= SymbolRef::SF_Weak;
759
760   if (symb->st_shndx == ELF::SHN_ABS)
761     Result |= SymbolRef::SF_Absolute;
762
763   if (symb->getType() == ELF::STT_FILE ||
764       symb->getType() == ELF::STT_SECTION)
765     Result |= SymbolRef::SF_FormatSpecific;
766
767   if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF)
768     Result |= SymbolRef::SF_Undefined;
769
770   if (symb->getType() == ELF::STT_COMMON ||
771       getSymbolTableIndex(symb) == ELF::SHN_COMMON)
772     Result |= SymbolRef::SF_Common;
773
774   if (symb->getType() == ELF::STT_TLS)
775     Result |= SymbolRef::SF_ThreadLocal;
776
777   return object_error::success;
778 }
779
780 template<support::endianness target_endianness, bool is64Bits>
781 error_code ELFObjectFile<target_endianness, is64Bits>
782                         ::getSymbolSection(DataRefImpl Symb,
783                                            section_iterator &Res) const {
784   validateSymbol(Symb);
785   const Elf_Sym  *symb = getSymbol(Symb);
786   const Elf_Shdr *sec = getSection(symb);
787   if (!sec)
788     Res = end_sections();
789   else {
790     DataRefImpl Sec;
791     Sec.p = reinterpret_cast<intptr_t>(sec);
792     Res = section_iterator(SectionRef(Sec, this));
793   }
794   return object_error::success;
795 }
796
797 template<support::endianness target_endianness, bool is64Bits>
798 error_code ELFObjectFile<target_endianness, is64Bits>
799                         ::getSectionNext(DataRefImpl Sec, SectionRef &Result) const {
800   const uint8_t *sec = reinterpret_cast<const uint8_t *>(Sec.p);
801   sec += Header->e_shentsize;
802   Sec.p = reinterpret_cast<intptr_t>(sec);
803   Result = SectionRef(Sec, this);
804   return object_error::success;
805 }
806
807 template<support::endianness target_endianness, bool is64Bits>
808 error_code ELFObjectFile<target_endianness, is64Bits>
809                         ::getSectionName(DataRefImpl Sec,
810                                          StringRef &Result) const {
811   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
812   Result = StringRef(getString(dot_shstrtab_sec, sec->sh_name));
813   return object_error::success;
814 }
815
816 template<support::endianness target_endianness, bool is64Bits>
817 error_code ELFObjectFile<target_endianness, is64Bits>
818                         ::getSectionAddress(DataRefImpl Sec,
819                                             uint64_t &Result) const {
820   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
821   Result = sec->sh_addr;
822   return object_error::success;
823 }
824
825 template<support::endianness target_endianness, bool is64Bits>
826 error_code ELFObjectFile<target_endianness, is64Bits>
827                         ::getSectionSize(DataRefImpl Sec,
828                                          uint64_t &Result) const {
829   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
830   Result = sec->sh_size;
831   return object_error::success;
832 }
833
834 template<support::endianness target_endianness, bool is64Bits>
835 error_code ELFObjectFile<target_endianness, is64Bits>
836                         ::getSectionContents(DataRefImpl Sec,
837                                              StringRef &Result) const {
838   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
839   const char *start = (const char*)base() + sec->sh_offset;
840   Result = StringRef(start, sec->sh_size);
841   return object_error::success;
842 }
843
844 template<support::endianness target_endianness, bool is64Bits>
845 error_code ELFObjectFile<target_endianness, is64Bits>
846                         ::getSectionAlignment(DataRefImpl Sec,
847                                               uint64_t &Result) const {
848   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
849   Result = sec->sh_addralign;
850   return object_error::success;
851 }
852
853 template<support::endianness target_endianness, bool is64Bits>
854 error_code ELFObjectFile<target_endianness, is64Bits>
855                         ::isSectionText(DataRefImpl Sec,
856                                         bool &Result) const {
857   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
858   if (sec->sh_flags & ELF::SHF_EXECINSTR)
859     Result = true;
860   else
861     Result = false;
862   return object_error::success;
863 }
864
865 template<support::endianness target_endianness, bool is64Bits>
866 error_code ELFObjectFile<target_endianness, is64Bits>
867                         ::isSectionData(DataRefImpl Sec,
868                                         bool &Result) const {
869   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
870   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
871       && sec->sh_type == ELF::SHT_PROGBITS)
872     Result = true;
873   else
874     Result = false;
875   return object_error::success;
876 }
877
878 template<support::endianness target_endianness, bool is64Bits>
879 error_code ELFObjectFile<target_endianness, is64Bits>
880                         ::isSectionBSS(DataRefImpl Sec,
881                                        bool &Result) const {
882   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
883   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
884       && sec->sh_type == ELF::SHT_NOBITS)
885     Result = true;
886   else
887     Result = false;
888   return object_error::success;
889 }
890
891 template<support::endianness target_endianness, bool is64Bits>
892 error_code ELFObjectFile<target_endianness, is64Bits>
893                           ::sectionContainsSymbol(DataRefImpl Sec,
894                                                   DataRefImpl Symb,
895                                                   bool &Result) const {
896   // FIXME: Unimplemented.
897   Result = false;
898   return object_error::success;
899 }
900
901 template<support::endianness target_endianness, bool is64Bits>
902 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
903                                  ::getSectionRelBegin(DataRefImpl Sec) const {
904   DataRefImpl RelData;
905   memset(&RelData, 0, sizeof(RelData));
906   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
907   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
908   if (sec != 0 && ittr != SectionRelocMap.end()) {
909     RelData.w.a = getSection(ittr->second[0])->sh_info;
910     RelData.w.b = ittr->second[0];
911     RelData.w.c = 0;
912   }
913   return relocation_iterator(RelocationRef(RelData, this));
914 }
915
916 template<support::endianness target_endianness, bool is64Bits>
917 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
918                                  ::getSectionRelEnd(DataRefImpl Sec) const {
919   DataRefImpl RelData;
920   memset(&RelData, 0, sizeof(RelData));
921   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
922   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
923   if (sec != 0 && ittr != SectionRelocMap.end()) {
924     // Get the index of the last relocation section for this section.
925     std::size_t relocsecindex = ittr->second[ittr->second.size() - 1];
926     const Elf_Shdr *relocsec = getSection(relocsecindex);
927     RelData.w.a = relocsec->sh_info;
928     RelData.w.b = relocsecindex;
929     RelData.w.c = relocsec->sh_size / relocsec->sh_entsize;
930   }
931   return relocation_iterator(RelocationRef(RelData, this));
932 }
933
934 // Relocations
935 template<support::endianness target_endianness, bool is64Bits>
936 error_code ELFObjectFile<target_endianness, is64Bits>
937                         ::getRelocationNext(DataRefImpl Rel,
938                                             RelocationRef &Result) const {
939   ++Rel.w.c;
940   const Elf_Shdr *relocsec = getSection(Rel.w.b);
941   if (Rel.w.c >= (relocsec->sh_size / relocsec->sh_entsize)) {
942     // We have reached the end of the relocations for this section. See if there
943     // is another relocation section.
944     typename RelocMap_t::mapped_type relocseclist =
945       SectionRelocMap.lookup(getSection(Rel.w.a));
946
947     // Do a binary search for the current reloc section index (which must be
948     // present). Then get the next one.
949     typename RelocMap_t::mapped_type::const_iterator loc =
950       std::lower_bound(relocseclist.begin(), relocseclist.end(), Rel.w.b);
951     ++loc;
952
953     // If there is no next one, don't do anything. The ++Rel.w.c above sets Rel
954     // to the end iterator.
955     if (loc != relocseclist.end()) {
956       Rel.w.b = *loc;
957       Rel.w.a = 0;
958     }
959   }
960   Result = RelocationRef(Rel, this);
961   return object_error::success;
962 }
963
964 template<support::endianness target_endianness, bool is64Bits>
965 error_code ELFObjectFile<target_endianness, is64Bits>
966                         ::getRelocationSymbol(DataRefImpl Rel,
967                                               SymbolRef &Result) const {
968   uint32_t symbolIdx;
969   const Elf_Shdr *sec = getSection(Rel.w.b);
970   switch (sec->sh_type) {
971     default :
972       report_fatal_error("Invalid section type in Rel!");
973     case ELF::SHT_REL : {
974       symbolIdx = getRel(Rel)->getSymbol();
975       break;
976     }
977     case ELF::SHT_RELA : {
978       symbolIdx = getRela(Rel)->getSymbol();
979       break;
980     }
981   }
982   DataRefImpl SymbolData;
983   IndexMap_t::const_iterator it = SymbolTableSectionsIndexMap.find(sec->sh_link);
984   if (it == SymbolTableSectionsIndexMap.end())
985     report_fatal_error("Relocation symbol table not found!");
986   SymbolData.d.a = symbolIdx;
987   SymbolData.d.b = it->second;
988   Result = SymbolRef(SymbolData, this);
989   return object_error::success;
990 }
991
992 template<support::endianness target_endianness, bool is64Bits>
993 error_code ELFObjectFile<target_endianness, is64Bits>
994                         ::getRelocationAddress(DataRefImpl Rel,
995                                                uint64_t &Result) const {
996   uint64_t offset;
997   const Elf_Shdr *sec = getSection(Rel.w.b);
998   switch (sec->sh_type) {
999     default :
1000       report_fatal_error("Invalid section type in Rel!");
1001     case ELF::SHT_REL : {
1002       offset = getRel(Rel)->r_offset;
1003       break;
1004     }
1005     case ELF::SHT_RELA : {
1006       offset = getRela(Rel)->r_offset;
1007       break;
1008     }
1009   }
1010
1011   Result = offset;
1012   return object_error::success;
1013 }
1014
1015 template<support::endianness target_endianness, bool is64Bits>
1016 error_code ELFObjectFile<target_endianness, is64Bits>
1017                         ::getRelocationOffset(DataRefImpl Rel,
1018                                               uint64_t &Result) const {
1019   uint64_t offset;
1020   const Elf_Shdr *sec = getSection(Rel.w.b);
1021   switch (sec->sh_type) {
1022     default :
1023       report_fatal_error("Invalid section type in Rel!");
1024     case ELF::SHT_REL : {
1025       offset = getRel(Rel)->r_offset;
1026       break;
1027     }
1028     case ELF::SHT_RELA : {
1029       offset = getRela(Rel)->r_offset;
1030       break;
1031     }
1032   }
1033
1034   Result = offset - sec->sh_addr;
1035   return object_error::success;
1036 }
1037
1038 template<support::endianness target_endianness, bool is64Bits>
1039 error_code ELFObjectFile<target_endianness, is64Bits>
1040                         ::getRelocationType(DataRefImpl Rel,
1041                                             uint64_t &Result) const {
1042   const Elf_Shdr *sec = getSection(Rel.w.b);
1043   switch (sec->sh_type) {
1044     default :
1045       report_fatal_error("Invalid section type in Rel!");
1046     case ELF::SHT_REL : {
1047       Result = getRel(Rel)->getType();
1048       break;
1049     }
1050     case ELF::SHT_RELA : {
1051       Result = getRela(Rel)->getType();
1052       break;
1053     }
1054   }
1055   return object_error::success;
1056 }
1057
1058 #define LLVM_ELF_SWITCH_RELOC_TYPE_NAME(enum) \
1059   case ELF::enum: res = #enum; break;
1060
1061 template<support::endianness target_endianness, bool is64Bits>
1062 error_code ELFObjectFile<target_endianness, is64Bits>
1063                         ::getRelocationTypeName(DataRefImpl Rel,
1064                                           SmallVectorImpl<char> &Result) const {
1065   const Elf_Shdr *sec = getSection(Rel.w.b);
1066   uint8_t type;
1067   StringRef res;
1068   switch (sec->sh_type) {
1069     default :
1070       return object_error::parse_failed;
1071     case ELF::SHT_REL : {
1072       type = getRel(Rel)->getType();
1073       break;
1074     }
1075     case ELF::SHT_RELA : {
1076       type = getRela(Rel)->getType();
1077       break;
1078     }
1079   }
1080   switch (Header->e_machine) {
1081   case ELF::EM_X86_64:
1082     switch (type) {
1083       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_NONE);
1084       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_64);
1085       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC32);
1086       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOT32);
1087       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PLT32);
1088       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_COPY);
1089       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GLOB_DAT);
1090       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_JUMP_SLOT);
1091       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_RELATIVE);
1092       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPCREL);
1093       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32);
1094       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32S);
1095       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_16);
1096       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC16);
1097       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_8);
1098       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC8);
1099       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPMOD64);
1100       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF64);
1101       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF64);
1102       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSGD);
1103       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSLD);
1104       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF32);
1105       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTTPOFF);
1106       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF32);
1107       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC64);
1108       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTOFF64);
1109       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32);
1110       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE32);
1111       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE64);
1112       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32_TLSDESC);
1113       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC_CALL);
1114       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC);
1115     default:
1116       res = "Unknown";
1117     }
1118     break;
1119   case ELF::EM_386:
1120     switch (type) {
1121       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_NONE);
1122       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32);
1123       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC32);
1124       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOT32);
1125       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PLT32);
1126       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_COPY);
1127       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GLOB_DAT);
1128       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_JUMP_SLOT);
1129       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_RELATIVE);
1130       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTOFF);
1131       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTPC);
1132       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32PLT);
1133       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF);
1134       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE);
1135       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTIE);
1136       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE);
1137       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD);
1138       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM);
1139       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_16);
1140       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC16);
1141       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_8);
1142       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC8);
1143       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_32);
1144       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_PUSH);
1145       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_CALL);
1146       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_POP);
1147       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_32);
1148       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_PUSH);
1149       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_CALL);
1150       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_POP);
1151       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDO_32);
1152       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE_32);
1153       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE_32);
1154       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPMOD32);
1155       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPOFF32);
1156       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF32);
1157       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTDESC);
1158       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC_CALL);
1159       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC);
1160       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_IRELATIVE);
1161     default:
1162       res = "Unknown";
1163     }
1164     break;
1165   default:
1166     res = "Unknown";
1167   }
1168   Result.append(res.begin(), res.end());
1169   return object_error::success;
1170 }
1171
1172 #undef LLVM_ELF_SWITCH_RELOC_TYPE_NAME
1173
1174 template<support::endianness target_endianness, bool is64Bits>
1175 error_code ELFObjectFile<target_endianness, is64Bits>
1176                         ::getRelocationAdditionalInfo(DataRefImpl Rel,
1177                                                       int64_t &Result) const {
1178   const Elf_Shdr *sec = getSection(Rel.w.b);
1179   switch (sec->sh_type) {
1180     default :
1181       report_fatal_error("Invalid section type in Rel!");
1182     case ELF::SHT_REL : {
1183       Result = 0;
1184       return object_error::success;
1185     }
1186     case ELF::SHT_RELA : {
1187       Result = getRela(Rel)->r_addend;
1188       return object_error::success;
1189     }
1190   }
1191 }
1192
1193 template<support::endianness target_endianness, bool is64Bits>
1194 error_code ELFObjectFile<target_endianness, is64Bits>
1195                         ::getRelocationValueString(DataRefImpl Rel,
1196                                           SmallVectorImpl<char> &Result) const {
1197   const Elf_Shdr *sec = getSection(Rel.w.b);
1198   uint8_t type;
1199   StringRef res;
1200   int64_t addend = 0;
1201   uint16_t symbol_index = 0;
1202   switch (sec->sh_type) {
1203     default :
1204       return object_error::parse_failed;
1205     case ELF::SHT_REL : {
1206       type = getRel(Rel)->getType();
1207       symbol_index = getRel(Rel)->getSymbol();
1208       // TODO: Read implicit addend from section data.
1209       break;
1210     }
1211     case ELF::SHT_RELA : {
1212       type = getRela(Rel)->getType();
1213       symbol_index = getRela(Rel)->getSymbol();
1214       addend = getRela(Rel)->r_addend;
1215       break;
1216     }
1217   }
1218   const Elf_Sym *symb = getEntry<Elf_Sym>(sec->sh_link, symbol_index);
1219   StringRef symname;
1220   if (error_code ec = getSymbolName(getSection(sec->sh_link), symb, symname))
1221     return ec;
1222   switch (Header->e_machine) {
1223   case ELF::EM_X86_64:
1224     switch (type) {
1225     case ELF::R_X86_64_32S:
1226       res = symname;
1227       break;
1228     case ELF::R_X86_64_PC32: {
1229         std::string fmtbuf;
1230         raw_string_ostream fmt(fmtbuf);
1231         fmt << symname << (addend < 0 ? "" : "+") << addend << "-P";
1232         fmt.flush();
1233         Result.append(fmtbuf.begin(), fmtbuf.end());
1234       }
1235       break;
1236     default:
1237       res = "Unknown";
1238     }
1239     break;
1240   default:
1241     res = "Unknown";
1242   }
1243   if (Result.empty())
1244     Result.append(res.begin(), res.end());
1245   return object_error::success;
1246 }
1247
1248 // Verify that the last byte in the string table in a null.
1249 template<support::endianness target_endianness, bool is64Bits>
1250 void ELFObjectFile<target_endianness, is64Bits>
1251                   ::VerifyStrTab(const Elf_Shdr *sh) const {
1252   const char *strtab = (const char*)base() + sh->sh_offset;
1253   if (strtab[sh->sh_size - 1] != 0)
1254     // FIXME: Proper error handling.
1255     report_fatal_error("String table must end with a null terminator!");
1256 }
1257
1258 template<support::endianness target_endianness, bool is64Bits>
1259 ELFObjectFile<target_endianness, is64Bits>::ELFObjectFile(MemoryBuffer *Object
1260                                                           , error_code &ec)
1261   : ObjectFile(getELFType(target_endianness == support::little, is64Bits),
1262                Object, ec)
1263   , isDyldELFObject(false)
1264   , SectionHeaderTable(0)
1265   , dot_shstrtab_sec(0)
1266   , dot_strtab_sec(0)
1267   , dot_dynstr_sec(0)
1268   , dot_dynamic_sec(0)
1269   , dt_soname(0) {
1270
1271   const uint64_t FileSize = Data->getBufferSize();
1272
1273   if (sizeof(Elf_Ehdr) > FileSize)
1274     // FIXME: Proper error handling.
1275     report_fatal_error("File too short!");
1276
1277   Header = reinterpret_cast<const Elf_Ehdr *>(base());
1278
1279   if (Header->e_shoff == 0)
1280     return;
1281
1282   const uint64_t SectionTableOffset = Header->e_shoff;
1283
1284   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
1285     // FIXME: Proper error handling.
1286     report_fatal_error("Section header table goes past end of file!");
1287
1288   // The getNumSections() call below depends on SectionHeaderTable being set.
1289   SectionHeaderTable =
1290     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
1291   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
1292
1293   if (SectionTableOffset + SectionTableSize > FileSize)
1294     // FIXME: Proper error handling.
1295     report_fatal_error("Section table goes past end of file!");
1296
1297   // To find the symbol tables we walk the section table to find SHT_SYMTAB.
1298   const Elf_Shdr* SymbolTableSectionHeaderIndex = 0;
1299   const Elf_Shdr* sh = SectionHeaderTable;
1300
1301   // Reserve SymbolTableSections[0] for .dynsym
1302   SymbolTableSections.push_back(NULL);
1303
1304   for (uint64_t i = 0, e = getNumSections(); i != e; ++i) {
1305     if (sh->sh_type == ELF::SHT_SYMTAB_SHNDX) {
1306       if (SymbolTableSectionHeaderIndex)
1307         // FIXME: Proper error handling.
1308         report_fatal_error("More than one .symtab_shndx!");
1309       SymbolTableSectionHeaderIndex = sh;
1310     }
1311     if (sh->sh_type == ELF::SHT_SYMTAB) {
1312       SymbolTableSectionsIndexMap[i] = SymbolTableSections.size();
1313       SymbolTableSections.push_back(sh);
1314     }
1315     if (sh->sh_type == ELF::SHT_DYNSYM) {
1316       if (SymbolTableSections[0] != NULL)
1317         // FIXME: Proper error handling.
1318         report_fatal_error("More than one .dynsym!");
1319       SymbolTableSectionsIndexMap[i] = 0;
1320       SymbolTableSections[0] = sh;
1321     }
1322     if (sh->sh_type == ELF::SHT_REL || sh->sh_type == ELF::SHT_RELA) {
1323       SectionRelocMap[getSection(sh->sh_info)].push_back(i);
1324     }
1325     if (sh->sh_type == ELF::SHT_DYNAMIC) {
1326       if (dot_dynamic_sec != NULL)
1327         // FIXME: Proper error handling.
1328         report_fatal_error("More than one .dynamic!");
1329       dot_dynamic_sec = sh;
1330     }
1331     ++sh;
1332   }
1333
1334   // Sort section relocation lists by index.
1335   for (typename RelocMap_t::iterator i = SectionRelocMap.begin(),
1336                                      e = SectionRelocMap.end(); i != e; ++i) {
1337     std::sort(i->second.begin(), i->second.end());
1338   }
1339
1340   // Get string table sections.
1341   dot_shstrtab_sec = getSection(getStringTableIndex());
1342   if (dot_shstrtab_sec) {
1343     // Verify that the last byte in the string table in a null.
1344     VerifyStrTab(dot_shstrtab_sec);
1345   }
1346
1347   // Merge this into the above loop.
1348   for (const char *i = reinterpret_cast<const char *>(SectionHeaderTable),
1349                   *e = i + getNumSections() * Header->e_shentsize;
1350                    i != e; i += Header->e_shentsize) {
1351     const Elf_Shdr *sh = reinterpret_cast<const Elf_Shdr*>(i);
1352     if (sh->sh_type == ELF::SHT_STRTAB) {
1353       StringRef SectionName(getString(dot_shstrtab_sec, sh->sh_name));
1354       if (SectionName == ".strtab") {
1355         if (dot_strtab_sec != 0)
1356           // FIXME: Proper error handling.
1357           report_fatal_error("Already found section named .strtab!");
1358         dot_strtab_sec = sh;
1359         VerifyStrTab(dot_strtab_sec);
1360       } else if (SectionName == ".dynstr") {
1361         if (dot_dynstr_sec != 0)
1362           // FIXME: Proper error handling.
1363           report_fatal_error("Already found section named .dynstr!");
1364         dot_dynstr_sec = sh;
1365         VerifyStrTab(dot_dynstr_sec);
1366       }
1367     }
1368   }
1369
1370   // Build symbol name side-mapping if there is one.
1371   if (SymbolTableSectionHeaderIndex) {
1372     const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
1373                                       SymbolTableSectionHeaderIndex->sh_offset);
1374     error_code ec;
1375     for (symbol_iterator si = begin_symbols(),
1376                          se = end_symbols(); si != se; si.increment(ec)) {
1377       if (ec)
1378         report_fatal_error("Fewer extended symbol table entries than symbols!");
1379       if (*ShndxTable != ELF::SHN_UNDEF)
1380         ExtendedSymbolTable[getSymbol(si->getRawDataRefImpl())] = *ShndxTable;
1381       ++ShndxTable;
1382     }
1383   }
1384 }
1385
1386 template<support::endianness target_endianness, bool is64Bits>
1387 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1388                              ::begin_symbols() const {
1389   DataRefImpl SymbolData;
1390   memset(&SymbolData, 0, sizeof(SymbolData));
1391   if (SymbolTableSections.size() <= 1) {
1392     SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1393     SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1394   } else {
1395     SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
1396     SymbolData.d.b = 1; // The 0th table is .dynsym
1397   }
1398   return symbol_iterator(SymbolRef(SymbolData, this));
1399 }
1400
1401 template<support::endianness target_endianness, bool is64Bits>
1402 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1403                              ::end_symbols() const {
1404   DataRefImpl SymbolData;
1405   memset(&SymbolData, 0, sizeof(SymbolData));
1406   SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1407   SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1408   return symbol_iterator(SymbolRef(SymbolData, this));
1409 }
1410
1411 template<support::endianness target_endianness, bool is64Bits>
1412 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1413                              ::begin_dynamic_symbols() const {
1414   DataRefImpl SymbolData;
1415   memset(&SymbolData, 0, sizeof(SymbolData));
1416   if (SymbolTableSections[0] == NULL) {
1417     SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1418     SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1419   } else {
1420     SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
1421     SymbolData.d.b = 0; // The 0th table is .dynsym
1422   }
1423   return symbol_iterator(SymbolRef(SymbolData, this));
1424 }
1425
1426 template<support::endianness target_endianness, bool is64Bits>
1427 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1428                              ::end_dynamic_symbols() const {
1429   DataRefImpl SymbolData;
1430   memset(&SymbolData, 0, sizeof(SymbolData));
1431   SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1432   SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1433   return symbol_iterator(SymbolRef(SymbolData, this));
1434 }
1435
1436 template<support::endianness target_endianness, bool is64Bits>
1437 section_iterator ELFObjectFile<target_endianness, is64Bits>
1438                               ::begin_sections() const {
1439   DataRefImpl ret;
1440   memset(&ret, 0, sizeof(DataRefImpl));
1441   ret.p = reinterpret_cast<intptr_t>(base() + Header->e_shoff);
1442   return section_iterator(SectionRef(ret, this));
1443 }
1444
1445 template<support::endianness target_endianness, bool is64Bits>
1446 section_iterator ELFObjectFile<target_endianness, is64Bits>
1447                               ::end_sections() const {
1448   DataRefImpl ret;
1449   memset(&ret, 0, sizeof(DataRefImpl));
1450   ret.p = reinterpret_cast<intptr_t>(base()
1451                                      + Header->e_shoff
1452                                      + (Header->e_shentsize*getNumSections()));
1453   return section_iterator(SectionRef(ret, this));
1454 }
1455
1456 template<support::endianness target_endianness, bool is64Bits>
1457 typename ELFObjectFile<target_endianness, is64Bits>::dyn_iterator
1458 ELFObjectFile<target_endianness, is64Bits>::begin_dynamic_table() const {
1459   DataRefImpl DynData;
1460   memset(&DynData, 0, sizeof(DynData));
1461   if (dot_dynamic_sec == NULL || dot_dynamic_sec->sh_size == 0) {
1462     DynData.d.a = std::numeric_limits<uint32_t>::max();
1463   } else {
1464     DynData.d.a = 0;
1465   }
1466   return dyn_iterator(DynRef(DynData, this));
1467 }
1468
1469 template<support::endianness target_endianness, bool is64Bits>
1470 typename ELFObjectFile<target_endianness, is64Bits>::dyn_iterator
1471 ELFObjectFile<target_endianness, is64Bits>
1472                           ::end_dynamic_table() const {
1473   DataRefImpl DynData;
1474   memset(&DynData, 0, sizeof(DynData));
1475   DynData.d.a = std::numeric_limits<uint32_t>::max();
1476   return dyn_iterator(DynRef(DynData, this));
1477 }
1478
1479 template<support::endianness target_endianness, bool is64Bits>
1480 error_code ELFObjectFile<target_endianness, is64Bits>
1481                         ::getDynNext(DataRefImpl DynData,
1482                                      DynRef &Result) const {
1483   ++DynData.d.a;
1484
1485   // Check to see if we are at the end of .dynamic
1486   if (DynData.d.a >= dot_dynamic_sec->getEntityCount()) {
1487     // We are at the end. Return the terminator.
1488     DynData.d.a = std::numeric_limits<uint32_t>::max();
1489   }
1490
1491   Result = DynRef(DynData, this);
1492   return object_error::success;
1493 }
1494
1495 template<support::endianness target_endianness, bool is64Bits>
1496 StringRef
1497 ELFObjectFile<target_endianness, is64Bits>::getLoadName() const {
1498   if (!dt_soname) {
1499     // Find the DT_SONAME entry
1500     dyn_iterator it = begin_dynamic_table();
1501     dyn_iterator ie = end_dynamic_table();
1502     error_code ec;
1503     while (it != ie) {
1504       if (it->getTag() == ELF::DT_SONAME)
1505         break;
1506       it.increment(ec);
1507       if (ec)
1508         report_fatal_error("dynamic table iteration failed");
1509     }
1510     if (it != ie) {
1511       if (dot_dynstr_sec == NULL)
1512         report_fatal_error("Dynamic string table is missing");
1513       dt_soname = getString(dot_dynstr_sec, it->getVal());
1514     } else {
1515       dt_soname = "";
1516     }
1517   }
1518   return dt_soname;
1519 }
1520
1521 template<support::endianness target_endianness, bool is64Bits>
1522 library_iterator ELFObjectFile<target_endianness, is64Bits>
1523                              ::begin_libraries_needed() const {
1524   // Find the first DT_NEEDED entry
1525   dyn_iterator i = begin_dynamic_table();
1526   dyn_iterator e = end_dynamic_table();
1527   error_code ec;
1528   while (i != e) {
1529     if (i->getTag() == ELF::DT_NEEDED)
1530       break;
1531     i.increment(ec);
1532     if (ec)
1533       report_fatal_error("dynamic table iteration failed");
1534   }
1535   // Use the same DataRefImpl format as DynRef.
1536   return library_iterator(LibraryRef(i->getRawDataRefImpl(), this));
1537 }
1538
1539 template<support::endianness target_endianness, bool is64Bits>
1540 error_code ELFObjectFile<target_endianness, is64Bits>
1541                         ::getLibraryNext(DataRefImpl Data,
1542                                          LibraryRef &Result) const {
1543   // Use the same DataRefImpl format as DynRef.
1544   dyn_iterator i = dyn_iterator(DynRef(Data, this));
1545   dyn_iterator e = end_dynamic_table();
1546
1547   // Skip the current dynamic table entry.
1548   error_code ec;
1549   if (i != e) {
1550     i.increment(ec);
1551     // TODO: proper error handling
1552     if (ec)
1553       report_fatal_error("dynamic table iteration failed");
1554   }
1555
1556   // Find the next DT_NEEDED entry.
1557   while (i != e) {
1558     if (i->getTag() == ELF::DT_NEEDED)
1559       break;
1560     i.increment(ec);
1561     if (ec)
1562       report_fatal_error("dynamic table iteration failed");
1563   }
1564   Result = LibraryRef(i->getRawDataRefImpl(), this);
1565   return object_error::success;
1566 }
1567
1568 template<support::endianness target_endianness, bool is64Bits>
1569 error_code ELFObjectFile<target_endianness, is64Bits>
1570          ::getLibraryPath(DataRefImpl Data, StringRef &Res) const {
1571   dyn_iterator i = dyn_iterator(DynRef(Data, this));
1572   if (i == end_dynamic_table())
1573     report_fatal_error("getLibraryPath() called on iterator end");
1574
1575   if (i->getTag() != ELF::DT_NEEDED)
1576     report_fatal_error("Invalid library_iterator");
1577
1578   // This uses .dynstr to lookup the name of the DT_NEEDED entry.
1579   // THis works as long as DT_STRTAB == .dynstr. This is true most of
1580   // the time, but the specification allows exceptions.
1581   // TODO: This should really use DT_STRTAB instead. Doing this requires
1582   // reading the program headers.
1583   if (dot_dynstr_sec == NULL)
1584     report_fatal_error("Dynamic string table is missing");
1585   Res = getString(dot_dynstr_sec, i->getVal());
1586   return object_error::success;
1587 }
1588
1589 template<support::endianness target_endianness, bool is64Bits>
1590 library_iterator ELFObjectFile<target_endianness, is64Bits>
1591                              ::end_libraries_needed() const {
1592   dyn_iterator e = end_dynamic_table();
1593   // Use the same DataRefImpl format as DynRef.
1594   return library_iterator(LibraryRef(e->getRawDataRefImpl(), this));
1595 }
1596
1597 template<support::endianness target_endianness, bool is64Bits>
1598 uint8_t ELFObjectFile<target_endianness, is64Bits>::getBytesInAddress() const {
1599   return is64Bits ? 8 : 4;
1600 }
1601
1602 template<support::endianness target_endianness, bool is64Bits>
1603 StringRef ELFObjectFile<target_endianness, is64Bits>
1604                        ::getFileFormatName() const {
1605   switch(Header->e_ident[ELF::EI_CLASS]) {
1606   case ELF::ELFCLASS32:
1607     switch(Header->e_machine) {
1608     case ELF::EM_386:
1609       return "ELF32-i386";
1610     case ELF::EM_X86_64:
1611       return "ELF32-x86-64";
1612     case ELF::EM_ARM:
1613       return "ELF32-arm";
1614     default:
1615       return "ELF32-unknown";
1616     }
1617   case ELF::ELFCLASS64:
1618     switch(Header->e_machine) {
1619     case ELF::EM_386:
1620       return "ELF64-i386";
1621     case ELF::EM_X86_64:
1622       return "ELF64-x86-64";
1623     default:
1624       return "ELF64-unknown";
1625     }
1626   default:
1627     // FIXME: Proper error handling.
1628     report_fatal_error("Invalid ELFCLASS!");
1629   }
1630 }
1631
1632 template<support::endianness target_endianness, bool is64Bits>
1633 unsigned ELFObjectFile<target_endianness, is64Bits>::getArch() const {
1634   switch(Header->e_machine) {
1635   case ELF::EM_386:
1636     return Triple::x86;
1637   case ELF::EM_X86_64:
1638     return Triple::x86_64;
1639   case ELF::EM_ARM:
1640     return Triple::arm;
1641   default:
1642     return Triple::UnknownArch;
1643   }
1644 }
1645
1646 template<support::endianness target_endianness, bool is64Bits>
1647 uint64_t ELFObjectFile<target_endianness, is64Bits>::getNumSections() const {
1648   assert(Header && "Header not initialized!");
1649   if (Header->e_shnum == ELF::SHN_UNDEF) {
1650     assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
1651     return SectionHeaderTable->sh_size;
1652   }
1653   return Header->e_shnum;
1654 }
1655
1656 template<support::endianness target_endianness, bool is64Bits>
1657 uint64_t
1658 ELFObjectFile<target_endianness, is64Bits>::getStringTableIndex() const {
1659   if (Header->e_shnum == ELF::SHN_UNDEF) {
1660     if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
1661       return SectionHeaderTable->sh_link;
1662     if (Header->e_shstrndx >= getNumSections())
1663       return 0;
1664   }
1665   return Header->e_shstrndx;
1666 }
1667
1668
1669 template<support::endianness target_endianness, bool is64Bits>
1670 template<typename T>
1671 inline const T *
1672 ELFObjectFile<target_endianness, is64Bits>::getEntry(uint16_t Section,
1673                                                      uint32_t Entry) const {
1674   return getEntry<T>(getSection(Section), Entry);
1675 }
1676
1677 template<support::endianness target_endianness, bool is64Bits>
1678 template<typename T>
1679 inline const T *
1680 ELFObjectFile<target_endianness, is64Bits>::getEntry(const Elf_Shdr * Section,
1681                                                      uint32_t Entry) const {
1682   return reinterpret_cast<const T *>(
1683            base()
1684            + Section->sh_offset
1685            + (Entry * Section->sh_entsize));
1686 }
1687
1688 template<support::endianness target_endianness, bool is64Bits>
1689 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
1690 ELFObjectFile<target_endianness, is64Bits>::getSymbol(DataRefImpl Symb) const {
1691   return getEntry<Elf_Sym>(SymbolTableSections[Symb.d.b], Symb.d.a);
1692 }
1693
1694 template<support::endianness target_endianness, bool is64Bits>
1695 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Dyn *
1696 ELFObjectFile<target_endianness, is64Bits>::getDyn(DataRefImpl DynData) const {
1697   return getEntry<Elf_Dyn>(dot_dynamic_sec, DynData.d.a);
1698 }
1699
1700 template<support::endianness target_endianness, bool is64Bits>
1701 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rel *
1702 ELFObjectFile<target_endianness, is64Bits>::getRel(DataRefImpl Rel) const {
1703   return getEntry<Elf_Rel>(Rel.w.b, Rel.w.c);
1704 }
1705
1706 template<support::endianness target_endianness, bool is64Bits>
1707 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rela *
1708 ELFObjectFile<target_endianness, is64Bits>::getRela(DataRefImpl Rela) const {
1709   return getEntry<Elf_Rela>(Rela.w.b, Rela.w.c);
1710 }
1711
1712 template<support::endianness target_endianness, bool is64Bits>
1713 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
1714 ELFObjectFile<target_endianness, is64Bits>::getSection(DataRefImpl Symb) const {
1715   const Elf_Shdr *sec = getSection(Symb.d.b);
1716   if (sec->sh_type != ELF::SHT_SYMTAB || sec->sh_type != ELF::SHT_DYNSYM)
1717     // FIXME: Proper error handling.
1718     report_fatal_error("Invalid symbol table section!");
1719   return sec;
1720 }
1721
1722 template<support::endianness target_endianness, bool is64Bits>
1723 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
1724 ELFObjectFile<target_endianness, is64Bits>::getSection(uint32_t index) const {
1725   if (index == 0)
1726     return 0;
1727   if (!SectionHeaderTable || index >= getNumSections())
1728     // FIXME: Proper error handling.
1729     report_fatal_error("Invalid section index!");
1730
1731   return reinterpret_cast<const Elf_Shdr *>(
1732          reinterpret_cast<const char *>(SectionHeaderTable)
1733          + (index * Header->e_shentsize));
1734 }
1735
1736 template<support::endianness target_endianness, bool is64Bits>
1737 const char *ELFObjectFile<target_endianness, is64Bits>
1738                          ::getString(uint32_t section,
1739                                      ELF::Elf32_Word offset) const {
1740   return getString(getSection(section), offset);
1741 }
1742
1743 template<support::endianness target_endianness, bool is64Bits>
1744 const char *ELFObjectFile<target_endianness, is64Bits>
1745                          ::getString(const Elf_Shdr *section,
1746                                      ELF::Elf32_Word offset) const {
1747   assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
1748   if (offset >= section->sh_size)
1749     // FIXME: Proper error handling.
1750     report_fatal_error("Symbol name offset outside of string table!");
1751   return (const char *)base() + section->sh_offset + offset;
1752 }
1753
1754 template<support::endianness target_endianness, bool is64Bits>
1755 error_code ELFObjectFile<target_endianness, is64Bits>
1756                         ::getSymbolName(const Elf_Shdr *section,
1757                                         const Elf_Sym *symb,
1758                                         StringRef &Result) const {
1759   if (symb->st_name == 0) {
1760     const Elf_Shdr *section = getSection(symb);
1761     if (!section)
1762       Result = "";
1763     else
1764       Result = getString(dot_shstrtab_sec, section->sh_name);
1765     return object_error::success;
1766   }
1767
1768   if (section == SymbolTableSections[0]) {
1769     // Symbol is in .dynsym, use .dynstr string table
1770     Result = getString(dot_dynstr_sec, symb->st_name);
1771   } else {
1772     // Use the default symbol table name section.
1773     Result = getString(dot_strtab_sec, symb->st_name);
1774   }
1775   return object_error::success;
1776 }
1777
1778 template<support::endianness target_endianness, bool is64Bits>
1779 inline DynRefImpl<target_endianness, is64Bits>
1780                  ::DynRefImpl(DataRefImpl DynP, const OwningType *Owner)
1781   : DynPimpl(DynP)
1782   , OwningObject(Owner) {}
1783
1784 template<support::endianness target_endianness, bool is64Bits>
1785 inline bool DynRefImpl<target_endianness, is64Bits>
1786                       ::operator==(const DynRefImpl &Other) const {
1787   return DynPimpl == Other.DynPimpl;
1788 }
1789
1790 template<support::endianness target_endianness, bool is64Bits>
1791 inline bool DynRefImpl<target_endianness, is64Bits>
1792                       ::operator <(const DynRefImpl &Other) const {
1793   return DynPimpl < Other.DynPimpl;
1794 }
1795
1796 template<support::endianness target_endianness, bool is64Bits>
1797 inline error_code DynRefImpl<target_endianness, is64Bits>
1798                             ::getNext(DynRefImpl &Result) const {
1799   return OwningObject->getDynNext(DynPimpl, Result);
1800 }
1801
1802 template<support::endianness target_endianness, bool is64Bits>
1803 inline int64_t DynRefImpl<target_endianness, is64Bits>
1804                             ::getTag() const {
1805   return OwningObject->getDyn(DynPimpl)->d_tag;
1806 }
1807
1808 template<support::endianness target_endianness, bool is64Bits>
1809 inline uint64_t DynRefImpl<target_endianness, is64Bits>
1810                             ::getVal() const {
1811   return OwningObject->getDyn(DynPimpl)->d_un.d_val;
1812 }
1813
1814 template<support::endianness target_endianness, bool is64Bits>
1815 inline uint64_t DynRefImpl<target_endianness, is64Bits>
1816                             ::getPtr() const {
1817   return OwningObject->getDyn(DynPimpl)->d_un.d_ptr;
1818 }
1819
1820 template<support::endianness target_endianness, bool is64Bits>
1821 inline DataRefImpl DynRefImpl<target_endianness, is64Bits>
1822                              ::getRawDataRefImpl() const {
1823   return DynPimpl;
1824 }
1825
1826 }
1827 }
1828
1829 #endif