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