1b536f17bff71e871be8e31584761d3d025447a5
[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 auxiliary 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      getSymbolVersion(const Elf_Shdr *section,
509                                    const Elf_Sym *Symb,
510                                    StringRef &Version,
511                                    bool &IsDefault) const;
512   void VerifyStrTab(const Elf_Shdr *sh) const;
513
514 protected:
515   const Elf_Sym  *getSymbol(DataRefImpl Symb) const; // FIXME: Should be private?
516   void            validateSymbol(DataRefImpl Symb) const;
517
518 public:
519   error_code      getSymbolName(const Elf_Shdr *section,
520                                 const Elf_Sym *Symb,
521                                 StringRef &Res) const;
522   error_code      getSectionName(const Elf_Shdr *section,
523                                  StringRef &Res) const;
524   const Elf_Dyn  *getDyn(DataRefImpl DynData) const;
525   error_code getSymbolVersion(SymbolRef Symb, StringRef &Version,
526                               bool &IsDefault) const;
527 protected:
528   virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
529   virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
530   virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) const;
531   virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const;
532   virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
533   virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const;
534   virtual error_code getSymbolFlags(DataRefImpl Symb, uint32_t &Res) const;
535   virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res) const;
536   virtual error_code getSymbolSection(DataRefImpl Symb,
537                                       section_iterator &Res) const;
538
539   friend class DynRefImpl<target_endianness, is64Bits>;
540   virtual error_code getDynNext(DataRefImpl DynData, DynRef &Result) const;
541
542   virtual error_code getLibraryNext(DataRefImpl Data, LibraryRef &Result) const;
543   virtual error_code getLibraryPath(DataRefImpl Data, StringRef &Res) const;
544
545   virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
546   virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
547   virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
548   virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
549   virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
550   virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const;
551   virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
552   virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
553   virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
554   virtual error_code isSectionRequiredForExecution(DataRefImpl Sec,
555                                                    bool &Res) const;
556   virtual error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const;
557   virtual error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const;
558   virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
559                                            bool &Result) const;
560   virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
561   virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;
562
563   virtual error_code getRelocationNext(DataRefImpl Rel,
564                                        RelocationRef &Res) const;
565   virtual error_code getRelocationAddress(DataRefImpl Rel,
566                                           uint64_t &Res) const;
567   virtual error_code getRelocationOffset(DataRefImpl Rel,
568                                          uint64_t &Res) const;
569   virtual error_code getRelocationSymbol(DataRefImpl Rel,
570                                          SymbolRef &Res) const;
571   virtual error_code getRelocationType(DataRefImpl Rel,
572                                        uint64_t &Res) const;
573   virtual error_code getRelocationTypeName(DataRefImpl Rel,
574                                            SmallVectorImpl<char> &Result) const;
575   virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
576                                                  int64_t &Res) const;
577   virtual error_code getRelocationValueString(DataRefImpl Rel,
578                                            SmallVectorImpl<char> &Result) const;
579
580 public:
581   ELFObjectFile(MemoryBuffer *Object, error_code &ec);
582   virtual symbol_iterator begin_symbols() const;
583   virtual symbol_iterator end_symbols() const;
584
585   virtual symbol_iterator begin_dynamic_symbols() const;
586   virtual symbol_iterator end_dynamic_symbols() const;
587
588   virtual section_iterator begin_sections() const;
589   virtual section_iterator end_sections() const;
590
591   virtual library_iterator begin_libraries_needed() const;
592   virtual library_iterator end_libraries_needed() const;
593
594   virtual dyn_iterator begin_dynamic_table() const;
595   virtual dyn_iterator end_dynamic_table() const;
596
597   virtual uint8_t getBytesInAddress() const;
598   virtual StringRef getFileFormatName() const;
599   virtual StringRef getObjectType() const { return "ELF"; }
600   virtual unsigned getArch() const;
601   virtual StringRef getLoadName() const;
602   virtual error_code getSectionContents(const Elf_Shdr *sec,
603                                         StringRef &Res) const;
604
605   uint64_t getNumSections() const;
606   uint64_t getStringTableIndex() const;
607   ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
608   const Elf_Shdr *getSection(const Elf_Sym *symb) const;
609   const Elf_Shdr *getElfSection(section_iterator &It) const;
610   const Elf_Sym *getElfSymbol(symbol_iterator &It) const;
611
612   // Methods for type inquiry through isa, cast, and dyn_cast
613   bool isDyldType() const { return isDyldELFObject; }
614   static inline bool classof(const Binary *v) {
615     return v->getType() == getELFType(target_endianness == support::little,
616                                       is64Bits);
617   }
618   static inline bool classof(const ELFObjectFile *v) { return true; }
619 };
620
621 // Iterate through the version definitions, and place each Elf_Verdef
622 // in the VersionMap according to its index.
623 template<support::endianness target_endianness, bool is64Bits>
624 void ELFObjectFile<target_endianness, is64Bits>::
625                   LoadVersionDefs(const Elf_Shdr *sec) const {
626   unsigned vd_size = sec->sh_size; // Size of section in bytes
627   unsigned vd_count = sec->sh_info; // Number of Verdef entries
628   const char *sec_start = (const char*)base() + sec->sh_offset;
629   const char *sec_end = sec_start + vd_size;
630   // The first Verdef entry is at the start of the section.
631   const char *p = sec_start;
632   for (unsigned i = 0; i < vd_count; i++) {
633     if (p + sizeof(Elf_Verdef) > sec_end)
634       report_fatal_error("Section ended unexpectedly while scanning "
635                          "version definitions.");
636     const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
637     if (vd->vd_version != ELF::VER_DEF_CURRENT)
638       report_fatal_error("Unexpected verdef version");
639     size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
640     if (index >= VersionMap.size())
641       VersionMap.resize(index+1);
642     VersionMap[index] = VersionMapEntry(vd);
643     p += vd->vd_next;
644   }
645 }
646
647 // Iterate through the versions needed section, and place each Elf_Vernaux
648 // in the VersionMap according to its index.
649 template<support::endianness target_endianness, bool is64Bits>
650 void ELFObjectFile<target_endianness, is64Bits>::
651                   LoadVersionNeeds(const Elf_Shdr *sec) const {
652   unsigned vn_size = sec->sh_size; // Size of section in bytes
653   unsigned vn_count = sec->sh_info; // Number of Verneed entries
654   const char *sec_start = (const char*)base() + sec->sh_offset;
655   const char *sec_end = sec_start + vn_size;
656   // The first Verneed entry is at the start of the section.
657   const char *p = sec_start;
658   for (unsigned i = 0; i < vn_count; i++) {
659     if (p + sizeof(Elf_Verneed) > sec_end)
660       report_fatal_error("Section ended unexpectedly while scanning "
661                          "version needed records.");
662     const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
663     if (vn->vn_version != ELF::VER_NEED_CURRENT)
664       report_fatal_error("Unexpected verneed version");
665     // Iterate through the Vernaux entries
666     const char *paux = p + vn->vn_aux;
667     for (unsigned j = 0; j < vn->vn_cnt; j++) {
668       if (paux + sizeof(Elf_Vernaux) > sec_end)
669         report_fatal_error("Section ended unexpected while scanning auxiliary "
670                            "version needed records.");
671       const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
672       size_t index = vna->vna_other & ELF::VERSYM_VERSION;
673       if (index >= VersionMap.size())
674         VersionMap.resize(index+1);
675       VersionMap[index] = VersionMapEntry(vna);
676       paux += vna->vna_next;
677     }
678     p += vn->vn_next;
679   }
680 }
681
682 template<support::endianness target_endianness, bool is64Bits>
683 void ELFObjectFile<target_endianness, is64Bits>::LoadVersionMap() const {
684   // If there is no dynamic symtab or version table, there is nothing to do.
685   if (SymbolTableSections[0] == NULL || dot_gnu_version_sec == NULL)
686     return;
687
688   // Has the VersionMap already been loaded?
689   if (VersionMap.size() > 0)
690     return;
691
692   // The first two version indexes are reserved.
693   // Index 0 is LOCAL, index 1 is GLOBAL.
694   VersionMap.push_back(VersionMapEntry());
695   VersionMap.push_back(VersionMapEntry());
696
697   if (dot_gnu_version_d_sec)
698     LoadVersionDefs(dot_gnu_version_d_sec);
699
700   if (dot_gnu_version_r_sec)
701     LoadVersionNeeds(dot_gnu_version_r_sec);
702 }
703
704 template<support::endianness target_endianness, bool is64Bits>
705 void ELFObjectFile<target_endianness, is64Bits>
706                   ::validateSymbol(DataRefImpl Symb) const {
707   const Elf_Sym  *symb = getSymbol(Symb);
708   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
709   // FIXME: We really need to do proper error handling in the case of an invalid
710   //        input file. Because we don't use exceptions, I think we'll just pass
711   //        an error object around.
712   if (!(  symb
713         && SymbolTableSection
714         && symb >= (const Elf_Sym*)(base()
715                    + SymbolTableSection->sh_offset)
716         && symb <  (const Elf_Sym*)(base()
717                    + SymbolTableSection->sh_offset
718                    + SymbolTableSection->sh_size)))
719     // FIXME: Proper error handling.
720     report_fatal_error("Symb must point to a valid symbol!");
721 }
722
723 template<support::endianness target_endianness, bool is64Bits>
724 error_code ELFObjectFile<target_endianness, is64Bits>
725                         ::getSymbolNext(DataRefImpl Symb,
726                                         SymbolRef &Result) const {
727   validateSymbol(Symb);
728   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
729
730   ++Symb.d.a;
731   // Check to see if we are at the end of this symbol table.
732   if (Symb.d.a >= SymbolTableSection->getEntityCount()) {
733     // We are at the end. If there are other symbol tables, jump to them.
734     // If the symbol table is .dynsym, we are iterating dynamic symbols,
735     // and there is only one table of these.
736     if (Symb.d.b != 0) {
737       ++Symb.d.b;
738       Symb.d.a = 1; // The 0th symbol in ELF is fake.
739     }
740     // Otherwise return the terminator.
741     if (Symb.d.b == 0 || Symb.d.b >= SymbolTableSections.size()) {
742       Symb.d.a = std::numeric_limits<uint32_t>::max();
743       Symb.d.b = std::numeric_limits<uint32_t>::max();
744     }
745   }
746
747   Result = SymbolRef(Symb, this);
748   return object_error::success;
749 }
750
751 template<support::endianness target_endianness, bool is64Bits>
752 error_code ELFObjectFile<target_endianness, is64Bits>
753                         ::getSymbolName(DataRefImpl Symb,
754                                         StringRef &Result) const {
755   validateSymbol(Symb);
756   const Elf_Sym *symb = getSymbol(Symb);
757   return getSymbolName(SymbolTableSections[Symb.d.b], symb, Result);
758 }
759
760 template<support::endianness target_endianness, bool is64Bits>
761 error_code ELFObjectFile<target_endianness, is64Bits>
762                         ::getSymbolVersion(SymbolRef SymRef,
763                                            StringRef &Version,
764                                            bool &IsDefault) const {
765   DataRefImpl Symb = SymRef.getRawDataRefImpl();
766   validateSymbol(Symb);
767   const Elf_Sym *symb = getSymbol(Symb);
768   return getSymbolVersion(SymbolTableSections[Symb.d.b], symb,
769                           Version, IsDefault);
770 }
771
772 template<support::endianness target_endianness, bool is64Bits>
773 ELF::Elf64_Word ELFObjectFile<target_endianness, is64Bits>
774                       ::getSymbolTableIndex(const Elf_Sym *symb) const {
775   if (symb->st_shndx == ELF::SHN_XINDEX)
776     return ExtendedSymbolTable.lookup(symb);
777   return symb->st_shndx;
778 }
779
780 template<support::endianness target_endianness, bool is64Bits>
781 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
782 ELFObjectFile<target_endianness, is64Bits>
783                              ::getSection(const Elf_Sym *symb) const {
784   if (symb->st_shndx == ELF::SHN_XINDEX)
785     return getSection(ExtendedSymbolTable.lookup(symb));
786   if (symb->st_shndx >= ELF::SHN_LORESERVE)
787     return 0;
788   return getSection(symb->st_shndx);
789 }
790
791 template<support::endianness target_endianness, bool is64Bits>
792 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
793 ELFObjectFile<target_endianness, is64Bits>
794                              ::getElfSection(section_iterator &It) const {
795   llvm::object::DataRefImpl ShdrRef = It->getRawDataRefImpl();
796   return const_cast<Elf_Shdr*>(reinterpret_cast<const Elf_Shdr *>
797                                  (ShdrRef.p));
798 }
799
800 template<support::endianness target_endianness, bool is64Bits>
801 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
802 ELFObjectFile<target_endianness, is64Bits>
803                              ::getElfSymbol(symbol_iterator &It) const {
804   return getSymbol(It->getRawDataRefImpl());
805 }
806
807 template<support::endianness target_endianness, bool is64Bits>
808 error_code ELFObjectFile<target_endianness, is64Bits>
809                         ::getSymbolFileOffset(DataRefImpl Symb,
810                                           uint64_t &Result) const {
811   validateSymbol(Symb);
812   const Elf_Sym  *symb = getSymbol(Symb);
813   const Elf_Shdr *Section;
814   switch (getSymbolTableIndex(symb)) {
815   case ELF::SHN_COMMON:
816    // Unintialized symbols have no offset in the object file
817   case ELF::SHN_UNDEF:
818     Result = UnknownAddressOrSize;
819     return object_error::success;
820   case ELF::SHN_ABS:
821     Result = symb->st_value;
822     return object_error::success;
823   default: Section = getSection(symb);
824   }
825
826   switch (symb->getType()) {
827   case ELF::STT_SECTION:
828     Result = Section ? Section->sh_addr : UnknownAddressOrSize;
829     return object_error::success;
830   case ELF::STT_FUNC:
831   case ELF::STT_OBJECT:
832   case ELF::STT_NOTYPE:
833     Result = symb->st_value +
834              (Section ? Section->sh_offset : 0);
835     return object_error::success;
836   default:
837     Result = UnknownAddressOrSize;
838     return object_error::success;
839   }
840 }
841
842 template<support::endianness target_endianness, bool is64Bits>
843 error_code ELFObjectFile<target_endianness, is64Bits>
844                         ::getSymbolAddress(DataRefImpl Symb,
845                                            uint64_t &Result) const {
846   validateSymbol(Symb);
847   const Elf_Sym  *symb = getSymbol(Symb);
848   const Elf_Shdr *Section;
849   switch (getSymbolTableIndex(symb)) {
850   case ELF::SHN_COMMON:
851   case ELF::SHN_UNDEF:
852     Result = UnknownAddressOrSize;
853     return object_error::success;
854   case ELF::SHN_ABS:
855     Result = symb->st_value;
856     return object_error::success;
857   default: Section = getSection(symb);
858   }
859
860   switch (symb->getType()) {
861   case ELF::STT_SECTION:
862     Result = Section ? Section->sh_addr : UnknownAddressOrSize;
863     return object_error::success;
864   case ELF::STT_FUNC:
865   case ELF::STT_OBJECT:
866   case ELF::STT_NOTYPE:
867     Result = symb->st_value + (Section ? Section->sh_addr : 0);
868     return object_error::success;
869   default:
870     Result = UnknownAddressOrSize;
871     return object_error::success;
872   }
873 }
874
875 template<support::endianness target_endianness, bool is64Bits>
876 error_code ELFObjectFile<target_endianness, is64Bits>
877                         ::getSymbolSize(DataRefImpl Symb,
878                                         uint64_t &Result) const {
879   validateSymbol(Symb);
880   const Elf_Sym  *symb = getSymbol(Symb);
881   if (symb->st_size == 0)
882     Result = UnknownAddressOrSize;
883   Result = symb->st_size;
884   return object_error::success;
885 }
886
887 template<support::endianness target_endianness, bool is64Bits>
888 error_code ELFObjectFile<target_endianness, is64Bits>
889                         ::getSymbolNMTypeChar(DataRefImpl Symb,
890                                               char &Result) const {
891   validateSymbol(Symb);
892   const Elf_Sym  *symb = getSymbol(Symb);
893   const Elf_Shdr *Section = getSection(symb);
894
895   char ret = '?';
896
897   if (Section) {
898     switch (Section->sh_type) {
899     case ELF::SHT_PROGBITS:
900     case ELF::SHT_DYNAMIC:
901       switch (Section->sh_flags) {
902       case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
903         ret = 't'; break;
904       case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
905         ret = 'd'; break;
906       case ELF::SHF_ALLOC:
907       case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
908       case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
909         ret = 'r'; break;
910       }
911       break;
912     case ELF::SHT_NOBITS: ret = 'b';
913     }
914   }
915
916   switch (getSymbolTableIndex(symb)) {
917   case ELF::SHN_UNDEF:
918     if (ret == '?')
919       ret = 'U';
920     break;
921   case ELF::SHN_ABS: ret = 'a'; break;
922   case ELF::SHN_COMMON: ret = 'c'; break;
923   }
924
925   switch (symb->getBinding()) {
926   case ELF::STB_GLOBAL: ret = ::toupper(ret); break;
927   case ELF::STB_WEAK:
928     if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF)
929       ret = 'w';
930     else
931       if (symb->getType() == ELF::STT_OBJECT)
932         ret = 'V';
933       else
934         ret = 'W';
935   }
936
937   if (ret == '?' && symb->getType() == ELF::STT_SECTION) {
938     StringRef name;
939     if (error_code ec = getSymbolName(Symb, name))
940       return ec;
941     Result = StringSwitch<char>(name)
942       .StartsWith(".debug", 'N')
943       .StartsWith(".note", 'n')
944       .Default('?');
945     return object_error::success;
946   }
947
948   Result = ret;
949   return object_error::success;
950 }
951
952 template<support::endianness target_endianness, bool is64Bits>
953 error_code ELFObjectFile<target_endianness, is64Bits>
954                         ::getSymbolType(DataRefImpl Symb,
955                                         SymbolRef::Type &Result) const {
956   validateSymbol(Symb);
957   const Elf_Sym  *symb = getSymbol(Symb);
958
959   switch (symb->getType()) {
960   case ELF::STT_NOTYPE:
961     Result = SymbolRef::ST_Unknown;
962     break;
963   case ELF::STT_SECTION:
964     Result = SymbolRef::ST_Debug;
965     break;
966   case ELF::STT_FILE:
967     Result = SymbolRef::ST_File;
968     break;
969   case ELF::STT_FUNC:
970     Result = SymbolRef::ST_Function;
971     break;
972   case ELF::STT_OBJECT:
973   case ELF::STT_COMMON:
974   case ELF::STT_TLS:
975     Result = SymbolRef::ST_Data;
976     break;
977   default:
978     Result = SymbolRef::ST_Other;
979     break;
980   }
981   return object_error::success;
982 }
983
984 template<support::endianness target_endianness, bool is64Bits>
985 error_code ELFObjectFile<target_endianness, is64Bits>
986                         ::getSymbolFlags(DataRefImpl Symb,
987                                          uint32_t &Result) const {
988   validateSymbol(Symb);
989   const Elf_Sym  *symb = getSymbol(Symb);
990
991   Result = SymbolRef::SF_None;
992
993   if (symb->getBinding() != ELF::STB_LOCAL)
994     Result |= SymbolRef::SF_Global;
995
996   if (symb->getBinding() == ELF::STB_WEAK)
997     Result |= SymbolRef::SF_Weak;
998
999   if (symb->st_shndx == ELF::SHN_ABS)
1000     Result |= SymbolRef::SF_Absolute;
1001
1002   if (symb->getType() == ELF::STT_FILE ||
1003       symb->getType() == ELF::STT_SECTION)
1004     Result |= SymbolRef::SF_FormatSpecific;
1005
1006   if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF)
1007     Result |= SymbolRef::SF_Undefined;
1008
1009   if (symb->getType() == ELF::STT_COMMON ||
1010       getSymbolTableIndex(symb) == ELF::SHN_COMMON)
1011     Result |= SymbolRef::SF_Common;
1012
1013   if (symb->getType() == ELF::STT_TLS)
1014     Result |= SymbolRef::SF_ThreadLocal;
1015
1016   return object_error::success;
1017 }
1018
1019 template<support::endianness target_endianness, bool is64Bits>
1020 error_code ELFObjectFile<target_endianness, is64Bits>
1021                         ::getSymbolSection(DataRefImpl Symb,
1022                                            section_iterator &Res) const {
1023   validateSymbol(Symb);
1024   const Elf_Sym  *symb = getSymbol(Symb);
1025   const Elf_Shdr *sec = getSection(symb);
1026   if (!sec)
1027     Res = end_sections();
1028   else {
1029     DataRefImpl Sec;
1030     Sec.p = reinterpret_cast<intptr_t>(sec);
1031     Res = section_iterator(SectionRef(Sec, this));
1032   }
1033   return object_error::success;
1034 }
1035
1036 template<support::endianness target_endianness, bool is64Bits>
1037 error_code ELFObjectFile<target_endianness, is64Bits>
1038                         ::getSectionNext(DataRefImpl Sec, SectionRef &Result) const {
1039   const uint8_t *sec = reinterpret_cast<const uint8_t *>(Sec.p);
1040   sec += Header->e_shentsize;
1041   Sec.p = reinterpret_cast<intptr_t>(sec);
1042   Result = SectionRef(Sec, this);
1043   return object_error::success;
1044 }
1045
1046 template<support::endianness target_endianness, bool is64Bits>
1047 error_code ELFObjectFile<target_endianness, is64Bits>
1048                         ::getSectionName(DataRefImpl Sec,
1049                                          StringRef &Result) const {
1050   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1051   Result = StringRef(getString(dot_shstrtab_sec, sec->sh_name));
1052   return object_error::success;
1053 }
1054
1055 template<support::endianness target_endianness, bool is64Bits>
1056 error_code ELFObjectFile<target_endianness, is64Bits>
1057                         ::getSectionAddress(DataRefImpl Sec,
1058                                             uint64_t &Result) const {
1059   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1060   Result = sec->sh_addr;
1061   return object_error::success;
1062 }
1063
1064 template<support::endianness target_endianness, bool is64Bits>
1065 error_code ELFObjectFile<target_endianness, is64Bits>
1066                         ::getSectionSize(DataRefImpl Sec,
1067                                          uint64_t &Result) const {
1068   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1069   Result = sec->sh_size;
1070   return object_error::success;
1071 }
1072
1073 template<support::endianness target_endianness, bool is64Bits>
1074 error_code ELFObjectFile<target_endianness, is64Bits>
1075                         ::getSectionContents(DataRefImpl Sec,
1076                                              StringRef &Result) const {
1077   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1078   const char *start = (const char*)base() + sec->sh_offset;
1079   Result = StringRef(start, sec->sh_size);
1080   return object_error::success;
1081 }
1082
1083 template<support::endianness target_endianness, bool is64Bits>
1084 error_code ELFObjectFile<target_endianness, is64Bits>
1085                         ::getSectionContents(const Elf_Shdr *Sec,
1086                                              StringRef &Result) const {
1087   const char *start = (const char*)base() + Sec->sh_offset;
1088   Result = StringRef(start, Sec->sh_size);
1089   return object_error::success;
1090 }
1091
1092 template<support::endianness target_endianness, bool is64Bits>
1093 error_code ELFObjectFile<target_endianness, is64Bits>
1094                         ::getSectionAlignment(DataRefImpl Sec,
1095                                               uint64_t &Result) const {
1096   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1097   Result = sec->sh_addralign;
1098   return object_error::success;
1099 }
1100
1101 template<support::endianness target_endianness, bool is64Bits>
1102 error_code ELFObjectFile<target_endianness, is64Bits>
1103                         ::isSectionText(DataRefImpl Sec,
1104                                         bool &Result) const {
1105   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1106   if (sec->sh_flags & ELF::SHF_EXECINSTR)
1107     Result = true;
1108   else
1109     Result = false;
1110   return object_error::success;
1111 }
1112
1113 template<support::endianness target_endianness, bool is64Bits>
1114 error_code ELFObjectFile<target_endianness, is64Bits>
1115                         ::isSectionData(DataRefImpl Sec,
1116                                         bool &Result) const {
1117   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1118   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
1119       && sec->sh_type == ELF::SHT_PROGBITS)
1120     Result = true;
1121   else
1122     Result = false;
1123   return object_error::success;
1124 }
1125
1126 template<support::endianness target_endianness, bool is64Bits>
1127 error_code ELFObjectFile<target_endianness, is64Bits>
1128                         ::isSectionBSS(DataRefImpl Sec,
1129                                        bool &Result) const {
1130   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1131   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
1132       && sec->sh_type == ELF::SHT_NOBITS)
1133     Result = true;
1134   else
1135     Result = false;
1136   return object_error::success;
1137 }
1138
1139 template<support::endianness target_endianness, bool is64Bits>
1140 error_code ELFObjectFile<target_endianness, is64Bits>
1141                         ::isSectionRequiredForExecution(DataRefImpl Sec,
1142                                                         bool &Result) const {
1143   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1144   if (sec->sh_flags & ELF::SHF_ALLOC)
1145     Result = true;
1146   else
1147     Result = false;
1148   return object_error::success;
1149 }
1150
1151 template<support::endianness target_endianness, bool is64Bits>
1152 error_code ELFObjectFile<target_endianness, is64Bits>
1153                         ::isSectionVirtual(DataRefImpl Sec,
1154                                            bool &Result) const {
1155   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1156   if (sec->sh_type == ELF::SHT_NOBITS)
1157     Result = true;
1158   else
1159     Result = false;
1160   return object_error::success;
1161 }
1162
1163 template<support::endianness target_endianness, bool is64Bits>
1164 error_code ELFObjectFile<target_endianness, is64Bits>::isSectionZeroInit(DataRefImpl Sec,
1165                                             bool &Result) const {
1166   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1167   // For ELF, all zero-init sections are virtual (that is, they occupy no space
1168   //   in the object image) and vice versa.
1169   if (sec->sh_flags & ELF::SHT_NOBITS)
1170     Result = true;
1171   else
1172     Result = false;
1173   return object_error::success;
1174 }
1175
1176 template<support::endianness target_endianness, bool is64Bits>
1177 error_code ELFObjectFile<target_endianness, is64Bits>
1178                           ::sectionContainsSymbol(DataRefImpl Sec,
1179                                                   DataRefImpl Symb,
1180                                                   bool &Result) const {
1181   // FIXME: Unimplemented.
1182   Result = false;
1183   return object_error::success;
1184 }
1185
1186 template<support::endianness target_endianness, bool is64Bits>
1187 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
1188                                  ::getSectionRelBegin(DataRefImpl Sec) const {
1189   DataRefImpl RelData;
1190   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1191   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
1192   if (sec != 0 && ittr != SectionRelocMap.end()) {
1193     RelData.w.a = getSection(ittr->second[0])->sh_info;
1194     RelData.w.b = ittr->second[0];
1195     RelData.w.c = 0;
1196   }
1197   return relocation_iterator(RelocationRef(RelData, this));
1198 }
1199
1200 template<support::endianness target_endianness, bool is64Bits>
1201 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
1202                                  ::getSectionRelEnd(DataRefImpl Sec) const {
1203   DataRefImpl RelData;
1204   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
1205   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
1206   if (sec != 0 && ittr != SectionRelocMap.end()) {
1207     // Get the index of the last relocation section for this section.
1208     std::size_t relocsecindex = ittr->second[ittr->second.size() - 1];
1209     const Elf_Shdr *relocsec = getSection(relocsecindex);
1210     RelData.w.a = relocsec->sh_info;
1211     RelData.w.b = relocsecindex;
1212     RelData.w.c = relocsec->sh_size / relocsec->sh_entsize;
1213   }
1214   return relocation_iterator(RelocationRef(RelData, this));
1215 }
1216
1217 // Relocations
1218 template<support::endianness target_endianness, bool is64Bits>
1219 error_code ELFObjectFile<target_endianness, is64Bits>
1220                         ::getRelocationNext(DataRefImpl Rel,
1221                                             RelocationRef &Result) const {
1222   ++Rel.w.c;
1223   const Elf_Shdr *relocsec = getSection(Rel.w.b);
1224   if (Rel.w.c >= (relocsec->sh_size / relocsec->sh_entsize)) {
1225     // We have reached the end of the relocations for this section. See if there
1226     // is another relocation section.
1227     typename RelocMap_t::mapped_type relocseclist =
1228       SectionRelocMap.lookup(getSection(Rel.w.a));
1229
1230     // Do a binary search for the current reloc section index (which must be
1231     // present). Then get the next one.
1232     typename RelocMap_t::mapped_type::const_iterator loc =
1233       std::lower_bound(relocseclist.begin(), relocseclist.end(), Rel.w.b);
1234     ++loc;
1235
1236     // If there is no next one, don't do anything. The ++Rel.w.c above sets Rel
1237     // to the end iterator.
1238     if (loc != relocseclist.end()) {
1239       Rel.w.b = *loc;
1240       Rel.w.a = 0;
1241     }
1242   }
1243   Result = RelocationRef(Rel, this);
1244   return object_error::success;
1245 }
1246
1247 template<support::endianness target_endianness, bool is64Bits>
1248 error_code ELFObjectFile<target_endianness, is64Bits>
1249                         ::getRelocationSymbol(DataRefImpl Rel,
1250                                               SymbolRef &Result) const {
1251   uint32_t symbolIdx;
1252   const Elf_Shdr *sec = getSection(Rel.w.b);
1253   switch (sec->sh_type) {
1254     default :
1255       report_fatal_error("Invalid section type in Rel!");
1256     case ELF::SHT_REL : {
1257       symbolIdx = getRel(Rel)->getSymbol();
1258       break;
1259     }
1260     case ELF::SHT_RELA : {
1261       symbolIdx = getRela(Rel)->getSymbol();
1262       break;
1263     }
1264   }
1265   DataRefImpl SymbolData;
1266   IndexMap_t::const_iterator it = SymbolTableSectionsIndexMap.find(sec->sh_link);
1267   if (it == SymbolTableSectionsIndexMap.end())
1268     report_fatal_error("Relocation symbol table not found!");
1269   SymbolData.d.a = symbolIdx;
1270   SymbolData.d.b = it->second;
1271   Result = SymbolRef(SymbolData, this);
1272   return object_error::success;
1273 }
1274
1275 template<support::endianness target_endianness, bool is64Bits>
1276 error_code ELFObjectFile<target_endianness, is64Bits>
1277                         ::getRelocationAddress(DataRefImpl Rel,
1278                                                uint64_t &Result) const {
1279   uint64_t offset;
1280   const Elf_Shdr *sec = getSection(Rel.w.b);
1281   switch (sec->sh_type) {
1282     default :
1283       report_fatal_error("Invalid section type in Rel!");
1284     case ELF::SHT_REL : {
1285       offset = getRel(Rel)->r_offset;
1286       break;
1287     }
1288     case ELF::SHT_RELA : {
1289       offset = getRela(Rel)->r_offset;
1290       break;
1291     }
1292   }
1293
1294   Result = offset;
1295   return object_error::success;
1296 }
1297
1298 template<support::endianness target_endianness, bool is64Bits>
1299 error_code ELFObjectFile<target_endianness, is64Bits>
1300                         ::getRelocationOffset(DataRefImpl Rel,
1301                                               uint64_t &Result) const {
1302   uint64_t offset;
1303   const Elf_Shdr *sec = getSection(Rel.w.b);
1304   switch (sec->sh_type) {
1305     default :
1306       report_fatal_error("Invalid section type in Rel!");
1307     case ELF::SHT_REL : {
1308       offset = getRel(Rel)->r_offset;
1309       break;
1310     }
1311     case ELF::SHT_RELA : {
1312       offset = getRela(Rel)->r_offset;
1313       break;
1314     }
1315   }
1316
1317   Result = offset - sec->sh_addr;
1318   return object_error::success;
1319 }
1320
1321 template<support::endianness target_endianness, bool is64Bits>
1322 error_code ELFObjectFile<target_endianness, is64Bits>
1323                         ::getRelocationType(DataRefImpl Rel,
1324                                             uint64_t &Result) const {
1325   const Elf_Shdr *sec = getSection(Rel.w.b);
1326   switch (sec->sh_type) {
1327     default :
1328       report_fatal_error("Invalid section type in Rel!");
1329     case ELF::SHT_REL : {
1330       Result = getRel(Rel)->getType();
1331       break;
1332     }
1333     case ELF::SHT_RELA : {
1334       Result = getRela(Rel)->getType();
1335       break;
1336     }
1337   }
1338   return object_error::success;
1339 }
1340
1341 #define LLVM_ELF_SWITCH_RELOC_TYPE_NAME(enum) \
1342   case ELF::enum: res = #enum; break;
1343
1344 template<support::endianness target_endianness, bool is64Bits>
1345 error_code ELFObjectFile<target_endianness, is64Bits>
1346                         ::getRelocationTypeName(DataRefImpl Rel,
1347                                           SmallVectorImpl<char> &Result) const {
1348   const Elf_Shdr *sec = getSection(Rel.w.b);
1349   uint8_t type;
1350   StringRef res;
1351   switch (sec->sh_type) {
1352     default :
1353       return object_error::parse_failed;
1354     case ELF::SHT_REL : {
1355       type = getRel(Rel)->getType();
1356       break;
1357     }
1358     case ELF::SHT_RELA : {
1359       type = getRela(Rel)->getType();
1360       break;
1361     }
1362   }
1363   switch (Header->e_machine) {
1364   case ELF::EM_X86_64:
1365     switch (type) {
1366       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_NONE);
1367       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_64);
1368       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC32);
1369       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOT32);
1370       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PLT32);
1371       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_COPY);
1372       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GLOB_DAT);
1373       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_JUMP_SLOT);
1374       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_RELATIVE);
1375       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPCREL);
1376       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32);
1377       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32S);
1378       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_16);
1379       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC16);
1380       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_8);
1381       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC8);
1382       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPMOD64);
1383       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF64);
1384       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF64);
1385       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSGD);
1386       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSLD);
1387       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF32);
1388       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTTPOFF);
1389       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF32);
1390       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC64);
1391       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTOFF64);
1392       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32);
1393       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE32);
1394       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE64);
1395       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32_TLSDESC);
1396       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC_CALL);
1397       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC);
1398     default:
1399       res = "Unknown";
1400     }
1401     break;
1402   case ELF::EM_386:
1403     switch (type) {
1404       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_NONE);
1405       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32);
1406       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC32);
1407       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOT32);
1408       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PLT32);
1409       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_COPY);
1410       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GLOB_DAT);
1411       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_JUMP_SLOT);
1412       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_RELATIVE);
1413       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTOFF);
1414       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTPC);
1415       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32PLT);
1416       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF);
1417       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE);
1418       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTIE);
1419       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE);
1420       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD);
1421       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM);
1422       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_16);
1423       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC16);
1424       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_8);
1425       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC8);
1426       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_32);
1427       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_PUSH);
1428       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_CALL);
1429       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_POP);
1430       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_32);
1431       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_PUSH);
1432       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_CALL);
1433       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_POP);
1434       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDO_32);
1435       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE_32);
1436       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE_32);
1437       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPMOD32);
1438       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPOFF32);
1439       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF32);
1440       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTDESC);
1441       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC_CALL);
1442       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC);
1443       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_IRELATIVE);
1444     default:
1445       res = "Unknown";
1446     }
1447     break;
1448   case ELF::EM_HEXAGON:
1449     switch (type) {
1450       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_NONE);
1451       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B22_PCREL);
1452       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B15_PCREL);
1453       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B7_PCREL);
1454       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_LO16);
1455       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_HI16);
1456       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_32);
1457       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_16);
1458       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_8);
1459       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GPREL16_0);
1460       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GPREL16_1);
1461       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GPREL16_2);
1462       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GPREL16_3);
1463       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_HL16);
1464       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B13_PCREL);
1465       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B9_PCREL);
1466       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B32_PCREL_X);
1467       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_32_6_X);
1468       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B22_PCREL_X);
1469       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B15_PCREL_X);
1470       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B13_PCREL_X);
1471       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B9_PCREL_X);
1472       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_B7_PCREL_X);
1473       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_16_X);
1474       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_12_X);
1475       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_11_X);
1476       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_10_X);
1477       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_9_X);
1478       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_8_X);
1479       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_7_X);
1480       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_6_X);
1481       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_32_PCREL);
1482       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_COPY);
1483       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GLOB_DAT);
1484       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_JMP_SLOT);
1485       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_RELATIVE);
1486       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_PLT_B22_PCREL);
1487       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_LO16);
1488       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_HI16);
1489       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_32);
1490       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_LO16);
1491       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_HI16);
1492       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_32);
1493       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_16);
1494       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPMOD_32);
1495       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_LO16);
1496       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_HI16);
1497       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_32);
1498       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_16);
1499       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_PLT_B22_PCREL);
1500       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_LO16);
1501       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_HI16);
1502       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_32);
1503       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_16);
1504       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_LO16);
1505       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_HI16);
1506       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_32);
1507       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_LO16);
1508       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_HI16);
1509       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_32);
1510       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_16);
1511       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_LO16);
1512       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_HI16);
1513       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_32);
1514       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_16);
1515       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_6_PCREL_X);
1516       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_32_6_X);
1517       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_16_X);
1518       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOTREL_11_X);
1519       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_32_6_X);
1520       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_16_X);
1521       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GOT_11_X);
1522       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_32_6_X);
1523       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_16_X);
1524       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_DTPREL_11_X);
1525       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_32_6_X);
1526       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_16_X);
1527       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_GD_GOT_11_X);
1528       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_32_6_X);
1529       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_16_X);
1530       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_32_6_X);
1531       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_16_X);
1532       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_IE_GOT_11_X);
1533       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_32_6_X);
1534       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_16_X);
1535       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_HEX_TPREL_11_X);
1536     default:
1537       res = "Unknown";
1538     }
1539     break;
1540   default:
1541     res = "Unknown";
1542   }
1543   Result.append(res.begin(), res.end());
1544   return object_error::success;
1545 }
1546
1547 #undef LLVM_ELF_SWITCH_RELOC_TYPE_NAME
1548
1549 template<support::endianness target_endianness, bool is64Bits>
1550 error_code ELFObjectFile<target_endianness, is64Bits>
1551                         ::getRelocationAdditionalInfo(DataRefImpl Rel,
1552                                                       int64_t &Result) const {
1553   const Elf_Shdr *sec = getSection(Rel.w.b);
1554   switch (sec->sh_type) {
1555     default :
1556       report_fatal_error("Invalid section type in Rel!");
1557     case ELF::SHT_REL : {
1558       Result = 0;
1559       return object_error::success;
1560     }
1561     case ELF::SHT_RELA : {
1562       Result = getRela(Rel)->r_addend;
1563       return object_error::success;
1564     }
1565   }
1566 }
1567
1568 template<support::endianness target_endianness, bool is64Bits>
1569 error_code ELFObjectFile<target_endianness, is64Bits>
1570                         ::getRelocationValueString(DataRefImpl Rel,
1571                                           SmallVectorImpl<char> &Result) const {
1572   const Elf_Shdr *sec = getSection(Rel.w.b);
1573   uint8_t type;
1574   StringRef res;
1575   int64_t addend = 0;
1576   uint16_t symbol_index = 0;
1577   switch (sec->sh_type) {
1578     default :
1579       return object_error::parse_failed;
1580     case ELF::SHT_REL : {
1581       type = getRel(Rel)->getType();
1582       symbol_index = getRel(Rel)->getSymbol();
1583       // TODO: Read implicit addend from section data.
1584       break;
1585     }
1586     case ELF::SHT_RELA : {
1587       type = getRela(Rel)->getType();
1588       symbol_index = getRela(Rel)->getSymbol();
1589       addend = getRela(Rel)->r_addend;
1590       break;
1591     }
1592   }
1593   const Elf_Sym *symb = getEntry<Elf_Sym>(sec->sh_link, symbol_index);
1594   StringRef symname;
1595   if (error_code ec = getSymbolName(getSection(sec->sh_link), symb, symname))
1596     return ec;
1597   switch (Header->e_machine) {
1598   case ELF::EM_X86_64:
1599     switch (type) {
1600     case ELF::R_X86_64_32S:
1601       res = symname;
1602       break;
1603     case ELF::R_X86_64_PC32: {
1604         std::string fmtbuf;
1605         raw_string_ostream fmt(fmtbuf);
1606         fmt << symname << (addend < 0 ? "" : "+") << addend << "-P";
1607         fmt.flush();
1608         Result.append(fmtbuf.begin(), fmtbuf.end());
1609       }
1610       break;
1611     default:
1612       res = "Unknown";
1613     }
1614     break;
1615   case ELF::EM_HEXAGON:
1616     res = symname;
1617     break;
1618   default:
1619     res = "Unknown";
1620   }
1621   if (Result.empty())
1622     Result.append(res.begin(), res.end());
1623   return object_error::success;
1624 }
1625
1626 // Verify that the last byte in the string table in a null.
1627 template<support::endianness target_endianness, bool is64Bits>
1628 void ELFObjectFile<target_endianness, is64Bits>
1629                   ::VerifyStrTab(const Elf_Shdr *sh) const {
1630   const char *strtab = (const char*)base() + sh->sh_offset;
1631   if (strtab[sh->sh_size - 1] != 0)
1632     // FIXME: Proper error handling.
1633     report_fatal_error("String table must end with a null terminator!");
1634 }
1635
1636 template<support::endianness target_endianness, bool is64Bits>
1637 ELFObjectFile<target_endianness, is64Bits>::ELFObjectFile(MemoryBuffer *Object
1638                                                           , error_code &ec)
1639   : ObjectFile(getELFType(target_endianness == support::little, is64Bits),
1640                Object, ec)
1641   , isDyldELFObject(false)
1642   , SectionHeaderTable(0)
1643   , dot_shstrtab_sec(0)
1644   , dot_strtab_sec(0)
1645   , dot_dynstr_sec(0)
1646   , dot_dynamic_sec(0)
1647   , dot_gnu_version_sec(0)
1648   , dot_gnu_version_r_sec(0)
1649   , dot_gnu_version_d_sec(0)
1650   , dt_soname(0)
1651  {
1652
1653   const uint64_t FileSize = Data->getBufferSize();
1654
1655   if (sizeof(Elf_Ehdr) > FileSize)
1656     // FIXME: Proper error handling.
1657     report_fatal_error("File too short!");
1658
1659   Header = reinterpret_cast<const Elf_Ehdr *>(base());
1660
1661   if (Header->e_shoff == 0)
1662     return;
1663
1664   const uint64_t SectionTableOffset = Header->e_shoff;
1665
1666   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
1667     // FIXME: Proper error handling.
1668     report_fatal_error("Section header table goes past end of file!");
1669
1670   // The getNumSections() call below depends on SectionHeaderTable being set.
1671   SectionHeaderTable =
1672     reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
1673   const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
1674
1675   if (SectionTableOffset + SectionTableSize > FileSize)
1676     // FIXME: Proper error handling.
1677     report_fatal_error("Section table goes past end of file!");
1678
1679   // To find the symbol tables we walk the section table to find SHT_SYMTAB.
1680   const Elf_Shdr* SymbolTableSectionHeaderIndex = 0;
1681   const Elf_Shdr* sh = SectionHeaderTable;
1682
1683   // Reserve SymbolTableSections[0] for .dynsym
1684   SymbolTableSections.push_back(NULL);
1685
1686   for (uint64_t i = 0, e = getNumSections(); i != e; ++i) {
1687     switch (sh->sh_type) {
1688     case ELF::SHT_SYMTAB_SHNDX: {
1689       if (SymbolTableSectionHeaderIndex)
1690         // FIXME: Proper error handling.
1691         report_fatal_error("More than one .symtab_shndx!");
1692       SymbolTableSectionHeaderIndex = sh;
1693       break;
1694     }
1695     case ELF::SHT_SYMTAB: {
1696       SymbolTableSectionsIndexMap[i] = SymbolTableSections.size();
1697       SymbolTableSections.push_back(sh);
1698       break;
1699     }
1700     case ELF::SHT_DYNSYM: {
1701       if (SymbolTableSections[0] != NULL)
1702         // FIXME: Proper error handling.
1703         report_fatal_error("More than one .dynsym!");
1704       SymbolTableSectionsIndexMap[i] = 0;
1705       SymbolTableSections[0] = sh;
1706       break;
1707     }
1708     case ELF::SHT_REL:
1709     case ELF::SHT_RELA: {
1710       SectionRelocMap[getSection(sh->sh_info)].push_back(i);
1711       break;
1712     }
1713     case ELF::SHT_DYNAMIC: {
1714       if (dot_dynamic_sec != NULL)
1715         // FIXME: Proper error handling.
1716         report_fatal_error("More than one .dynamic!");
1717       dot_dynamic_sec = sh;
1718       break;
1719     }
1720     case ELF::SHT_GNU_versym: {
1721       if (dot_gnu_version_sec != NULL)
1722         // FIXME: Proper error handling.
1723         report_fatal_error("More than one .gnu.version section!");
1724       dot_gnu_version_sec = sh;
1725       break;
1726     }
1727     case ELF::SHT_GNU_verdef: {
1728       if (dot_gnu_version_d_sec != NULL)
1729         // FIXME: Proper error handling.
1730         report_fatal_error("More than one .gnu.version_d section!");
1731       dot_gnu_version_d_sec = sh;
1732       break;
1733     }
1734     case ELF::SHT_GNU_verneed: {
1735       if (dot_gnu_version_r_sec != NULL)
1736         // FIXME: Proper error handling.
1737         report_fatal_error("More than one .gnu.version_r section!");
1738       dot_gnu_version_r_sec = sh;
1739       break;
1740     }
1741     }
1742     ++sh;
1743   }
1744
1745   // Sort section relocation lists by index.
1746   for (typename RelocMap_t::iterator i = SectionRelocMap.begin(),
1747                                      e = SectionRelocMap.end(); i != e; ++i) {
1748     std::sort(i->second.begin(), i->second.end());
1749   }
1750
1751   // Get string table sections.
1752   dot_shstrtab_sec = getSection(getStringTableIndex());
1753   if (dot_shstrtab_sec) {
1754     // Verify that the last byte in the string table in a null.
1755     VerifyStrTab(dot_shstrtab_sec);
1756   }
1757
1758   // Merge this into the above loop.
1759   for (const char *i = reinterpret_cast<const char *>(SectionHeaderTable),
1760                   *e = i + getNumSections() * Header->e_shentsize;
1761                    i != e; i += Header->e_shentsize) {
1762     const Elf_Shdr *sh = reinterpret_cast<const Elf_Shdr*>(i);
1763     if (sh->sh_type == ELF::SHT_STRTAB) {
1764       StringRef SectionName(getString(dot_shstrtab_sec, sh->sh_name));
1765       if (SectionName == ".strtab") {
1766         if (dot_strtab_sec != 0)
1767           // FIXME: Proper error handling.
1768           report_fatal_error("Already found section named .strtab!");
1769         dot_strtab_sec = sh;
1770         VerifyStrTab(dot_strtab_sec);
1771       } else if (SectionName == ".dynstr") {
1772         if (dot_dynstr_sec != 0)
1773           // FIXME: Proper error handling.
1774           report_fatal_error("Already found section named .dynstr!");
1775         dot_dynstr_sec = sh;
1776         VerifyStrTab(dot_dynstr_sec);
1777       }
1778     }
1779   }
1780
1781   // Build symbol name side-mapping if there is one.
1782   if (SymbolTableSectionHeaderIndex) {
1783     const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
1784                                       SymbolTableSectionHeaderIndex->sh_offset);
1785     error_code ec;
1786     for (symbol_iterator si = begin_symbols(),
1787                          se = end_symbols(); si != se; si.increment(ec)) {
1788       if (ec)
1789         report_fatal_error("Fewer extended symbol table entries than symbols!");
1790       if (*ShndxTable != ELF::SHN_UNDEF)
1791         ExtendedSymbolTable[getSymbol(si->getRawDataRefImpl())] = *ShndxTable;
1792       ++ShndxTable;
1793     }
1794   }
1795 }
1796
1797 template<support::endianness target_endianness, bool is64Bits>
1798 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1799                              ::begin_symbols() const {
1800   DataRefImpl SymbolData;
1801   if (SymbolTableSections.size() <= 1) {
1802     SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1803     SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1804   } else {
1805     SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
1806     SymbolData.d.b = 1; // The 0th table is .dynsym
1807   }
1808   return symbol_iterator(SymbolRef(SymbolData, this));
1809 }
1810
1811 template<support::endianness target_endianness, bool is64Bits>
1812 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1813                              ::end_symbols() const {
1814   DataRefImpl SymbolData;
1815   SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1816   SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1817   return symbol_iterator(SymbolRef(SymbolData, this));
1818 }
1819
1820 template<support::endianness target_endianness, bool is64Bits>
1821 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1822                              ::begin_dynamic_symbols() const {
1823   DataRefImpl SymbolData;
1824   if (SymbolTableSections[0] == NULL) {
1825     SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1826     SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1827   } else {
1828     SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
1829     SymbolData.d.b = 0; // The 0th table is .dynsym
1830   }
1831   return symbol_iterator(SymbolRef(SymbolData, this));
1832 }
1833
1834 template<support::endianness target_endianness, bool is64Bits>
1835 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1836                              ::end_dynamic_symbols() const {
1837   DataRefImpl SymbolData;
1838   SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1839   SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1840   return symbol_iterator(SymbolRef(SymbolData, this));
1841 }
1842
1843 template<support::endianness target_endianness, bool is64Bits>
1844 section_iterator ELFObjectFile<target_endianness, is64Bits>
1845                               ::begin_sections() const {
1846   DataRefImpl ret;
1847   ret.p = reinterpret_cast<intptr_t>(base() + Header->e_shoff);
1848   return section_iterator(SectionRef(ret, this));
1849 }
1850
1851 template<support::endianness target_endianness, bool is64Bits>
1852 section_iterator ELFObjectFile<target_endianness, is64Bits>
1853                               ::end_sections() const {
1854   DataRefImpl ret;
1855   ret.p = reinterpret_cast<intptr_t>(base()
1856                                      + Header->e_shoff
1857                                      + (Header->e_shentsize*getNumSections()));
1858   return section_iterator(SectionRef(ret, this));
1859 }
1860
1861 template<support::endianness target_endianness, bool is64Bits>
1862 typename ELFObjectFile<target_endianness, is64Bits>::dyn_iterator
1863 ELFObjectFile<target_endianness, is64Bits>::begin_dynamic_table() const {
1864   DataRefImpl DynData;
1865   if (dot_dynamic_sec == NULL || dot_dynamic_sec->sh_size == 0) {
1866     DynData.d.a = std::numeric_limits<uint32_t>::max();
1867   } else {
1868     DynData.d.a = 0;
1869   }
1870   return dyn_iterator(DynRef(DynData, this));
1871 }
1872
1873 template<support::endianness target_endianness, bool is64Bits>
1874 typename ELFObjectFile<target_endianness, is64Bits>::dyn_iterator
1875 ELFObjectFile<target_endianness, is64Bits>
1876                           ::end_dynamic_table() const {
1877   DataRefImpl DynData;
1878   DynData.d.a = std::numeric_limits<uint32_t>::max();
1879   return dyn_iterator(DynRef(DynData, this));
1880 }
1881
1882 template<support::endianness target_endianness, bool is64Bits>
1883 error_code ELFObjectFile<target_endianness, is64Bits>
1884                         ::getDynNext(DataRefImpl DynData,
1885                                      DynRef &Result) const {
1886   ++DynData.d.a;
1887
1888   // Check to see if we are at the end of .dynamic
1889   if (DynData.d.a >= dot_dynamic_sec->getEntityCount()) {
1890     // We are at the end. Return the terminator.
1891     DynData.d.a = std::numeric_limits<uint32_t>::max();
1892   }
1893
1894   Result = DynRef(DynData, this);
1895   return object_error::success;
1896 }
1897
1898 template<support::endianness target_endianness, bool is64Bits>
1899 StringRef
1900 ELFObjectFile<target_endianness, is64Bits>::getLoadName() const {
1901   if (!dt_soname) {
1902     // Find the DT_SONAME entry
1903     dyn_iterator it = begin_dynamic_table();
1904     dyn_iterator ie = end_dynamic_table();
1905     error_code ec;
1906     while (it != ie) {
1907       if (it->getTag() == ELF::DT_SONAME)
1908         break;
1909       it.increment(ec);
1910       if (ec)
1911         report_fatal_error("dynamic table iteration failed");
1912     }
1913     if (it != ie) {
1914       if (dot_dynstr_sec == NULL)
1915         report_fatal_error("Dynamic string table is missing");
1916       dt_soname = getString(dot_dynstr_sec, it->getVal());
1917     } else {
1918       dt_soname = "";
1919     }
1920   }
1921   return dt_soname;
1922 }
1923
1924 template<support::endianness target_endianness, bool is64Bits>
1925 library_iterator ELFObjectFile<target_endianness, is64Bits>
1926                              ::begin_libraries_needed() const {
1927   // Find the first DT_NEEDED entry
1928   dyn_iterator i = begin_dynamic_table();
1929   dyn_iterator e = end_dynamic_table();
1930   error_code ec;
1931   while (i != e) {
1932     if (i->getTag() == ELF::DT_NEEDED)
1933       break;
1934     i.increment(ec);
1935     if (ec)
1936       report_fatal_error("dynamic table iteration failed");
1937   }
1938   // Use the same DataRefImpl format as DynRef.
1939   return library_iterator(LibraryRef(i->getRawDataRefImpl(), this));
1940 }
1941
1942 template<support::endianness target_endianness, bool is64Bits>
1943 error_code ELFObjectFile<target_endianness, is64Bits>
1944                         ::getLibraryNext(DataRefImpl Data,
1945                                          LibraryRef &Result) const {
1946   // Use the same DataRefImpl format as DynRef.
1947   dyn_iterator i = dyn_iterator(DynRef(Data, this));
1948   dyn_iterator e = end_dynamic_table();
1949
1950   // Skip the current dynamic table entry.
1951   error_code ec;
1952   if (i != e) {
1953     i.increment(ec);
1954     // TODO: proper error handling
1955     if (ec)
1956       report_fatal_error("dynamic table iteration failed");
1957   }
1958
1959   // Find the next DT_NEEDED entry.
1960   while (i != e) {
1961     if (i->getTag() == ELF::DT_NEEDED)
1962       break;
1963     i.increment(ec);
1964     if (ec)
1965       report_fatal_error("dynamic table iteration failed");
1966   }
1967   Result = LibraryRef(i->getRawDataRefImpl(), this);
1968   return object_error::success;
1969 }
1970
1971 template<support::endianness target_endianness, bool is64Bits>
1972 error_code ELFObjectFile<target_endianness, is64Bits>
1973          ::getLibraryPath(DataRefImpl Data, StringRef &Res) const {
1974   dyn_iterator i = dyn_iterator(DynRef(Data, this));
1975   if (i == end_dynamic_table())
1976     report_fatal_error("getLibraryPath() called on iterator end");
1977
1978   if (i->getTag() != ELF::DT_NEEDED)
1979     report_fatal_error("Invalid library_iterator");
1980
1981   // This uses .dynstr to lookup the name of the DT_NEEDED entry.
1982   // THis works as long as DT_STRTAB == .dynstr. This is true most of
1983   // the time, but the specification allows exceptions.
1984   // TODO: This should really use DT_STRTAB instead. Doing this requires
1985   // reading the program headers.
1986   if (dot_dynstr_sec == NULL)
1987     report_fatal_error("Dynamic string table is missing");
1988   Res = getString(dot_dynstr_sec, i->getVal());
1989   return object_error::success;
1990 }
1991
1992 template<support::endianness target_endianness, bool is64Bits>
1993 library_iterator ELFObjectFile<target_endianness, is64Bits>
1994                              ::end_libraries_needed() const {
1995   dyn_iterator e = end_dynamic_table();
1996   // Use the same DataRefImpl format as DynRef.
1997   return library_iterator(LibraryRef(e->getRawDataRefImpl(), this));
1998 }
1999
2000 template<support::endianness target_endianness, bool is64Bits>
2001 uint8_t ELFObjectFile<target_endianness, is64Bits>::getBytesInAddress() const {
2002   return is64Bits ? 8 : 4;
2003 }
2004
2005 template<support::endianness target_endianness, bool is64Bits>
2006 StringRef ELFObjectFile<target_endianness, is64Bits>
2007                        ::getFileFormatName() const {
2008   switch(Header->e_ident[ELF::EI_CLASS]) {
2009   case ELF::ELFCLASS32:
2010     switch(Header->e_machine) {
2011     case ELF::EM_386:
2012       return "ELF32-i386";
2013     case ELF::EM_X86_64:
2014       return "ELF32-x86-64";
2015     case ELF::EM_ARM:
2016       return "ELF32-arm";
2017     case ELF::EM_HEXAGON:
2018       return "ELF32-hexagon";
2019     default:
2020       return "ELF32-unknown";
2021     }
2022   case ELF::ELFCLASS64:
2023     switch(Header->e_machine) {
2024     case ELF::EM_386:
2025       return "ELF64-i386";
2026     case ELF::EM_X86_64:
2027       return "ELF64-x86-64";
2028     default:
2029       return "ELF64-unknown";
2030     }
2031   default:
2032     // FIXME: Proper error handling.
2033     report_fatal_error("Invalid ELFCLASS!");
2034   }
2035 }
2036
2037 template<support::endianness target_endianness, bool is64Bits>
2038 unsigned ELFObjectFile<target_endianness, is64Bits>::getArch() const {
2039   switch(Header->e_machine) {
2040   case ELF::EM_386:
2041     return Triple::x86;
2042   case ELF::EM_X86_64:
2043     return Triple::x86_64;
2044   case ELF::EM_ARM:
2045     return Triple::arm;
2046   case ELF::EM_HEXAGON:
2047     return Triple::hexagon;
2048   default:
2049     return Triple::UnknownArch;
2050   }
2051 }
2052
2053 template<support::endianness target_endianness, bool is64Bits>
2054 uint64_t ELFObjectFile<target_endianness, is64Bits>::getNumSections() const {
2055   assert(Header && "Header not initialized!");
2056   if (Header->e_shnum == ELF::SHN_UNDEF) {
2057     assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
2058     return SectionHeaderTable->sh_size;
2059   }
2060   return Header->e_shnum;
2061 }
2062
2063 template<support::endianness target_endianness, bool is64Bits>
2064 uint64_t
2065 ELFObjectFile<target_endianness, is64Bits>::getStringTableIndex() const {
2066   if (Header->e_shnum == ELF::SHN_UNDEF) {
2067     if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
2068       return SectionHeaderTable->sh_link;
2069     if (Header->e_shstrndx >= getNumSections())
2070       return 0;
2071   }
2072   return Header->e_shstrndx;
2073 }
2074
2075
2076 template<support::endianness target_endianness, bool is64Bits>
2077 template<typename T>
2078 inline const T *
2079 ELFObjectFile<target_endianness, is64Bits>::getEntry(uint16_t Section,
2080                                                      uint32_t Entry) const {
2081   return getEntry<T>(getSection(Section), Entry);
2082 }
2083
2084 template<support::endianness target_endianness, bool is64Bits>
2085 template<typename T>
2086 inline const T *
2087 ELFObjectFile<target_endianness, is64Bits>::getEntry(const Elf_Shdr * Section,
2088                                                      uint32_t Entry) const {
2089   return reinterpret_cast<const T *>(
2090            base()
2091            + Section->sh_offset
2092            + (Entry * Section->sh_entsize));
2093 }
2094
2095 template<support::endianness target_endianness, bool is64Bits>
2096 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
2097 ELFObjectFile<target_endianness, is64Bits>::getSymbol(DataRefImpl Symb) const {
2098   return getEntry<Elf_Sym>(SymbolTableSections[Symb.d.b], Symb.d.a);
2099 }
2100
2101 template<support::endianness target_endianness, bool is64Bits>
2102 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Dyn *
2103 ELFObjectFile<target_endianness, is64Bits>::getDyn(DataRefImpl DynData) const {
2104   return getEntry<Elf_Dyn>(dot_dynamic_sec, DynData.d.a);
2105 }
2106
2107 template<support::endianness target_endianness, bool is64Bits>
2108 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rel *
2109 ELFObjectFile<target_endianness, is64Bits>::getRel(DataRefImpl Rel) const {
2110   return getEntry<Elf_Rel>(Rel.w.b, Rel.w.c);
2111 }
2112
2113 template<support::endianness target_endianness, bool is64Bits>
2114 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rela *
2115 ELFObjectFile<target_endianness, is64Bits>::getRela(DataRefImpl Rela) const {
2116   return getEntry<Elf_Rela>(Rela.w.b, Rela.w.c);
2117 }
2118
2119 template<support::endianness target_endianness, bool is64Bits>
2120 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
2121 ELFObjectFile<target_endianness, is64Bits>::getSection(DataRefImpl Symb) const {
2122   const Elf_Shdr *sec = getSection(Symb.d.b);
2123   if (sec->sh_type != ELF::SHT_SYMTAB || sec->sh_type != ELF::SHT_DYNSYM)
2124     // FIXME: Proper error handling.
2125     report_fatal_error("Invalid symbol table section!");
2126   return sec;
2127 }
2128
2129 template<support::endianness target_endianness, bool is64Bits>
2130 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
2131 ELFObjectFile<target_endianness, is64Bits>::getSection(uint32_t index) const {
2132   if (index == 0)
2133     return 0;
2134   if (!SectionHeaderTable || index >= getNumSections())
2135     // FIXME: Proper error handling.
2136     report_fatal_error("Invalid section index!");
2137
2138   return reinterpret_cast<const Elf_Shdr *>(
2139          reinterpret_cast<const char *>(SectionHeaderTable)
2140          + (index * Header->e_shentsize));
2141 }
2142
2143 template<support::endianness target_endianness, bool is64Bits>
2144 const char *ELFObjectFile<target_endianness, is64Bits>
2145                          ::getString(uint32_t section,
2146                                      ELF::Elf32_Word offset) const {
2147   return getString(getSection(section), offset);
2148 }
2149
2150 template<support::endianness target_endianness, bool is64Bits>
2151 const char *ELFObjectFile<target_endianness, is64Bits>
2152                          ::getString(const Elf_Shdr *section,
2153                                      ELF::Elf32_Word offset) const {
2154   assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
2155   if (offset >= section->sh_size)
2156     // FIXME: Proper error handling.
2157     report_fatal_error("Symbol name offset outside of string table!");
2158   return (const char *)base() + section->sh_offset + offset;
2159 }
2160
2161 template<support::endianness target_endianness, bool is64Bits>
2162 error_code ELFObjectFile<target_endianness, is64Bits>
2163                         ::getSymbolName(const Elf_Shdr *section,
2164                                         const Elf_Sym *symb,
2165                                         StringRef &Result) const {
2166   if (symb->st_name == 0) {
2167     const Elf_Shdr *section = getSection(symb);
2168     if (!section)
2169       Result = "";
2170     else
2171       Result = getString(dot_shstrtab_sec, section->sh_name);
2172     return object_error::success;
2173   }
2174
2175   if (section == SymbolTableSections[0]) {
2176     // Symbol is in .dynsym, use .dynstr string table
2177     Result = getString(dot_dynstr_sec, symb->st_name);
2178   } else {
2179     // Use the default symbol table name section.
2180     Result = getString(dot_strtab_sec, symb->st_name);
2181   }
2182   return object_error::success;
2183 }
2184
2185 template<support::endianness target_endianness, bool is64Bits>
2186 error_code ELFObjectFile<target_endianness, is64Bits>
2187                         ::getSectionName(const Elf_Shdr *section,
2188                                         StringRef &Result) const {
2189   Result = StringRef(getString(dot_shstrtab_sec, section->sh_name));
2190   return object_error::success;
2191 }
2192
2193 template<support::endianness target_endianness, bool is64Bits>
2194 error_code ELFObjectFile<target_endianness, is64Bits>
2195                         ::getSymbolVersion(const Elf_Shdr *section,
2196                                            const Elf_Sym *symb,
2197                                            StringRef &Version,
2198                                            bool &IsDefault) const {
2199   // Handle non-dynamic symbols.
2200   if (section != SymbolTableSections[0]) {
2201     // Non-dynamic symbols can have versions in their names
2202     // A name of the form 'foo@V1' indicates version 'V1', non-default.
2203     // A name of the form 'foo@@V2' indicates version 'V2', default version.
2204     StringRef Name;
2205     error_code ec = getSymbolName(section, symb, Name);
2206     if (ec != object_error::success)
2207       return ec;
2208     size_t atpos = Name.find('@');
2209     if (atpos == StringRef::npos) {
2210       Version = "";
2211       IsDefault = false;
2212       return object_error::success;
2213     }
2214     ++atpos;
2215     if (atpos < Name.size() && Name[atpos] == '@') {
2216       IsDefault = true;
2217       ++atpos;
2218     } else {
2219       IsDefault = false;
2220     }
2221     Version = Name.substr(atpos);
2222     return object_error::success;
2223   }
2224
2225   // This is a dynamic symbol. Look in the GNU symbol version table.
2226   if (dot_gnu_version_sec == NULL) {
2227     // No version table.
2228     Version = "";
2229     IsDefault = false;
2230     return object_error::success;
2231   }
2232
2233   // Determine the position in the symbol table of this entry.
2234   const char *sec_start = (const char*)base() + section->sh_offset;
2235   size_t entry_index = ((const char*)symb - sec_start)/section->sh_entsize;
2236
2237   // Get the corresponding version index entry
2238   const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
2239   size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
2240
2241   // Special markers for unversioned symbols.
2242   if (version_index == ELF::VER_NDX_LOCAL ||
2243       version_index == ELF::VER_NDX_GLOBAL) {
2244     Version = "";
2245     IsDefault = false;
2246     return object_error::success;
2247   }
2248
2249   // Lookup this symbol in the version table
2250   LoadVersionMap();
2251   if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
2252     report_fatal_error("Symbol has version index without corresponding "
2253                        "define or reference entry");
2254   const VersionMapEntry &entry = VersionMap[version_index];
2255
2256   // Get the version name string
2257   size_t name_offset;
2258   if (entry.isVerdef()) {
2259     // The first Verdaux entry holds the name.
2260     name_offset = entry.getVerdef()->getAux()->vda_name;
2261   } else {
2262     name_offset = entry.getVernaux()->vna_name;
2263   }
2264   Version = getString(dot_dynstr_sec, name_offset);
2265
2266   // Set IsDefault
2267   if (entry.isVerdef()) {
2268     IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
2269   } else {
2270     IsDefault = false;
2271   }
2272
2273   return object_error::success;
2274 }
2275
2276 template<support::endianness target_endianness, bool is64Bits>
2277 inline DynRefImpl<target_endianness, is64Bits>
2278                  ::DynRefImpl(DataRefImpl DynP, const OwningType *Owner)
2279   : DynPimpl(DynP)
2280   , OwningObject(Owner) {}
2281
2282 template<support::endianness target_endianness, bool is64Bits>
2283 inline bool DynRefImpl<target_endianness, is64Bits>
2284                       ::operator==(const DynRefImpl &Other) const {
2285   return DynPimpl == Other.DynPimpl;
2286 }
2287
2288 template<support::endianness target_endianness, bool is64Bits>
2289 inline bool DynRefImpl<target_endianness, is64Bits>
2290                       ::operator <(const DynRefImpl &Other) const {
2291   return DynPimpl < Other.DynPimpl;
2292 }
2293
2294 template<support::endianness target_endianness, bool is64Bits>
2295 inline error_code DynRefImpl<target_endianness, is64Bits>
2296                             ::getNext(DynRefImpl &Result) const {
2297   return OwningObject->getDynNext(DynPimpl, Result);
2298 }
2299
2300 template<support::endianness target_endianness, bool is64Bits>
2301 inline int64_t DynRefImpl<target_endianness, is64Bits>
2302                             ::getTag() const {
2303   return OwningObject->getDyn(DynPimpl)->d_tag;
2304 }
2305
2306 template<support::endianness target_endianness, bool is64Bits>
2307 inline uint64_t DynRefImpl<target_endianness, is64Bits>
2308                             ::getVal() const {
2309   return OwningObject->getDyn(DynPimpl)->d_un.d_val;
2310 }
2311
2312 template<support::endianness target_endianness, bool is64Bits>
2313 inline uint64_t DynRefImpl<target_endianness, is64Bits>
2314                             ::getPtr() const {
2315   return OwningObject->getDyn(DynPimpl)->d_un.d_ptr;
2316 }
2317
2318 template<support::endianness target_endianness, bool is64Bits>
2319 inline DataRefImpl DynRefImpl<target_endianness, is64Bits>
2320                              ::getRawDataRefImpl() const {
2321   return DynPimpl;
2322 }
2323
2324 /// This is a generic interface for retrieving GNU symbol version
2325 /// information from an ELFObjectFile.
2326 static inline error_code GetELFSymbolVersion(const ObjectFile *Obj,
2327                                              const SymbolRef &Sym,
2328                                              StringRef &Version,
2329                                              bool &IsDefault) {
2330   // Little-endian 32-bit
2331   if (const ELFObjectFile<support::little, false> *ELFObj =
2332           dyn_cast<ELFObjectFile<support::little, false> >(Obj))
2333     return ELFObj->getSymbolVersion(Sym, Version, IsDefault);
2334
2335   // Big-endian 32-bit
2336   if (const ELFObjectFile<support::big, false> *ELFObj =
2337           dyn_cast<ELFObjectFile<support::big, false> >(Obj))
2338     return ELFObj->getSymbolVersion(Sym, Version, IsDefault);
2339
2340   // Little-endian 64-bit
2341   if (const ELFObjectFile<support::little, true> *ELFObj =
2342           dyn_cast<ELFObjectFile<support::little, true> >(Obj))
2343     return ELFObj->getSymbolVersion(Sym, Version, IsDefault);
2344
2345   // Big-endian 64-bit
2346   if (const ELFObjectFile<support::big, true> *ELFObj =
2347           dyn_cast<ELFObjectFile<support::big, true> >(Obj))
2348     return ELFObj->getSymbolVersion(Sym, Version, IsDefault);
2349
2350   llvm_unreachable("Object passed to GetELFSymbolVersion() is not ELF");
2351 }
2352
2353 }
2354 }
2355
2356 #endif