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