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