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