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