Object: Add isSymbolWeak.
[oota-llvm.git] / lib / Object / ELFObjectFile.cpp
1 //===- ELFObjectFile.cpp - 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 defines the ELFObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/Object/ObjectFile.h"
19 #include "llvm/Support/ELF.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <algorithm>
25 #include <limits>
26 #include <utility>
27
28 using namespace llvm;
29 using namespace object;
30
31 // Templates to choose Elf_Addr and Elf_Off depending on is64Bits.
32 namespace {
33 template<support::endianness target_endianness>
34 struct ELFDataTypeTypedefHelperCommon {
35   typedef support::detail::packed_endian_specific_integral
36     <uint16_t, target_endianness, support::aligned> Elf_Half;
37   typedef support::detail::packed_endian_specific_integral
38     <uint32_t, target_endianness, support::aligned> Elf_Word;
39   typedef support::detail::packed_endian_specific_integral
40     <int32_t, target_endianness, support::aligned> Elf_Sword;
41   typedef support::detail::packed_endian_specific_integral
42     <uint64_t, target_endianness, support::aligned> Elf_Xword;
43   typedef support::detail::packed_endian_specific_integral
44     <int64_t, target_endianness, support::aligned> Elf_Sxword;
45 };
46 }
47
48 namespace {
49 template<support::endianness target_endianness, bool is64Bits>
50 struct ELFDataTypeTypedefHelper;
51
52 /// ELF 32bit types.
53 template<support::endianness target_endianness>
54 struct ELFDataTypeTypedefHelper<target_endianness, false>
55   : ELFDataTypeTypedefHelperCommon<target_endianness> {
56   typedef support::detail::packed_endian_specific_integral
57     <uint32_t, target_endianness, support::aligned> Elf_Addr;
58   typedef support::detail::packed_endian_specific_integral
59     <uint32_t, target_endianness, support::aligned> Elf_Off;
60 };
61
62 /// ELF 64bit types.
63 template<support::endianness target_endianness>
64 struct ELFDataTypeTypedefHelper<target_endianness, true>
65   : ELFDataTypeTypedefHelperCommon<target_endianness>{
66   typedef support::detail::packed_endian_specific_integral
67     <uint64_t, target_endianness, support::aligned> Elf_Addr;
68   typedef support::detail::packed_endian_specific_integral
69     <uint64_t, target_endianness, support::aligned> Elf_Off;
70 };
71 }
72
73 // I really don't like doing this, but the alternative is copypasta.
74 #define LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits) \
75 typedef typename \
76   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Addr Elf_Addr; \
77 typedef typename \
78   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Off Elf_Off; \
79 typedef typename \
80   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Half Elf_Half; \
81 typedef typename \
82   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Word Elf_Word; \
83 typedef typename \
84   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sword Elf_Sword; \
85 typedef typename \
86   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Xword Elf_Xword; \
87 typedef typename \
88   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sxword Elf_Sxword;
89
90   // Section header.
91 namespace {
92 template<support::endianness target_endianness, bool is64Bits>
93 struct Elf_Shdr_Base;
94
95 template<support::endianness target_endianness>
96 struct Elf_Shdr_Base<target_endianness, false> {
97   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
98   Elf_Word sh_name;     // Section name (index into string table)
99   Elf_Word sh_type;     // Section type (SHT_*)
100   Elf_Word sh_flags;    // Section flags (SHF_*)
101   Elf_Addr sh_addr;     // Address where section is to be loaded
102   Elf_Off  sh_offset;   // File offset of section data, in bytes
103   Elf_Word sh_size;     // Size of section, in bytes
104   Elf_Word sh_link;     // Section type-specific header table index link
105   Elf_Word sh_info;     // Section type-specific extra information
106   Elf_Word sh_addralign;// Section address alignment
107   Elf_Word sh_entsize;  // Size of records contained within the section
108 };
109
110 template<support::endianness target_endianness>
111 struct Elf_Shdr_Base<target_endianness, true> {
112   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
113   Elf_Word  sh_name;     // Section name (index into string table)
114   Elf_Word  sh_type;     // Section type (SHT_*)
115   Elf_Xword sh_flags;    // Section flags (SHF_*)
116   Elf_Addr  sh_addr;     // Address where section is to be loaded
117   Elf_Off   sh_offset;   // File offset of section data, in bytes
118   Elf_Xword sh_size;     // Size of section, in bytes
119   Elf_Word  sh_link;     // Section type-specific header table index link
120   Elf_Word  sh_info;     // Section type-specific extra information
121   Elf_Xword sh_addralign;// Section address alignment
122   Elf_Xword sh_entsize;  // Size of records contained within the section
123 };
124
125 template<support::endianness target_endianness, bool is64Bits>
126 struct Elf_Shdr_Impl : Elf_Shdr_Base<target_endianness, is64Bits> {
127   using Elf_Shdr_Base<target_endianness, is64Bits>::sh_entsize;
128   using Elf_Shdr_Base<target_endianness, is64Bits>::sh_size;
129
130   /// @brief Get the number of entities this section contains if it has any.
131   unsigned getEntityCount() const {
132     if (sh_entsize == 0)
133       return 0;
134     return sh_size / sh_entsize;
135   }
136 };
137 }
138
139 namespace {
140 template<support::endianness target_endianness, bool is64Bits>
141 struct Elf_Sym_Base;
142
143 template<support::endianness target_endianness>
144 struct Elf_Sym_Base<target_endianness, false> {
145   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
146   Elf_Word      st_name;  // Symbol name (index into string table)
147   Elf_Addr      st_value; // Value or address associated with the symbol
148   Elf_Word      st_size;  // Size of the symbol
149   unsigned char st_info;  // Symbol's type and binding attributes
150   unsigned char st_other; // Must be zero; reserved
151   Elf_Half      st_shndx; // Which section (header table index) it's defined in
152 };
153
154 template<support::endianness target_endianness>
155 struct Elf_Sym_Base<target_endianness, true> {
156   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
157   Elf_Word      st_name;  // Symbol name (index into string table)
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   Elf_Addr      st_value; // Value or address associated with the symbol
162   Elf_Xword     st_size;  // Size of the symbol
163 };
164
165 template<support::endianness target_endianness, bool is64Bits>
166 struct Elf_Sym_Impl : Elf_Sym_Base<target_endianness, is64Bits> {
167   using Elf_Sym_Base<target_endianness, is64Bits>::st_info;
168
169   // These accessors and mutators correspond to the ELF32_ST_BIND,
170   // ELF32_ST_TYPE, and ELF32_ST_INFO macros defined in the ELF specification:
171   unsigned char getBinding() const { return st_info >> 4; }
172   unsigned char getType() const { return st_info & 0x0f; }
173   void setBinding(unsigned char b) { setBindingAndType(b, getType()); }
174   void setType(unsigned char t) { setBindingAndType(getBinding(), t); }
175   void setBindingAndType(unsigned char b, unsigned char t) {
176     st_info = (b << 4) + (t & 0x0f);
177   }
178 };
179 }
180
181 namespace {
182 template<support::endianness target_endianness, bool is64Bits, bool isRela>
183 struct Elf_Rel_Base;
184
185 template<support::endianness target_endianness>
186 struct Elf_Rel_Base<target_endianness, false, false> {
187   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
188   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
189   Elf_Word      r_info;  // Symbol table index and type of relocation to apply
190 };
191
192 template<support::endianness target_endianness>
193 struct Elf_Rel_Base<target_endianness, true, false> {
194   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
195   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
196   Elf_Xword     r_info;   // Symbol table index and type of relocation to apply
197 };
198
199 template<support::endianness target_endianness>
200 struct Elf_Rel_Base<target_endianness, false, true> {
201   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
202   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
203   Elf_Word      r_info;   // Symbol table index and type of relocation to apply
204   Elf_Sword     r_addend; // Compute value for relocatable field by adding this
205 };
206
207 template<support::endianness target_endianness>
208 struct Elf_Rel_Base<target_endianness, true, true> {
209   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
210   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
211   Elf_Xword     r_info;   // Symbol table index and type of relocation to apply
212   Elf_Sxword    r_addend; // Compute value for relocatable field by adding this.
213 };
214
215 template<support::endianness target_endianness, bool is64Bits, bool isRela>
216 struct Elf_Rel_Impl;
217
218 template<support::endianness target_endianness, bool isRela>
219 struct Elf_Rel_Impl<target_endianness, true, isRela>
220        : Elf_Rel_Base<target_endianness, true, isRela> {
221   using Elf_Rel_Base<target_endianness, true, isRela>::r_info;
222   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
223
224   // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_TYPE,
225   // and ELF64_R_INFO macros defined in the ELF specification:
226   uint64_t getSymbol() const { return (r_info >> 32); }
227   unsigned char getType() const {
228     return (unsigned char) (r_info & 0xffffffffL);
229   }
230   void setSymbol(uint64_t s) { setSymbolAndType(s, getType()); }
231   void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
232   void setSymbolAndType(uint64_t s, unsigned char t) {
233     r_info = (s << 32) + (t&0xffffffffL);
234   }
235 };
236
237 template<support::endianness target_endianness, bool isRela>
238 struct Elf_Rel_Impl<target_endianness, false, isRela>
239        : Elf_Rel_Base<target_endianness, false, isRela> {
240   using Elf_Rel_Base<target_endianness, false, isRela>::r_info;
241   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
242
243   // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_TYPE,
244   // and ELF32_R_INFO macros defined in the ELF specification:
245   uint32_t getSymbol() const { return (r_info >> 8); }
246   unsigned char getType() const { return (unsigned char) (r_info & 0x0ff); }
247   void setSymbol(uint32_t s) { setSymbolAndType(s, getType()); }
248   void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
249   void setSymbolAndType(uint32_t s, unsigned char t) {
250     r_info = (s << 8) + t;
251   }
252 };
253
254 }
255
256 namespace {
257 template<support::endianness target_endianness, bool is64Bits>
258 class ELFObjectFile : public ObjectFile {
259   LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
260
261   typedef Elf_Shdr_Impl<target_endianness, is64Bits> Elf_Shdr;
262   typedef Elf_Sym_Impl<target_endianness, is64Bits> Elf_Sym;
263   typedef Elf_Rel_Impl<target_endianness, is64Bits, false> Elf_Rel;
264   typedef Elf_Rel_Impl<target_endianness, is64Bits, true> Elf_Rela;
265
266   struct Elf_Ehdr {
267     unsigned char e_ident[ELF::EI_NIDENT]; // ELF Identification bytes
268     Elf_Half e_type;     // Type of file (see ET_*)
269     Elf_Half e_machine;  // Required architecture for this file (see EM_*)
270     Elf_Word e_version;  // Must be equal to 1
271     Elf_Addr e_entry;    // Address to jump to in order to start program
272     Elf_Off  e_phoff;    // Program header table's file offset, in bytes
273     Elf_Off  e_shoff;    // Section header table's file offset, in bytes
274     Elf_Word e_flags;    // Processor-specific flags
275     Elf_Half e_ehsize;   // Size of ELF header, in bytes
276     Elf_Half e_phentsize;// Size of an entry in the program header table
277     Elf_Half e_phnum;    // Number of entries in the program header table
278     Elf_Half e_shentsize;// Size of an entry in the section header table
279     Elf_Half e_shnum;    // Number of entries in the section header table
280     Elf_Half e_shstrndx; // Section header table index of section name
281                                   // string table
282     bool checkMagic() const {
283       return (memcmp(e_ident, ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
284     }
285     unsigned char getFileClass() const { return e_ident[ELF::EI_CLASS]; }
286     unsigned char getDataEncoding() const { return e_ident[ELF::EI_DATA]; }
287   };
288
289   typedef SmallVector<const Elf_Shdr*, 1> Sections_t;
290   typedef DenseMap<unsigned, unsigned> IndexMap_t;
291   typedef DenseMap<const Elf_Shdr*, SmallVector<uint32_t, 1> > RelocMap_t;
292
293   const Elf_Ehdr *Header;
294   const Elf_Shdr *SectionHeaderTable;
295   const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
296   const Elf_Shdr *dot_strtab_sec;   // Symbol header string table.
297   Sections_t SymbolTableSections;
298   IndexMap_t SymbolTableSectionsIndexMap;
299   DenseMap<const Elf_Sym*, ELF::Elf64_Word> ExtendedSymbolTable;
300
301   /// @brief Map sections to an array of relocation sections that reference
302   ///        them sorted by section index.
303   RelocMap_t SectionRelocMap;
304
305   /// @brief Get the relocation section that contains \a Rel.
306   const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
307     return getSection(Rel.w.b);
308   }
309
310   void            validateSymbol(DataRefImpl Symb) const;
311   bool            isRelocationHasAddend(DataRefImpl Rel) const;
312   template<typename T>
313   const T        *getEntry(uint16_t Section, uint32_t Entry) const;
314   template<typename T>
315   const T        *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
316   const Elf_Sym  *getSymbol(DataRefImpl Symb) const;
317   const Elf_Shdr *getSection(DataRefImpl index) const;
318   const Elf_Shdr *getSection(uint32_t index) const;
319   const Elf_Rel  *getRel(DataRefImpl Rel) const;
320   const Elf_Rela *getRela(DataRefImpl Rela) const;
321   const char     *getString(uint32_t section, uint32_t offset) const;
322   const char     *getString(const Elf_Shdr *section, uint32_t offset) const;
323   error_code      getSymbolName(const Elf_Sym *Symb, StringRef &Res) const;
324
325 protected:
326   virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
327   virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
328   virtual error_code getSymbolOffset(DataRefImpl Symb, uint64_t &Res) const;
329   virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const;
330   virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
331   virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const;
332   virtual error_code isSymbolInternal(DataRefImpl Symb, bool &Res) const;
333   virtual error_code isSymbolGlobal(DataRefImpl Symb, bool &Res) const;
334   virtual error_code isSymbolWeak(DataRefImpl Symb, bool &Res) const;
335   virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res) const;
336
337   virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
338   virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
339   virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
340   virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
341   virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
342   virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const;
343   virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
344   virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
345   virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
346   virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
347                                            bool &Result) const;
348   virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
349   virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;
350
351   virtual error_code getRelocationNext(DataRefImpl Rel,
352                                        RelocationRef &Res) const;
353   virtual error_code getRelocationAddress(DataRefImpl Rel,
354                                           uint64_t &Res) const;
355   virtual error_code getRelocationSymbol(DataRefImpl Rel,
356                                          SymbolRef &Res) const;
357   virtual error_code getRelocationType(DataRefImpl Rel,
358                                        uint32_t &Res) const;
359   virtual error_code getRelocationTypeName(DataRefImpl Rel,
360                                            SmallVectorImpl<char> &Result) const;
361   virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
362                                                  int64_t &Res) const;
363   virtual error_code getRelocationValueString(DataRefImpl Rel,
364                                            SmallVectorImpl<char> &Result) const;
365
366 public:
367   ELFObjectFile(MemoryBuffer *Object, error_code &ec);
368   virtual symbol_iterator begin_symbols() const;
369   virtual symbol_iterator end_symbols() const;
370   virtual section_iterator begin_sections() const;
371   virtual section_iterator end_sections() const;
372
373   virtual uint8_t getBytesInAddress() const;
374   virtual StringRef getFileFormatName() const;
375   virtual unsigned getArch() const;
376
377   uint64_t getNumSections() const;
378   uint64_t getStringTableIndex() const;
379   ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
380   const Elf_Shdr *getSection(const Elf_Sym *symb) const;
381
382   static inline bool classof(const Binary *v) {
383     return v->getType() == isELF;
384   }
385   static inline bool classof(const ELFObjectFile *v) { return true; }
386 };
387 } // end namespace
388
389 template<support::endianness target_endianness, bool is64Bits>
390 void ELFObjectFile<target_endianness, is64Bits>
391                   ::validateSymbol(DataRefImpl Symb) const {
392   const Elf_Sym  *symb = getSymbol(Symb);
393   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
394   // FIXME: We really need to do proper error handling in the case of an invalid
395   //        input file. Because we don't use exceptions, I think we'll just pass
396   //        an error object around.
397   if (!(  symb
398         && SymbolTableSection
399         && symb >= (const Elf_Sym*)(base()
400                    + SymbolTableSection->sh_offset)
401         && symb <  (const Elf_Sym*)(base()
402                    + SymbolTableSection->sh_offset
403                    + SymbolTableSection->sh_size)))
404     // FIXME: Proper error handling.
405     report_fatal_error("Symb must point to a valid symbol!");
406 }
407
408 template<support::endianness target_endianness, bool is64Bits>
409 error_code ELFObjectFile<target_endianness, is64Bits>
410                         ::getSymbolNext(DataRefImpl Symb,
411                                         SymbolRef &Result) const {
412   validateSymbol(Symb);
413   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
414
415   ++Symb.d.a;
416   // Check to see if we are at the end of this symbol table.
417   if (Symb.d.a >= SymbolTableSection->getEntityCount()) {
418     // We are at the end. If there are other symbol tables, jump to them.
419     ++Symb.d.b;
420     Symb.d.a = 1; // The 0th symbol in ELF is fake.
421     // Otherwise return the terminator.
422     if (Symb.d.b >= SymbolTableSections.size()) {
423       Symb.d.a = std::numeric_limits<uint32_t>::max();
424       Symb.d.b = std::numeric_limits<uint32_t>::max();
425     }
426   }
427
428   Result = SymbolRef(Symb, this);
429   return object_error::success;
430 }
431
432 template<support::endianness target_endianness, bool is64Bits>
433 error_code ELFObjectFile<target_endianness, is64Bits>
434                         ::getSymbolName(DataRefImpl Symb,
435                                         StringRef &Result) const {
436   validateSymbol(Symb);
437   const Elf_Sym *symb = getSymbol(Symb);
438   return getSymbolName(symb, Result);
439 }
440
441 template<support::endianness target_endianness, bool is64Bits>
442 ELF::Elf64_Word ELFObjectFile<target_endianness, is64Bits>
443                       ::getSymbolTableIndex(const Elf_Sym *symb) const {
444   if (symb->st_shndx == ELF::SHN_XINDEX)
445     return ExtendedSymbolTable.lookup(symb);
446   return symb->st_shndx;
447 }
448
449 template<support::endianness target_endianness, bool is64Bits>
450 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
451 ELFObjectFile<target_endianness, is64Bits>
452                              ::getSection(const Elf_Sym *symb) const {
453   if (symb->st_shndx == ELF::SHN_XINDEX)
454     return getSection(ExtendedSymbolTable.lookup(symb));
455   if (symb->st_shndx >= ELF::SHN_LORESERVE)
456     return 0;
457   return getSection(symb->st_shndx);
458 }
459
460 template<support::endianness target_endianness, bool is64Bits>
461 error_code ELFObjectFile<target_endianness, is64Bits>
462                         ::getSymbolOffset(DataRefImpl Symb,
463                                           uint64_t &Result) const {
464   validateSymbol(Symb);
465   const Elf_Sym  *symb = getSymbol(Symb);
466   const Elf_Shdr *Section;
467   switch (getSymbolTableIndex(symb)) {
468   case ELF::SHN_COMMON:
469    // Undefined symbols have no address yet.
470   case ELF::SHN_UNDEF:
471     Result = UnknownAddressOrSize;
472     return object_error::success;
473   case ELF::SHN_ABS:
474     Result = symb->st_value;
475     return object_error::success;
476   default: Section = getSection(symb);
477   }
478
479   switch (symb->getType()) {
480   case ELF::STT_SECTION:
481     Result = Section ? Section->sh_addr : UnknownAddressOrSize;
482     return object_error::success;
483   case ELF::STT_FUNC:
484   case ELF::STT_OBJECT:
485   case ELF::STT_NOTYPE:
486     Result = symb->st_value;
487     return object_error::success;
488   default:
489     Result = UnknownAddressOrSize;
490     return object_error::success;
491   }
492 }
493
494 template<support::endianness target_endianness, bool is64Bits>
495 error_code ELFObjectFile<target_endianness, is64Bits>
496                         ::getSymbolAddress(DataRefImpl Symb,
497                                            uint64_t &Result) const {
498   validateSymbol(Symb);
499   const Elf_Sym  *symb = getSymbol(Symb);
500   const Elf_Shdr *Section;
501   switch (getSymbolTableIndex(symb)) {
502   case ELF::SHN_COMMON: // Fall through.
503    // Undefined symbols have no address yet.
504   case ELF::SHN_UNDEF:
505     Result = UnknownAddressOrSize;
506     return object_error::success;
507   case ELF::SHN_ABS:
508     Result = reinterpret_cast<uintptr_t>(base()+symb->st_value);
509     return object_error::success;
510   default: Section = getSection(symb);
511   }
512   const uint8_t* addr = base();
513   if (Section)
514     addr += Section->sh_offset;
515   switch (symb->getType()) {
516   case ELF::STT_SECTION:
517     Result = reinterpret_cast<uintptr_t>(addr);
518     return object_error::success;
519   case ELF::STT_FUNC: // Fall through.
520   case ELF::STT_OBJECT: // Fall through.
521   case ELF::STT_NOTYPE:
522     addr += symb->st_value;
523     Result = reinterpret_cast<uintptr_t>(addr);
524     return object_error::success;
525   default:
526     Result = UnknownAddressOrSize;
527     return object_error::success;
528   }
529 }
530
531 template<support::endianness target_endianness, bool is64Bits>
532 error_code ELFObjectFile<target_endianness, is64Bits>
533                         ::getSymbolSize(DataRefImpl Symb,
534                                         uint64_t &Result) const {
535   validateSymbol(Symb);
536   const Elf_Sym  *symb = getSymbol(Symb);
537   if (symb->st_size == 0)
538     Result = UnknownAddressOrSize;
539   Result = symb->st_size;
540   return object_error::success;
541 }
542
543 template<support::endianness target_endianness, bool is64Bits>
544 error_code ELFObjectFile<target_endianness, is64Bits>
545                         ::getSymbolNMTypeChar(DataRefImpl Symb,
546                                               char &Result) const {
547   validateSymbol(Symb);
548   const Elf_Sym  *symb = getSymbol(Symb);
549   const Elf_Shdr *Section = getSection(symb);
550
551   char ret = '?';
552
553   if (Section) {
554     switch (Section->sh_type) {
555     case ELF::SHT_PROGBITS:
556     case ELF::SHT_DYNAMIC:
557       switch (Section->sh_flags) {
558       case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
559         ret = 't'; break;
560       case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
561         ret = 'd'; break;
562       case ELF::SHF_ALLOC:
563       case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
564       case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
565         ret = 'r'; break;
566       }
567       break;
568     case ELF::SHT_NOBITS: ret = 'b';
569     }
570   }
571
572   switch (getSymbolTableIndex(symb)) {
573   case ELF::SHN_UNDEF:
574     if (ret == '?')
575       ret = 'U';
576     break;
577   case ELF::SHN_ABS: ret = 'a'; break;
578   case ELF::SHN_COMMON: ret = 'c'; break;
579   }
580
581   switch (symb->getBinding()) {
582   case ELF::STB_GLOBAL: ret = ::toupper(ret); break;
583   case ELF::STB_WEAK:
584     if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF)
585       ret = 'w';
586     else
587       if (symb->getType() == ELF::STT_OBJECT)
588         ret = 'V';
589       else
590         ret = 'W';
591   }
592
593   if (ret == '?' && symb->getType() == ELF::STT_SECTION) {
594     StringRef name;
595     if (error_code ec = getSymbolName(Symb, name))
596       return ec;
597     Result = StringSwitch<char>(name)
598       .StartsWith(".debug", 'N')
599       .StartsWith(".note", 'n')
600       .Default('?');
601     return object_error::success;
602   }
603
604   Result = ret;
605   return object_error::success;
606 }
607
608 template<support::endianness target_endianness, bool is64Bits>
609 error_code ELFObjectFile<target_endianness, is64Bits>
610                         ::getSymbolType(DataRefImpl Symb,
611                                         SymbolRef::Type &Result) const {
612   validateSymbol(Symb);
613   const Elf_Sym  *symb = getSymbol(Symb);
614
615   if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF) {
616     Result = SymbolRef::ST_External;
617     return object_error::success;
618   }
619
620   switch (symb->getType()) {
621   case ELF::STT_FUNC:
622     Result = SymbolRef::ST_Function;
623     break;
624   case ELF::STT_OBJECT:
625     Result = SymbolRef::ST_Data;
626     break;
627   default:
628     Result = SymbolRef::ST_Other;
629     break;
630   }
631   return object_error::success;
632 }
633
634 template<support::endianness target_endianness, bool is64Bits>
635 error_code ELFObjectFile<target_endianness, is64Bits>
636                         ::isSymbolGlobal(DataRefImpl Symb,
637                                         bool &Result) const {
638   validateSymbol(Symb);
639   const Elf_Sym  *symb = getSymbol(Symb);
640
641   Result = symb->getBinding() == ELF::STB_GLOBAL;
642   return object_error::success;
643 }
644
645 template<support::endianness target_endianness, bool is64Bits>
646 error_code ELFObjectFile<target_endianness, is64Bits>
647                         ::isSymbolWeak(DataRefImpl Symb,
648                                        bool &Result) const {
649   validateSymbol(Symb);
650   const Elf_Sym  *symb = getSymbol(Symb);
651
652   Result = symb->getBinding() == ELF::STB_WEAK;
653   return object_error::success;
654 }
655
656 template<support::endianness target_endianness, bool is64Bits>
657 error_code ELFObjectFile<target_endianness, is64Bits>
658                         ::isSymbolInternal(DataRefImpl Symb,
659                                            bool &Result) const {
660   validateSymbol(Symb);
661   const Elf_Sym  *symb = getSymbol(Symb);
662
663   if (  symb->getType() == ELF::STT_FILE
664      || symb->getType() == ELF::STT_SECTION)
665     Result = true;
666   Result = false;
667   return object_error::success;
668 }
669
670 template<support::endianness target_endianness, bool is64Bits>
671 error_code ELFObjectFile<target_endianness, is64Bits>
672                         ::getSectionNext(DataRefImpl Sec, SectionRef &Result) const {
673   const uint8_t *sec = reinterpret_cast<const uint8_t *>(Sec.p);
674   sec += Header->e_shentsize;
675   Sec.p = reinterpret_cast<intptr_t>(sec);
676   Result = SectionRef(Sec, this);
677   return object_error::success;
678 }
679
680 template<support::endianness target_endianness, bool is64Bits>
681 error_code ELFObjectFile<target_endianness, is64Bits>
682                         ::getSectionName(DataRefImpl Sec,
683                                          StringRef &Result) const {
684   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
685   Result = StringRef(getString(dot_shstrtab_sec, sec->sh_name));
686   return object_error::success;
687 }
688
689 template<support::endianness target_endianness, bool is64Bits>
690 error_code ELFObjectFile<target_endianness, is64Bits>
691                         ::getSectionAddress(DataRefImpl Sec,
692                                             uint64_t &Result) const {
693   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
694   Result = sec->sh_addr;
695   return object_error::success;
696 }
697
698 template<support::endianness target_endianness, bool is64Bits>
699 error_code ELFObjectFile<target_endianness, is64Bits>
700                         ::getSectionSize(DataRefImpl Sec,
701                                          uint64_t &Result) const {
702   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
703   Result = sec->sh_size;
704   return object_error::success;
705 }
706
707 template<support::endianness target_endianness, bool is64Bits>
708 error_code ELFObjectFile<target_endianness, is64Bits>
709                         ::getSectionContents(DataRefImpl Sec,
710                                              StringRef &Result) const {
711   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
712   const char *start = (const char*)base() + sec->sh_offset;
713   Result = StringRef(start, sec->sh_size);
714   return object_error::success;
715 }
716
717 template<support::endianness target_endianness, bool is64Bits>
718 error_code ELFObjectFile<target_endianness, is64Bits>
719                         ::getSectionAlignment(DataRefImpl Sec,
720                                               uint64_t &Result) const {
721   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
722   Result = sec->sh_addralign;
723   return object_error::success;
724 }
725
726 template<support::endianness target_endianness, bool is64Bits>
727 error_code ELFObjectFile<target_endianness, is64Bits>
728                         ::isSectionText(DataRefImpl Sec,
729                                         bool &Result) const {
730   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
731   if (sec->sh_flags & ELF::SHF_EXECINSTR)
732     Result = true;
733   else
734     Result = false;
735   return object_error::success;
736 }
737
738 template<support::endianness target_endianness, bool is64Bits>
739 error_code ELFObjectFile<target_endianness, is64Bits>
740                         ::isSectionData(DataRefImpl Sec,
741                                         bool &Result) const {
742   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
743   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
744       && sec->sh_type == ELF::SHT_PROGBITS)
745     Result = true;
746   else
747     Result = false;
748   return object_error::success;
749 }
750
751 template<support::endianness target_endianness, bool is64Bits>
752 error_code ELFObjectFile<target_endianness, is64Bits>
753                         ::isSectionBSS(DataRefImpl Sec,
754                                        bool &Result) const {
755   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
756   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
757       && sec->sh_type == ELF::SHT_NOBITS)
758     Result = true;
759   else
760     Result = false;
761   return object_error::success;
762 }
763
764 template<support::endianness target_endianness, bool is64Bits>
765 error_code ELFObjectFile<target_endianness, is64Bits>
766                           ::sectionContainsSymbol(DataRefImpl Sec,
767                                                   DataRefImpl Symb,
768                                                   bool &Result) const {
769   // FIXME: Unimplemented.
770   Result = false;
771   return object_error::success;
772 }
773
774 template<support::endianness target_endianness, bool is64Bits>
775 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
776                                  ::getSectionRelBegin(DataRefImpl Sec) const {
777   DataRefImpl RelData;
778   memset(&RelData, 0, sizeof(RelData));
779   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
780   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
781   if (sec != 0 && ittr != SectionRelocMap.end()) {
782     RelData.w.a = getSection(ittr->second[0])->sh_info;
783     RelData.w.b = ittr->second[0];
784     RelData.w.c = 0;
785   }
786   return relocation_iterator(RelocationRef(RelData, this));
787 }
788
789 template<support::endianness target_endianness, bool is64Bits>
790 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
791                                  ::getSectionRelEnd(DataRefImpl Sec) const {
792   DataRefImpl RelData;
793   memset(&RelData, 0, sizeof(RelData));
794   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
795   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
796   if (sec != 0 && ittr != SectionRelocMap.end()) {
797     // Get the index of the last relocation section for this section.
798     std::size_t relocsecindex = ittr->second[ittr->second.size() - 1];
799     const Elf_Shdr *relocsec = getSection(relocsecindex);
800     RelData.w.a = relocsec->sh_info;
801     RelData.w.b = relocsecindex;
802     RelData.w.c = relocsec->sh_size / relocsec->sh_entsize;
803   }
804   return relocation_iterator(RelocationRef(RelData, this));
805 }
806
807 // Relocations
808 template<support::endianness target_endianness, bool is64Bits>
809 error_code ELFObjectFile<target_endianness, is64Bits>
810                         ::getRelocationNext(DataRefImpl Rel,
811                                             RelocationRef &Result) const {
812   ++Rel.w.c;
813   const Elf_Shdr *relocsec = getSection(Rel.w.b);
814   if (Rel.w.c >= (relocsec->sh_size / relocsec->sh_entsize)) {
815     // We have reached the end of the relocations for this section. See if there
816     // is another relocation section.
817     typename RelocMap_t::mapped_type relocseclist =
818       SectionRelocMap.lookup(getSection(Rel.w.a));
819
820     // Do a binary search for the current reloc section index (which must be
821     // present). Then get the next one.
822     typename RelocMap_t::mapped_type::const_iterator loc =
823       std::lower_bound(relocseclist.begin(), relocseclist.end(), Rel.w.b);
824     ++loc;
825
826     // If there is no next one, don't do anything. The ++Rel.w.c above sets Rel
827     // to the end iterator.
828     if (loc != relocseclist.end()) {
829       Rel.w.b = *loc;
830       Rel.w.a = 0;
831     }
832   }
833   Result = RelocationRef(Rel, this);
834   return object_error::success;
835 }
836
837 template<support::endianness target_endianness, bool is64Bits>
838 error_code ELFObjectFile<target_endianness, is64Bits>
839                         ::getRelocationSymbol(DataRefImpl Rel,
840                                               SymbolRef &Result) const {
841   uint32_t symbolIdx;
842   const Elf_Shdr *sec = getSection(Rel.w.b);
843   switch (sec->sh_type) {
844     default :
845       report_fatal_error("Invalid section type in Rel!");
846     case ELF::SHT_REL : {
847       symbolIdx = getRel(Rel)->getSymbol();
848       break;
849     }
850     case ELF::SHT_RELA : {
851       symbolIdx = getRela(Rel)->getSymbol();
852       break;
853     }
854   }
855   DataRefImpl SymbolData;
856   IndexMap_t::const_iterator it = SymbolTableSectionsIndexMap.find(sec->sh_link);
857   if (it == SymbolTableSectionsIndexMap.end())
858     report_fatal_error("Relocation symbol table not found!");
859   SymbolData.d.a = symbolIdx;
860   SymbolData.d.b = it->second;
861   Result = SymbolRef(SymbolData, this);
862   return object_error::success;
863 }
864
865 template<support::endianness target_endianness, bool is64Bits>
866 error_code ELFObjectFile<target_endianness, is64Bits>
867                         ::getRelocationAddress(DataRefImpl Rel,
868                                                uint64_t &Result) const {
869   uint64_t offset;
870   const Elf_Shdr *sec = getSection(Rel.w.b);
871   switch (sec->sh_type) {
872     default :
873       report_fatal_error("Invalid section type in Rel!");
874     case ELF::SHT_REL : {
875       offset = getRel(Rel)->r_offset;
876       break;
877     }
878     case ELF::SHT_RELA : {
879       offset = getRela(Rel)->r_offset;
880       break;
881     }
882   }
883
884   Result = offset;
885   return object_error::success;
886 }
887
888 template<support::endianness target_endianness, bool is64Bits>
889 error_code ELFObjectFile<target_endianness, is64Bits>
890                         ::getRelocationType(DataRefImpl Rel,
891                                             uint32_t &Result) const {
892   const Elf_Shdr *sec = getSection(Rel.w.b);
893   switch (sec->sh_type) {
894     default :
895       report_fatal_error("Invalid section type in Rel!");
896     case ELF::SHT_REL : {
897       Result = getRel(Rel)->getType();
898       break;
899     }
900     case ELF::SHT_RELA : {
901       Result = getRela(Rel)->getType();
902       break;
903     }
904   }
905   return object_error::success;
906 }
907
908 #define LLVM_ELF_SWITCH_RELOC_TYPE_NAME(enum) \
909   case ELF::enum: res = #enum; break;
910
911 template<support::endianness target_endianness, bool is64Bits>
912 error_code ELFObjectFile<target_endianness, is64Bits>
913                         ::getRelocationTypeName(DataRefImpl Rel,
914                                           SmallVectorImpl<char> &Result) const {
915   const Elf_Shdr *sec = getSection(Rel.w.b);
916   uint8_t type;
917   StringRef res;
918   switch (sec->sh_type) {
919     default :
920       return object_error::parse_failed;
921     case ELF::SHT_REL : {
922       type = getRel(Rel)->getType();
923       break;
924     }
925     case ELF::SHT_RELA : {
926       type = getRela(Rel)->getType();
927       break;
928     }
929   }
930   switch (Header->e_machine) {
931   case ELF::EM_X86_64:
932     switch (type) {
933       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_NONE);
934       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_64);
935       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC32);
936       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOT32);
937       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PLT32);
938       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_COPY);
939       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GLOB_DAT);
940       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_JUMP_SLOT);
941       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_RELATIVE);
942       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPCREL);
943       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32);
944       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32S);
945       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_16);
946       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC16);
947       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_8);
948       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC8);
949       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPMOD64);
950       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF64);
951       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF64);
952       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSGD);
953       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSLD);
954       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF32);
955       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTTPOFF);
956       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF32);
957       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC64);
958       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTOFF64);
959       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32);
960       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE32);
961       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE64);
962       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32_TLSDESC);
963       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC_CALL);
964       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC);
965     default:
966       res = "Unknown";
967     }
968     break;
969   case ELF::EM_386:
970     switch (type) {
971       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_NONE);
972       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32);
973       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC32);
974       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOT32);
975       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PLT32);
976       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_COPY);
977       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GLOB_DAT);
978       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_JUMP_SLOT);
979       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_RELATIVE);
980       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTOFF);
981       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTPC);
982       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32PLT);
983       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF);
984       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE);
985       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTIE);
986       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE);
987       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD);
988       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM);
989       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_16);
990       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC16);
991       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_8);
992       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC8);
993       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_32);
994       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_PUSH);
995       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_CALL);
996       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_POP);
997       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_32);
998       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_PUSH);
999       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_CALL);
1000       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_POP);
1001       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDO_32);
1002       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE_32);
1003       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE_32);
1004       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPMOD32);
1005       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPOFF32);
1006       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF32);
1007       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTDESC);
1008       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC_CALL);
1009       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC);
1010       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_IRELATIVE);
1011     default:
1012       res = "Unknown";
1013     }
1014     break;
1015   default:
1016     res = "Unknown";
1017   }
1018   Result.append(res.begin(), res.end());
1019   return object_error::success;
1020 }
1021
1022 #undef LLVM_ELF_SWITCH_RELOC_TYPE_NAME
1023
1024 template<support::endianness target_endianness, bool is64Bits>
1025 error_code ELFObjectFile<target_endianness, is64Bits>
1026                         ::getRelocationAdditionalInfo(DataRefImpl Rel,
1027                                                       int64_t &Result) const {
1028   const Elf_Shdr *sec = getSection(Rel.w.b);
1029   switch (sec->sh_type) {
1030     default :
1031       report_fatal_error("Invalid section type in Rel!");
1032     case ELF::SHT_REL : {
1033       Result = 0;
1034       return object_error::success;
1035     }
1036     case ELF::SHT_RELA : {
1037       Result = getRela(Rel)->r_addend;
1038       return object_error::success;
1039     }
1040   }
1041 }
1042
1043 template<support::endianness target_endianness, bool is64Bits>
1044 error_code ELFObjectFile<target_endianness, is64Bits>
1045                         ::getRelocationValueString(DataRefImpl Rel,
1046                                           SmallVectorImpl<char> &Result) const {
1047   const Elf_Shdr *sec = getSection(Rel.w.b);
1048   uint8_t type;
1049   StringRef res;
1050   int64_t addend = 0;
1051   uint16_t symbol_index = 0;
1052   switch (sec->sh_type) {
1053     default :
1054       return object_error::parse_failed;
1055     case ELF::SHT_REL : {
1056       type = getRel(Rel)->getType();
1057       symbol_index = getRel(Rel)->getSymbol();
1058       // TODO: Read implicit addend from section data.
1059       break;
1060     }
1061     case ELF::SHT_RELA : {
1062       type = getRela(Rel)->getType();
1063       symbol_index = getRela(Rel)->getSymbol();
1064       addend = getRela(Rel)->r_addend;
1065       break;
1066     }
1067   }
1068   const Elf_Sym *symb = getEntry<Elf_Sym>(sec->sh_link, symbol_index);
1069   StringRef symname;
1070   if (error_code ec = getSymbolName(symb, symname))
1071     return ec;
1072   switch (Header->e_machine) {
1073   case ELF::EM_X86_64:
1074     switch (type) {
1075     case ELF::R_X86_64_32S:
1076       res = symname;
1077       break;
1078     case ELF::R_X86_64_PC32: {
1079         std::string fmtbuf;
1080         raw_string_ostream fmt(fmtbuf);
1081         fmt << symname << (addend < 0 ? "" : "+") << addend << "-P";
1082         fmt.flush();
1083         Result.append(fmtbuf.begin(), fmtbuf.end());
1084       }
1085       break;
1086     default:
1087       res = "Unknown";
1088     }
1089     break;
1090   default:
1091     res = "Unknown";
1092   }
1093   if (Result.empty())
1094     Result.append(res.begin(), res.end());
1095   return object_error::success;
1096 }
1097
1098 template<support::endianness target_endianness, bool is64Bits>
1099 ELFObjectFile<target_endianness, is64Bits>::ELFObjectFile(MemoryBuffer *Object
1100                                                           , error_code &ec)
1101   : ObjectFile(Binary::isELF, Object, ec)
1102   , SectionHeaderTable(0)
1103   , dot_shstrtab_sec(0)
1104   , dot_strtab_sec(0) {
1105   Header = reinterpret_cast<const Elf_Ehdr *>(base());
1106
1107   if (Header->e_shoff == 0)
1108     return;
1109
1110   SectionHeaderTable =
1111     reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
1112   uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
1113   if (!(  (const uint8_t *)SectionHeaderTable + SectionTableSize
1114          <= base() + Data->getBufferSize()))
1115     // FIXME: Proper error handling.
1116     report_fatal_error("Section table goes past end of file!");
1117
1118
1119   // To find the symbol tables we walk the section table to find SHT_SYMTAB.
1120   const Elf_Shdr* SymbolTableSectionHeaderIndex = 0;
1121   const Elf_Shdr* sh = reinterpret_cast<const Elf_Shdr*>(SectionHeaderTable);
1122   for (uint64_t i = 0, e = getNumSections(); i != e; ++i) {
1123     if (sh->sh_type == ELF::SHT_SYMTAB_SHNDX) {
1124       if (SymbolTableSectionHeaderIndex)
1125         // FIXME: Proper error handling.
1126         report_fatal_error("More than one .symtab_shndx!");
1127       SymbolTableSectionHeaderIndex = sh;
1128     }
1129     if (sh->sh_type == ELF::SHT_SYMTAB) {
1130       SymbolTableSectionsIndexMap[i] = SymbolTableSections.size();
1131       SymbolTableSections.push_back(sh);
1132     }
1133     if (sh->sh_type == ELF::SHT_REL || sh->sh_type == ELF::SHT_RELA) {
1134       SectionRelocMap[getSection(sh->sh_info)].push_back(i);
1135     }
1136     ++sh;
1137   }
1138
1139   // Sort section relocation lists by index.
1140   for (typename RelocMap_t::iterator i = SectionRelocMap.begin(),
1141                                      e = SectionRelocMap.end(); i != e; ++i) {
1142     std::sort(i->second.begin(), i->second.end());
1143   }
1144
1145   // Get string table sections.
1146   dot_shstrtab_sec = getSection(getStringTableIndex());
1147   if (dot_shstrtab_sec) {
1148     // Verify that the last byte in the string table in a null.
1149     if (((const char*)base() + dot_shstrtab_sec->sh_offset)
1150         [dot_shstrtab_sec->sh_size - 1] != 0)
1151       // FIXME: Proper error handling.
1152       report_fatal_error("String table must end with a null terminator!");
1153   }
1154
1155   // Merge this into the above loop.
1156   for (const char *i = reinterpret_cast<const char *>(SectionHeaderTable),
1157                   *e = i + getNumSections() * Header->e_shentsize;
1158                    i != e; i += Header->e_shentsize) {
1159     const Elf_Shdr *sh = reinterpret_cast<const Elf_Shdr*>(i);
1160     if (sh->sh_type == ELF::SHT_STRTAB) {
1161       StringRef SectionName(getString(dot_shstrtab_sec, sh->sh_name));
1162       if (SectionName == ".strtab") {
1163         if (dot_strtab_sec != 0)
1164           // FIXME: Proper error handling.
1165           report_fatal_error("Already found section named .strtab!");
1166         dot_strtab_sec = sh;
1167         const char *dot_strtab = (const char*)base() + sh->sh_offset;
1168           if (dot_strtab[sh->sh_size - 1] != 0)
1169             // FIXME: Proper error handling.
1170             report_fatal_error("String table must end with a null terminator!");
1171       }
1172     }
1173   }
1174
1175   // Build symbol name side-mapping if there is one.
1176   if (SymbolTableSectionHeaderIndex) {
1177     const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
1178                                       SymbolTableSectionHeaderIndex->sh_offset);
1179     error_code ec;
1180     for (symbol_iterator si = begin_symbols(),
1181                          se = end_symbols(); si != se; si.increment(ec)) {
1182       if (ec)
1183         report_fatal_error("Fewer extended symbol table entries than symbols!");
1184       if (*ShndxTable != ELF::SHN_UNDEF)
1185         ExtendedSymbolTable[getSymbol(si->getRawDataRefImpl())] = *ShndxTable;
1186       ++ShndxTable;
1187     }
1188   }
1189 }
1190
1191 template<support::endianness target_endianness, bool is64Bits>
1192 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1193                              ::begin_symbols() const {
1194   DataRefImpl SymbolData;
1195   memset(&SymbolData, 0, sizeof(SymbolData));
1196   if (SymbolTableSections.size() == 0) {
1197     SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1198     SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1199   } else {
1200     SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
1201     SymbolData.d.b = 0;
1202   }
1203   return symbol_iterator(SymbolRef(SymbolData, this));
1204 }
1205
1206 template<support::endianness target_endianness, bool is64Bits>
1207 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1208                              ::end_symbols() const {
1209   DataRefImpl SymbolData;
1210   memset(&SymbolData, 0, sizeof(SymbolData));
1211   SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1212   SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1213   return symbol_iterator(SymbolRef(SymbolData, this));
1214 }
1215
1216 template<support::endianness target_endianness, bool is64Bits>
1217 section_iterator ELFObjectFile<target_endianness, is64Bits>
1218                               ::begin_sections() const {
1219   DataRefImpl ret;
1220   memset(&ret, 0, sizeof(DataRefImpl));
1221   ret.p = reinterpret_cast<intptr_t>(base() + Header->e_shoff);
1222   return section_iterator(SectionRef(ret, this));
1223 }
1224
1225 template<support::endianness target_endianness, bool is64Bits>
1226 section_iterator ELFObjectFile<target_endianness, is64Bits>
1227                               ::end_sections() const {
1228   DataRefImpl ret;
1229   memset(&ret, 0, sizeof(DataRefImpl));
1230   ret.p = reinterpret_cast<intptr_t>(base()
1231                                      + Header->e_shoff
1232                                      + (Header->e_shentsize*getNumSections()));
1233   return section_iterator(SectionRef(ret, this));
1234 }
1235
1236 template<support::endianness target_endianness, bool is64Bits>
1237 uint8_t ELFObjectFile<target_endianness, is64Bits>::getBytesInAddress() const {
1238   return is64Bits ? 8 : 4;
1239 }
1240
1241 template<support::endianness target_endianness, bool is64Bits>
1242 StringRef ELFObjectFile<target_endianness, is64Bits>
1243                        ::getFileFormatName() const {
1244   switch(Header->e_ident[ELF::EI_CLASS]) {
1245   case ELF::ELFCLASS32:
1246     switch(Header->e_machine) {
1247     case ELF::EM_386:
1248       return "ELF32-i386";
1249     case ELF::EM_X86_64:
1250       return "ELF32-x86-64";
1251     case ELF::EM_ARM:
1252       return "ELF32-arm";
1253     default:
1254       return "ELF32-unknown";
1255     }
1256   case ELF::ELFCLASS64:
1257     switch(Header->e_machine) {
1258     case ELF::EM_386:
1259       return "ELF64-i386";
1260     case ELF::EM_X86_64:
1261       return "ELF64-x86-64";
1262     default:
1263       return "ELF64-unknown";
1264     }
1265   default:
1266     // FIXME: Proper error handling.
1267     report_fatal_error("Invalid ELFCLASS!");
1268   }
1269 }
1270
1271 template<support::endianness target_endianness, bool is64Bits>
1272 unsigned ELFObjectFile<target_endianness, is64Bits>::getArch() const {
1273   switch(Header->e_machine) {
1274   case ELF::EM_386:
1275     return Triple::x86;
1276   case ELF::EM_X86_64:
1277     return Triple::x86_64;
1278   case ELF::EM_ARM:
1279     return Triple::arm;
1280   default:
1281     return Triple::UnknownArch;
1282   }
1283 }
1284
1285 template<support::endianness target_endianness, bool is64Bits>
1286 uint64_t ELFObjectFile<target_endianness, is64Bits>::getNumSections() const {
1287   if (Header->e_shnum == ELF::SHN_UNDEF)
1288     return SectionHeaderTable->sh_size;
1289   return Header->e_shnum;
1290 }
1291
1292 template<support::endianness target_endianness, bool is64Bits>
1293 uint64_t
1294 ELFObjectFile<target_endianness, is64Bits>::getStringTableIndex() const {
1295   if (Header->e_shnum == ELF::SHN_UNDEF) {
1296     if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
1297       return SectionHeaderTable->sh_link;
1298     if (Header->e_shstrndx >= getNumSections())
1299       return 0;
1300   }
1301   return Header->e_shstrndx;
1302 }
1303
1304
1305 template<support::endianness target_endianness, bool is64Bits>
1306 template<typename T>
1307 inline const T *
1308 ELFObjectFile<target_endianness, is64Bits>::getEntry(uint16_t Section,
1309                                                      uint32_t Entry) const {
1310   return getEntry<T>(getSection(Section), Entry);
1311 }
1312
1313 template<support::endianness target_endianness, bool is64Bits>
1314 template<typename T>
1315 inline const T *
1316 ELFObjectFile<target_endianness, is64Bits>::getEntry(const Elf_Shdr * Section,
1317                                                      uint32_t Entry) const {
1318   return reinterpret_cast<const T *>(
1319            base()
1320            + Section->sh_offset
1321            + (Entry * Section->sh_entsize));
1322 }
1323
1324 template<support::endianness target_endianness, bool is64Bits>
1325 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
1326 ELFObjectFile<target_endianness, is64Bits>::getSymbol(DataRefImpl Symb) const {
1327   return getEntry<Elf_Sym>(SymbolTableSections[Symb.d.b], Symb.d.a);
1328 }
1329
1330 template<support::endianness target_endianness, bool is64Bits>
1331 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rel *
1332 ELFObjectFile<target_endianness, is64Bits>::getRel(DataRefImpl Rel) const {
1333   return getEntry<Elf_Rel>(Rel.w.b, Rel.w.c);
1334 }
1335
1336 template<support::endianness target_endianness, bool is64Bits>
1337 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rela *
1338 ELFObjectFile<target_endianness, is64Bits>::getRela(DataRefImpl Rela) const {
1339   return getEntry<Elf_Rela>(Rela.w.b, Rela.w.c);
1340 }
1341
1342 template<support::endianness target_endianness, bool is64Bits>
1343 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
1344 ELFObjectFile<target_endianness, is64Bits>::getSection(DataRefImpl Symb) const {
1345   const Elf_Shdr *sec = getSection(Symb.d.b);
1346   if (sec->sh_type != ELF::SHT_SYMTAB || sec->sh_type != ELF::SHT_DYNSYM)
1347     // FIXME: Proper error handling.
1348     report_fatal_error("Invalid symbol table section!");
1349   return sec;
1350 }
1351
1352 template<support::endianness target_endianness, bool is64Bits>
1353 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
1354 ELFObjectFile<target_endianness, is64Bits>::getSection(uint32_t index) const {
1355   if (index == 0)
1356     return 0;
1357   if (!SectionHeaderTable || index >= getNumSections())
1358     // FIXME: Proper error handling.
1359     report_fatal_error("Invalid section index!");
1360
1361   return reinterpret_cast<const Elf_Shdr *>(
1362          reinterpret_cast<const char *>(SectionHeaderTable)
1363          + (index * Header->e_shentsize));
1364 }
1365
1366 template<support::endianness target_endianness, bool is64Bits>
1367 const char *ELFObjectFile<target_endianness, is64Bits>
1368                          ::getString(uint32_t section,
1369                                      ELF::Elf32_Word offset) const {
1370   return getString(getSection(section), offset);
1371 }
1372
1373 template<support::endianness target_endianness, bool is64Bits>
1374 const char *ELFObjectFile<target_endianness, is64Bits>
1375                          ::getString(const Elf_Shdr *section,
1376                                      ELF::Elf32_Word offset) const {
1377   assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
1378   if (offset >= section->sh_size)
1379     // FIXME: Proper error handling.
1380     report_fatal_error("Symbol name offset outside of string table!");
1381   return (const char *)base() + section->sh_offset + offset;
1382 }
1383
1384 template<support::endianness target_endianness, bool is64Bits>
1385 error_code ELFObjectFile<target_endianness, is64Bits>
1386                         ::getSymbolName(const Elf_Sym *symb,
1387                                         StringRef &Result) const {
1388   if (symb->st_name == 0) {
1389     const Elf_Shdr *section = getSection(symb);
1390     if (!section)
1391       Result = "";
1392     else
1393       Result = getString(dot_shstrtab_sec, section->sh_name);
1394     return object_error::success;
1395   }
1396
1397   // Use the default symbol table name section.
1398   Result = getString(dot_strtab_sec, symb->st_name);
1399   return object_error::success;
1400 }
1401
1402 // EI_CLASS, EI_DATA.
1403 static std::pair<unsigned char, unsigned char>
1404 getElfArchType(MemoryBuffer *Object) {
1405   if (Object->getBufferSize() < ELF::EI_NIDENT)
1406     return std::make_pair((uint8_t)ELF::ELFCLASSNONE,(uint8_t)ELF::ELFDATANONE);
1407   return std::make_pair( (uint8_t)Object->getBufferStart()[ELF::EI_CLASS]
1408                        , (uint8_t)Object->getBufferStart()[ELF::EI_DATA]);
1409 }
1410
1411 namespace llvm {
1412
1413   ObjectFile *ObjectFile::createELFObjectFile(MemoryBuffer *Object) {
1414     std::pair<unsigned char, unsigned char> Ident = getElfArchType(Object);
1415     error_code ec;
1416     if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB)
1417       return new ELFObjectFile<support::little, false>(Object, ec);
1418     else if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB)
1419       return new ELFObjectFile<support::big, false>(Object, ec);
1420     else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB)
1421       return new ELFObjectFile<support::little, true>(Object, ec);
1422     else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB)
1423       return new ELFObjectFile<support::big, true>(Object, ec);
1424     // FIXME: Proper error handling.
1425     report_fatal_error("Not an ELF object file!");
1426   }
1427
1428 } // end namespace llvm