Add support for .symtab_shnidx. Unfortunately, doing this required breaking a
[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_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(uint16_t index) const;
319   const Elf_Rel  *getRel(DataRefImpl Rel) const;
320   const Elf_Rela *getRela(DataRefImpl Rela) const;
321   const char     *getString(uint16_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 getSymbolType(DataRefImpl Symb, SymbolRef::SymbolType &Res) const;
335
336   virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
337   virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
338   virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
339   virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
340   virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
341   virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const;
342   virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
343   virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
344   virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
345   virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
346                                            bool &Result) const;
347   virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
348   virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;
349
350   virtual error_code getRelocationNext(DataRefImpl Rel,
351                                        RelocationRef &Res) const;
352   virtual error_code getRelocationAddress(DataRefImpl Rel,
353                                           uint64_t &Res) const;
354   virtual error_code getRelocationSymbol(DataRefImpl Rel,
355                                          SymbolRef &Res) const;
356   virtual error_code getRelocationType(DataRefImpl Rel,
357                                        uint32_t &Res) const;
358   virtual error_code getRelocationTypeName(DataRefImpl Rel,
359                                            SmallVectorImpl<char> &Result) const;
360   virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
361                                                  int64_t &Res) const;
362   virtual error_code getRelocationValueString(DataRefImpl Rel,
363                                            SmallVectorImpl<char> &Result) const;
364
365 public:
366   ELFObjectFile(MemoryBuffer *Object, error_code &ec);
367   virtual symbol_iterator begin_symbols() const;
368   virtual symbol_iterator end_symbols() const;
369   virtual section_iterator begin_sections() const;
370   virtual section_iterator end_sections() const;
371
372   virtual uint8_t getBytesInAddress() const;
373   virtual StringRef getFileFormatName() const;
374   virtual unsigned getArch() const;
375
376   uint64_t getSymbolTableIndex(const Elf_Sym *symb) const;
377 };
378 } // end namespace
379
380 template<support::endianness target_endianness, bool is64Bits>
381 void ELFObjectFile<target_endianness, is64Bits>
382                   ::validateSymbol(DataRefImpl Symb) const {
383   const Elf_Sym  *symb = getSymbol(Symb);
384   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
385   // FIXME: We really need to do proper error handling in the case of an invalid
386   //        input file. Because we don't use exceptions, I think we'll just pass
387   //        an error object around.
388   if (!(  symb
389         && SymbolTableSection
390         && symb >= (const Elf_Sym*)(base()
391                    + SymbolTableSection->sh_offset)
392         && symb <  (const Elf_Sym*)(base()
393                    + SymbolTableSection->sh_offset
394                    + SymbolTableSection->sh_size)))
395     // FIXME: Proper error handling.
396     report_fatal_error("Symb must point to a valid symbol!");
397 }
398
399 template<support::endianness target_endianness, bool is64Bits>
400 error_code ELFObjectFile<target_endianness, is64Bits>
401                         ::getSymbolNext(DataRefImpl Symb,
402                                         SymbolRef &Result) const {
403   validateSymbol(Symb);
404   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
405
406   ++Symb.d.a;
407   // Check to see if we are at the end of this symbol table.
408   if (Symb.d.a >= SymbolTableSection->getEntityCount()) {
409     // We are at the end. If there are other symbol tables, jump to them.
410     ++Symb.d.b;
411     Symb.d.a = 1; // The 0th symbol in ELF is fake.
412     // Otherwise return the terminator.
413     if (Symb.d.b >= SymbolTableSections.size()) {
414       Symb.d.a = std::numeric_limits<uint32_t>::max();
415       Symb.d.b = std::numeric_limits<uint32_t>::max();
416     }
417   }
418
419   Result = SymbolRef(Symb, this);
420   return object_error::success;
421 }
422
423 template<support::endianness target_endianness, bool is64Bits>
424 error_code ELFObjectFile<target_endianness, is64Bits>
425                         ::getSymbolName(DataRefImpl Symb,
426                                         StringRef &Result) const {
427   validateSymbol(Symb);
428   const Elf_Sym *symb = getSymbol(Symb);
429   return getSymbolName(symb, Result);
430 }
431
432 template<support::endianness target_endianness, bool is64Bits>
433 uint64_t ELFObjectFile<target_endianness, is64Bits>
434                       ::getSymbolTableIndex(const Elf_Sym *symb) const {
435   if (symb->st_shndx == ELF::SHN_XINDEX)
436     return ExtendedSymbolTable.lookup(symb);
437   return symb->st_shndx;
438 }
439
440 template<support::endianness target_endianness, bool is64Bits>
441 error_code ELFObjectFile<target_endianness, is64Bits>
442                         ::getSymbolOffset(DataRefImpl Symb,
443                                           uint64_t &Result) const {
444   validateSymbol(Symb);
445   const Elf_Sym  *symb = getSymbol(Symb);
446   const Elf_Shdr *Section;
447   switch (getSymbolTableIndex(symb)) {
448   case ELF::SHN_COMMON:
449    // Undefined symbols have no address yet.
450   case ELF::SHN_UNDEF:
451     Result = UnknownAddressOrSize;
452     return object_error::success;
453   case ELF::SHN_ABS:
454     Result = symb->st_value;
455     return object_error::success;
456   default: Section = getSection(symb->st_shndx);
457   }
458
459   switch (symb->getType()) {
460   case ELF::STT_SECTION:
461     Result = Section ? Section->sh_addr : UnknownAddressOrSize;
462     return object_error::success;
463   case ELF::STT_FUNC:
464   case ELF::STT_OBJECT:
465   case ELF::STT_NOTYPE:
466     Result = symb->st_value;
467     return object_error::success;
468   default:
469     Result = UnknownAddressOrSize;
470     return object_error::success;
471   }
472 }
473
474 template<support::endianness target_endianness, bool is64Bits>
475 error_code ELFObjectFile<target_endianness, is64Bits>
476                         ::getSymbolAddress(DataRefImpl Symb,
477                                            uint64_t &Result) const {
478   validateSymbol(Symb);
479   const Elf_Sym  *symb = getSymbol(Symb);
480   const Elf_Shdr *Section;
481   switch (getSymbolTableIndex(symb)) {
482   case ELF::SHN_COMMON: // Fall through.
483    // Undefined symbols have no address yet.
484   case ELF::SHN_UNDEF:
485     Result = UnknownAddressOrSize;
486     return object_error::success;
487   case ELF::SHN_ABS:
488     Result = reinterpret_cast<uintptr_t>(base()+symb->st_value);
489     return object_error::success;
490   default: Section = getSection(getSymbolTableIndex(symb));
491   }
492   const uint8_t* addr = base();
493   if (Section)
494     addr += Section->sh_offset;
495   switch (symb->getType()) {
496   case ELF::STT_SECTION:
497     Result = reinterpret_cast<uintptr_t>(addr);
498     return object_error::success;
499   case ELF::STT_FUNC: // Fall through.
500   case ELF::STT_OBJECT: // Fall through.
501   case ELF::STT_NOTYPE:
502     addr += symb->st_value;
503     Result = reinterpret_cast<uintptr_t>(addr);
504     return object_error::success;
505   default:
506     Result = UnknownAddressOrSize;
507     return object_error::success;
508   }
509 }
510
511 template<support::endianness target_endianness, bool is64Bits>
512 error_code ELFObjectFile<target_endianness, is64Bits>
513                         ::getSymbolSize(DataRefImpl Symb,
514                                         uint64_t &Result) const {
515   validateSymbol(Symb);
516   const Elf_Sym  *symb = getSymbol(Symb);
517   if (symb->st_size == 0)
518     Result = UnknownAddressOrSize;
519   Result = symb->st_size;
520   return object_error::success;
521 }
522
523 template<support::endianness target_endianness, bool is64Bits>
524 error_code ELFObjectFile<target_endianness, is64Bits>
525                         ::getSymbolNMTypeChar(DataRefImpl Symb,
526                                               char &Result) const {
527   validateSymbol(Symb);
528   const Elf_Sym  *symb = getSymbol(Symb);
529   const Elf_Shdr *Section = getSection(getSymbolTableIndex(symb));
530
531   char ret = '?';
532
533   if (Section) {
534     switch (Section->sh_type) {
535     case ELF::SHT_PROGBITS:
536     case ELF::SHT_DYNAMIC:
537       switch (Section->sh_flags) {
538       case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
539         ret = 't'; break;
540       case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
541         ret = 'd'; break;
542       case ELF::SHF_ALLOC:
543       case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
544       case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
545         ret = 'r'; break;
546       }
547       break;
548     case ELF::SHT_NOBITS: ret = 'b';
549     }
550   }
551
552   switch (symb->st_shndx) {
553   case ELF::SHN_UNDEF:
554     if (ret == '?')
555       ret = 'U';
556     break;
557   case ELF::SHN_ABS: ret = 'a'; break;
558   case ELF::SHN_COMMON: ret = 'c'; break;
559   }
560
561   switch (symb->getBinding()) {
562   case ELF::STB_GLOBAL: ret = ::toupper(ret); break;
563   case ELF::STB_WEAK:
564     if (symb->st_shndx == ELF::SHN_UNDEF)
565       ret = 'w';
566     else
567       if (symb->getType() == ELF::STT_OBJECT)
568         ret = 'V';
569       else
570         ret = 'W';
571   }
572
573   if (ret == '?' && symb->getType() == ELF::STT_SECTION) {
574     StringRef name;
575     if (error_code ec = getSymbolName(Symb, name))
576       return ec;
577     Result = StringSwitch<char>(name)
578       .StartsWith(".debug", 'N')
579       .StartsWith(".note", 'n')
580       .Default('?');
581     return object_error::success;
582   }
583
584   Result = ret;
585   return object_error::success;
586 }
587
588 template<support::endianness target_endianness, bool is64Bits>
589 error_code ELFObjectFile<target_endianness, is64Bits>
590                         ::getSymbolType(DataRefImpl Symb,
591                                         SymbolRef::SymbolType &Result) const {
592   validateSymbol(Symb);
593   const Elf_Sym  *symb = getSymbol(Symb);
594
595   if (getSymbolTableIndex(symb) == ELF::SHN_UNDEF) {
596     Result = SymbolRef::ST_External;
597     return object_error::success;
598   }
599
600   switch (symb->getType()) {
601   case ELF::STT_FUNC:
602     Result = SymbolRef::ST_Function;
603     break;
604   case ELF::STT_OBJECT:
605     Result = SymbolRef::ST_Data;
606     break;
607   default:
608     Result = SymbolRef::ST_Other;
609     break;
610   }
611   return object_error::success;
612 }
613
614 template<support::endianness target_endianness, bool is64Bits>
615 error_code ELFObjectFile<target_endianness, is64Bits>
616                         ::isSymbolGlobal(DataRefImpl Symb,
617                                         bool &Result) const {
618   validateSymbol(Symb);
619   const Elf_Sym  *symb = getSymbol(Symb);
620
621   Result = symb->getBinding() == ELF::STB_GLOBAL;
622   return object_error::success;
623 }
624
625 template<support::endianness target_endianness, bool is64Bits>
626 error_code ELFObjectFile<target_endianness, is64Bits>
627                         ::isSymbolInternal(DataRefImpl Symb,
628                                            bool &Result) const {
629   validateSymbol(Symb);
630   const Elf_Sym  *symb = getSymbol(Symb);
631
632   if (  symb->getType() == ELF::STT_FILE
633      || symb->getType() == ELF::STT_SECTION)
634     Result = true;
635   Result = false;
636   return object_error::success;
637 }
638
639 template<support::endianness target_endianness, bool is64Bits>
640 error_code ELFObjectFile<target_endianness, is64Bits>
641                         ::getSectionNext(DataRefImpl Sec, SectionRef &Result) const {
642   const uint8_t *sec = reinterpret_cast<const uint8_t *>(Sec.p);
643   sec += Header->e_shentsize;
644   Sec.p = reinterpret_cast<intptr_t>(sec);
645   Result = SectionRef(Sec, this);
646   return object_error::success;
647 }
648
649 template<support::endianness target_endianness, bool is64Bits>
650 error_code ELFObjectFile<target_endianness, is64Bits>
651                         ::getSectionName(DataRefImpl Sec,
652                                          StringRef &Result) const {
653   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
654   Result = StringRef(getString(dot_shstrtab_sec, sec->sh_name));
655   return object_error::success;
656 }
657
658 template<support::endianness target_endianness, bool is64Bits>
659 error_code ELFObjectFile<target_endianness, is64Bits>
660                         ::getSectionAddress(DataRefImpl Sec,
661                                             uint64_t &Result) const {
662   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
663   Result = sec->sh_addr;
664   return object_error::success;
665 }
666
667 template<support::endianness target_endianness, bool is64Bits>
668 error_code ELFObjectFile<target_endianness, is64Bits>
669                         ::getSectionSize(DataRefImpl Sec,
670                                          uint64_t &Result) const {
671   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
672   Result = sec->sh_size;
673   return object_error::success;
674 }
675
676 template<support::endianness target_endianness, bool is64Bits>
677 error_code ELFObjectFile<target_endianness, is64Bits>
678                         ::getSectionContents(DataRefImpl Sec,
679                                              StringRef &Result) const {
680   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
681   const char *start = (const char*)base() + sec->sh_offset;
682   Result = StringRef(start, sec->sh_size);
683   return object_error::success;
684 }
685
686 template<support::endianness target_endianness, bool is64Bits>
687 error_code ELFObjectFile<target_endianness, is64Bits>
688                         ::getSectionAlignment(DataRefImpl Sec,
689                                               uint64_t &Result) const {
690   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
691   Result = sec->sh_addralign;
692   return object_error::success;
693 }
694
695 template<support::endianness target_endianness, bool is64Bits>
696 error_code ELFObjectFile<target_endianness, is64Bits>
697                         ::isSectionText(DataRefImpl Sec,
698                                         bool &Result) const {
699   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
700   if (sec->sh_flags & ELF::SHF_EXECINSTR)
701     Result = true;
702   else
703     Result = false;
704   return object_error::success;
705 }
706
707 template<support::endianness target_endianness, bool is64Bits>
708 error_code ELFObjectFile<target_endianness, is64Bits>
709                         ::isSectionData(DataRefImpl Sec,
710                                         bool &Result) const {
711   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
712   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
713       && sec->sh_type == ELF::SHT_PROGBITS)
714     Result = true;
715   else
716     Result = false;
717   return object_error::success;
718 }
719
720 template<support::endianness target_endianness, bool is64Bits>
721 error_code ELFObjectFile<target_endianness, is64Bits>
722                         ::isSectionBSS(DataRefImpl Sec,
723                                        bool &Result) const {
724   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
725   if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
726       && sec->sh_type == ELF::SHT_NOBITS)
727     Result = true;
728   else
729     Result = false;
730   return object_error::success;
731 }
732
733 template<support::endianness target_endianness, bool is64Bits>
734 error_code ELFObjectFile<target_endianness, is64Bits>
735                           ::sectionContainsSymbol(DataRefImpl Sec,
736                                                   DataRefImpl Symb,
737                                                   bool &Result) const {
738   // FIXME: Unimplemented.
739   Result = false;
740   return object_error::success;
741 }
742
743 template<support::endianness target_endianness, bool is64Bits>
744 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
745                                  ::getSectionRelBegin(DataRefImpl Sec) const {
746   DataRefImpl RelData;
747   memset(&RelData, 0, sizeof(RelData));
748   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
749   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
750   if (sec != 0 && ittr != SectionRelocMap.end()) {
751     RelData.w.a = getSection(ittr->second[0])->sh_link;
752     RelData.w.b = ittr->second[0];
753     RelData.w.c = 0;
754   }
755   return relocation_iterator(RelocationRef(RelData, this));
756 }
757
758 template<support::endianness target_endianness, bool is64Bits>
759 relocation_iterator ELFObjectFile<target_endianness, is64Bits>
760                                  ::getSectionRelEnd(DataRefImpl Sec) const {
761   DataRefImpl RelData;
762   memset(&RelData, 0, sizeof(RelData));
763   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
764   typename RelocMap_t::const_iterator ittr = SectionRelocMap.find(sec);
765   if (sec != 0 && ittr != SectionRelocMap.end()) {
766     // Get the index of the last relocation section for this section.
767     std::size_t relocsecindex = ittr->second[ittr->second.size() - 1];
768     const Elf_Shdr *relocsec = getSection(relocsecindex);
769     RelData.w.a = relocsec->sh_link;
770     RelData.w.b = relocsecindex;
771     RelData.w.c = relocsec->sh_size / relocsec->sh_entsize;
772   }
773   return relocation_iterator(RelocationRef(RelData, this));
774 }
775
776 // Relocations
777 template<support::endianness target_endianness, bool is64Bits>
778 error_code ELFObjectFile<target_endianness, is64Bits>
779                         ::getRelocationNext(DataRefImpl Rel,
780                                             RelocationRef &Result) const {
781   ++Rel.w.c;
782   const Elf_Shdr *relocsec = getSection(Rel.w.b);
783   if (Rel.w.c >= (relocsec->sh_size / relocsec->sh_entsize)) {
784     // We have reached the end of the relocations for this section. See if there
785     // is another relocation section.
786     typename RelocMap_t::mapped_type relocseclist =
787       SectionRelocMap.lookup(getSection(Rel.w.a));
788
789     // Do a binary search for the current reloc section index (which must be
790     // present). Then get the next one.
791     typename RelocMap_t::mapped_type::const_iterator loc =
792       std::lower_bound(relocseclist.begin(), relocseclist.end(), Rel.w.b);
793     ++loc;
794
795     // If there is no next one, don't do anything. The ++Rel.w.c above sets Rel
796     // to the end iterator.
797     if (loc != relocseclist.end()) {
798       Rel.w.b = *loc;
799       Rel.w.a = 0;
800     }
801   }
802   Result = RelocationRef(Rel, this);
803   return object_error::success;
804 }
805
806 template<support::endianness target_endianness, bool is64Bits>
807 error_code ELFObjectFile<target_endianness, is64Bits>
808                         ::getRelocationSymbol(DataRefImpl Rel,
809                                               SymbolRef &Result) const {
810   uint32_t symbolIdx;
811   const Elf_Shdr *sec = getSection(Rel.w.b);
812   switch (sec->sh_type) {
813     default :
814       report_fatal_error("Invalid section type in Rel!");
815     case ELF::SHT_REL : {
816       symbolIdx = getRel(Rel)->getSymbol();
817       break;
818     }
819     case ELF::SHT_RELA : {
820       symbolIdx = getRela(Rel)->getSymbol();
821       break;
822     }
823   }
824   DataRefImpl SymbolData;
825   IndexMap_t::const_iterator it = SymbolTableSectionsIndexMap.find(sec->sh_link);
826   if (it == SymbolTableSectionsIndexMap.end())
827     report_fatal_error("Relocation symbol table not found!");
828   SymbolData.d.a = symbolIdx;
829   SymbolData.d.b = it->second;
830   Result = SymbolRef(SymbolData, this);
831   return object_error::success;
832 }
833
834 template<support::endianness target_endianness, bool is64Bits>
835 error_code ELFObjectFile<target_endianness, is64Bits>
836                         ::getRelocationAddress(DataRefImpl Rel,
837                                                uint64_t &Result) const {
838   uint64_t offset;
839   const Elf_Shdr *sec = getSection(Rel.w.b);
840   switch (sec->sh_type) {
841     default :
842       report_fatal_error("Invalid section type in Rel!");
843     case ELF::SHT_REL : {
844       offset = getRel(Rel)->r_offset;
845       break;
846     }
847     case ELF::SHT_RELA : {
848       offset = getRela(Rel)->r_offset;
849       break;
850     }
851   }
852
853   Result = offset;
854   return object_error::success;
855 }
856
857 template<support::endianness target_endianness, bool is64Bits>
858 error_code ELFObjectFile<target_endianness, is64Bits>
859                         ::getRelocationType(DataRefImpl Rel,
860                                             uint32_t &Result) const {
861   const Elf_Shdr *sec = getSection(Rel.w.b);
862   switch (sec->sh_type) {
863     default :
864       report_fatal_error("Invalid section type in Rel!");
865     case ELF::SHT_REL : {
866       Result = getRel(Rel)->getType();
867       break;
868     }
869     case ELF::SHT_RELA : {
870       Result = getRela(Rel)->getType();
871       break;
872     }
873   }
874   return object_error::success;
875 }
876
877 #define LLVM_ELF_SWITCH_RELOC_TYPE_NAME(enum) \
878   case ELF::enum: res = #enum; break;
879
880 template<support::endianness target_endianness, bool is64Bits>
881 error_code ELFObjectFile<target_endianness, is64Bits>
882                         ::getRelocationTypeName(DataRefImpl Rel,
883                                           SmallVectorImpl<char> &Result) const {
884   const Elf_Shdr *sec = getSection(Rel.w.b);
885   uint8_t type;
886   StringRef res;
887   switch (sec->sh_type) {
888     default :
889       return object_error::parse_failed;
890     case ELF::SHT_REL : {
891       type = getRel(Rel)->getType();
892       break;
893     }
894     case ELF::SHT_RELA : {
895       type = getRela(Rel)->getType();
896       break;
897     }
898   }
899   switch (Header->e_machine) {
900   case ELF::EM_X86_64:
901     switch (type) {
902       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_NONE);
903       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_64);
904       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC32);
905       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOT32);
906       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PLT32);
907       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_COPY);
908       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GLOB_DAT);
909       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_JUMP_SLOT);
910       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_RELATIVE);
911       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPCREL);
912       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32);
913       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32S);
914       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_16);
915       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC16);
916       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_8);
917       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC8);
918       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPMOD64);
919       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF64);
920       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF64);
921       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSGD);
922       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSLD);
923       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF32);
924       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTTPOFF);
925       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF32);
926       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC64);
927       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTOFF64);
928       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32);
929       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE32);
930       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE64);
931       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32_TLSDESC);
932       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC_CALL);
933       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC);
934     default:
935       res = "Unknown";
936     }
937     break;
938   case ELF::EM_386:
939     switch (type) {
940       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_NONE);
941       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32);
942       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC32);
943       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOT32);
944       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PLT32);
945       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_COPY);
946       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GLOB_DAT);
947       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_JUMP_SLOT);
948       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_RELATIVE);
949       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTOFF);
950       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTPC);
951       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32PLT);
952       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF);
953       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE);
954       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTIE);
955       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE);
956       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD);
957       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM);
958       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_16);
959       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC16);
960       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_8);
961       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC8);
962       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_32);
963       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_PUSH);
964       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_CALL);
965       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_POP);
966       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_32);
967       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_PUSH);
968       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_CALL);
969       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_POP);
970       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDO_32);
971       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE_32);
972       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE_32);
973       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPMOD32);
974       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPOFF32);
975       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF32);
976       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTDESC);
977       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC_CALL);
978       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC);
979       LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_IRELATIVE);
980     default:
981       res = "Unknown";
982     }
983     break;
984   default:
985     res = "Unknown";
986   }
987   Result.append(res.begin(), res.end());
988   return object_error::success;
989 }
990
991 #undef LLVM_ELF_SWITCH_RELOC_TYPE_NAME
992
993 template<support::endianness target_endianness, bool is64Bits>
994 error_code ELFObjectFile<target_endianness, is64Bits>
995                         ::getRelocationAdditionalInfo(DataRefImpl Rel,
996                                                       int64_t &Result) const {
997   const Elf_Shdr *sec = getSection(Rel.w.b);
998   switch (sec->sh_type) {
999     default :
1000       report_fatal_error("Invalid section type in Rel!");
1001     case ELF::SHT_REL : {
1002       Result = 0;
1003       return object_error::success;
1004     }
1005     case ELF::SHT_RELA : {
1006       Result = getRela(Rel)->r_addend;
1007       return object_error::success;
1008     }
1009   }
1010 }
1011
1012 template<support::endianness target_endianness, bool is64Bits>
1013 error_code ELFObjectFile<target_endianness, is64Bits>
1014                         ::getRelocationValueString(DataRefImpl Rel,
1015                                           SmallVectorImpl<char> &Result) const {
1016   const Elf_Shdr *sec = getSection(Rel.w.b);
1017   uint8_t type;
1018   StringRef res;
1019   int64_t addend = 0;
1020   uint16_t symbol_index = 0;
1021   switch (sec->sh_type) {
1022     default :
1023       return object_error::parse_failed;
1024     case ELF::SHT_REL : {
1025       type = getRel(Rel)->getType();
1026       symbol_index = getRel(Rel)->getSymbol();
1027       // TODO: Read implicit addend from section data.
1028       break;
1029     }
1030     case ELF::SHT_RELA : {
1031       type = getRela(Rel)->getType();
1032       symbol_index = getRela(Rel)->getSymbol();
1033       addend = getRela(Rel)->r_addend;
1034       break;
1035     }
1036   }
1037   const Elf_Sym *symb = getEntry<Elf_Sym>(sec->sh_link, symbol_index);
1038   StringRef symname;
1039   if (error_code ec = getSymbolName(symb, symname))
1040     return ec;
1041   switch (Header->e_machine) {
1042   case ELF::EM_X86_64:
1043     switch (type) {
1044     case ELF::R_X86_64_32S:
1045       res = symname;
1046       break;
1047     case ELF::R_X86_64_PC32: {
1048         std::string fmtbuf;
1049         raw_string_ostream fmt(fmtbuf);
1050         fmt << symname << (addend < 0 ? "" : "+") << addend << "-P";
1051         fmt.flush();
1052         Result.append(fmtbuf.begin(), fmtbuf.end());
1053       }
1054       break;
1055     default:
1056       res = "Unknown";
1057     }
1058     break;
1059   default:
1060     res = "Unknown";
1061   }
1062   if (Result.empty())
1063     Result.append(res.begin(), res.end());
1064   return object_error::success;
1065 }
1066
1067 template<support::endianness target_endianness, bool is64Bits>
1068 ELFObjectFile<target_endianness, is64Bits>::ELFObjectFile(MemoryBuffer *Object
1069                                                           , error_code &ec)
1070   : ObjectFile(Binary::isELF, Object, ec)
1071   , SectionHeaderTable(0)
1072   , dot_shstrtab_sec(0)
1073   , dot_strtab_sec(0) {
1074   Header = reinterpret_cast<const Elf_Ehdr *>(base());
1075
1076   if (Header->e_shoff == 0)
1077     return;
1078
1079   SectionHeaderTable =
1080     reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
1081   uint32_t SectionTableSize = Header->e_shnum * Header->e_shentsize;
1082   if (!(  (const uint8_t *)SectionHeaderTable + SectionTableSize
1083          <= base() + Data->getBufferSize()))
1084     // FIXME: Proper error handling.
1085     report_fatal_error("Section table goes past end of file!");
1086
1087
1088   // To find the symbol tables we walk the section table to find SHT_SYMTAB.
1089   const Elf_Shdr* SymbolTableSectionHeaderIndex = 0;
1090   const Elf_Shdr* sh = reinterpret_cast<const Elf_Shdr*>(SectionHeaderTable);
1091   for (unsigned i = 0; i < Header->e_shnum; ++i) {
1092     if (sh->sh_type == ELF::SHT_SYMTAB_SHNDX) {
1093       if (SymbolTableSectionHeaderIndex)
1094         // FIXME: Proper error handling.
1095         report_fatal_error("More than one .symtab_shndx!");
1096       SymbolTableSectionHeaderIndex = sh;
1097     }
1098     if (sh->sh_type == ELF::SHT_SYMTAB) {
1099       SymbolTableSectionsIndexMap[i] = SymbolTableSections.size();
1100       SymbolTableSections.push_back(sh);
1101     }
1102     if (sh->sh_type == ELF::SHT_REL || sh->sh_type == ELF::SHT_RELA) {
1103       SectionRelocMap[getSection(sh->sh_link)].push_back(i);
1104     }
1105     ++sh;
1106   }
1107
1108   // Sort section relocation lists by index.
1109   for (typename RelocMap_t::iterator i = SectionRelocMap.begin(),
1110                                      e = SectionRelocMap.end(); i != e; ++i) {
1111     std::sort(i->second.begin(), i->second.end());
1112   }
1113
1114   // Get string table sections.
1115   dot_shstrtab_sec = getSection(Header->e_shstrndx);
1116   if (dot_shstrtab_sec) {
1117     // Verify that the last byte in the string table in a null.
1118     if (((const char*)base() + dot_shstrtab_sec->sh_offset)
1119         [dot_shstrtab_sec->sh_size - 1] != 0)
1120       // FIXME: Proper error handling.
1121       report_fatal_error("String table must end with a null terminator!");
1122   }
1123
1124   // Merge this into the above loop.
1125   for (const char *i = reinterpret_cast<const char *>(SectionHeaderTable),
1126                   *e = i + Header->e_shnum * Header->e_shentsize;
1127                    i != e; i += Header->e_shentsize) {
1128     const Elf_Shdr *sh = reinterpret_cast<const Elf_Shdr*>(i);
1129     if (sh->sh_type == ELF::SHT_STRTAB) {
1130       StringRef SectionName(getString(dot_shstrtab_sec, sh->sh_name));
1131       if (SectionName == ".strtab") {
1132         if (dot_strtab_sec != 0)
1133           // FIXME: Proper error handling.
1134           report_fatal_error("Already found section named .strtab!");
1135         dot_strtab_sec = sh;
1136         const char *dot_strtab = (const char*)base() + sh->sh_offset;
1137           if (dot_strtab[sh->sh_size - 1] != 0)
1138             // FIXME: Proper error handling.
1139             report_fatal_error("String table must end with a null terminator!");
1140       }
1141     }
1142   }
1143
1144   // Build symbol name side-mapping if there is one.
1145   if (SymbolTableSectionHeaderIndex) {
1146     const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
1147                                       SymbolTableSectionHeaderIndex->sh_offset);
1148     error_code ec;
1149     for (symbol_iterator si = begin_symbols(),
1150                          se = end_symbols(); si != se; si.increment(ec)) {
1151       if (ec)
1152         report_fatal_error("Fewer extended symbol table entries than symbols!");
1153       if (*ShndxTable != ELF::SHN_UNDEF)
1154         ExtendedSymbolTable[getSymbol(si->getRawDataRefImpl())] = *ShndxTable;
1155       ++ShndxTable;
1156     }
1157   }
1158 }
1159
1160 template<support::endianness target_endianness, bool is64Bits>
1161 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1162                              ::begin_symbols() const {
1163   DataRefImpl SymbolData;
1164   memset(&SymbolData, 0, sizeof(SymbolData));
1165   if (SymbolTableSections.size() == 0) {
1166     SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1167     SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1168   } else {
1169     SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
1170     SymbolData.d.b = 0;
1171   }
1172   return symbol_iterator(SymbolRef(SymbolData, this));
1173 }
1174
1175 template<support::endianness target_endianness, bool is64Bits>
1176 symbol_iterator ELFObjectFile<target_endianness, is64Bits>
1177                              ::end_symbols() const {
1178   DataRefImpl SymbolData;
1179   memset(&SymbolData, 0, sizeof(SymbolData));
1180   SymbolData.d.a = std::numeric_limits<uint32_t>::max();
1181   SymbolData.d.b = std::numeric_limits<uint32_t>::max();
1182   return symbol_iterator(SymbolRef(SymbolData, this));
1183 }
1184
1185 template<support::endianness target_endianness, bool is64Bits>
1186 section_iterator ELFObjectFile<target_endianness, is64Bits>
1187                               ::begin_sections() const {
1188   DataRefImpl ret;
1189   memset(&ret, 0, sizeof(DataRefImpl));
1190   ret.p = reinterpret_cast<intptr_t>(base() + Header->e_shoff);
1191   return section_iterator(SectionRef(ret, this));
1192 }
1193
1194 template<support::endianness target_endianness, bool is64Bits>
1195 section_iterator ELFObjectFile<target_endianness, is64Bits>
1196                               ::end_sections() const {
1197   DataRefImpl ret;
1198   memset(&ret, 0, sizeof(DataRefImpl));
1199   ret.p = reinterpret_cast<intptr_t>(base()
1200                                      + Header->e_shoff
1201                                      + (Header->e_shentsize * Header->e_shnum));
1202   return section_iterator(SectionRef(ret, this));
1203 }
1204
1205 template<support::endianness target_endianness, bool is64Bits>
1206 uint8_t ELFObjectFile<target_endianness, is64Bits>::getBytesInAddress() const {
1207   return is64Bits ? 8 : 4;
1208 }
1209
1210 template<support::endianness target_endianness, bool is64Bits>
1211 StringRef ELFObjectFile<target_endianness, is64Bits>
1212                        ::getFileFormatName() const {
1213   switch(Header->e_ident[ELF::EI_CLASS]) {
1214   case ELF::ELFCLASS32:
1215     switch(Header->e_machine) {
1216     case ELF::EM_386:
1217       return "ELF32-i386";
1218     case ELF::EM_X86_64:
1219       return "ELF32-x86-64";
1220     case ELF::EM_ARM:
1221       return "ELF32-arm";
1222     default:
1223       return "ELF32-unknown";
1224     }
1225   case ELF::ELFCLASS64:
1226     switch(Header->e_machine) {
1227     case ELF::EM_386:
1228       return "ELF64-i386";
1229     case ELF::EM_X86_64:
1230       return "ELF64-x86-64";
1231     default:
1232       return "ELF64-unknown";
1233     }
1234   default:
1235     // FIXME: Proper error handling.
1236     report_fatal_error("Invalid ELFCLASS!");
1237   }
1238 }
1239
1240 template<support::endianness target_endianness, bool is64Bits>
1241 unsigned ELFObjectFile<target_endianness, is64Bits>::getArch() const {
1242   switch(Header->e_machine) {
1243   case ELF::EM_386:
1244     return Triple::x86;
1245   case ELF::EM_X86_64:
1246     return Triple::x86_64;
1247   case ELF::EM_ARM:
1248     return Triple::arm;
1249   default:
1250     return Triple::UnknownArch;
1251   }
1252 }
1253
1254
1255 template<support::endianness target_endianness, bool is64Bits>
1256 template<typename T>
1257 inline const T *
1258 ELFObjectFile<target_endianness, is64Bits>::getEntry(uint16_t Section,
1259                                                      uint32_t Entry) const {
1260   return getEntry<T>(getSection(Section), Entry);
1261 }
1262
1263 template<support::endianness target_endianness, bool is64Bits>
1264 template<typename T>
1265 inline const T *
1266 ELFObjectFile<target_endianness, is64Bits>::getEntry(const Elf_Shdr * Section,
1267                                                      uint32_t Entry) const {
1268   return reinterpret_cast<const T *>(
1269            base()
1270            + Section->sh_offset
1271            + (Entry * Section->sh_entsize));
1272 }
1273
1274 template<support::endianness target_endianness, bool is64Bits>
1275 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
1276 ELFObjectFile<target_endianness, is64Bits>::getSymbol(DataRefImpl Symb) const {
1277   return getEntry<Elf_Sym>(SymbolTableSections[Symb.d.b], Symb.d.a);
1278 }
1279
1280 template<support::endianness target_endianness, bool is64Bits>
1281 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rel *
1282 ELFObjectFile<target_endianness, is64Bits>::getRel(DataRefImpl Rel) const {
1283   return getEntry<Elf_Rel>(Rel.w.b, Rel.w.c);
1284 }
1285
1286 template<support::endianness target_endianness, bool is64Bits>
1287 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rela *
1288 ELFObjectFile<target_endianness, is64Bits>::getRela(DataRefImpl Rela) const {
1289   return getEntry<Elf_Rela>(Rela.w.b, Rela.w.c);
1290 }
1291
1292 template<support::endianness target_endianness, bool is64Bits>
1293 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
1294 ELFObjectFile<target_endianness, is64Bits>::getSection(DataRefImpl Symb) const {
1295   const Elf_Shdr *sec = getSection(Symb.d.b);
1296   if (sec->sh_type != ELF::SHT_SYMTAB || sec->sh_type != ELF::SHT_DYNSYM)
1297     // FIXME: Proper error handling.
1298     report_fatal_error("Invalid symbol table section!");
1299   return sec;
1300 }
1301
1302 template<support::endianness target_endianness, bool is64Bits>
1303 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
1304 ELFObjectFile<target_endianness, is64Bits>::getSection(uint16_t index) const {
1305   if (index == 0 || index >= ELF::SHN_LORESERVE)
1306     return 0;
1307   if (!SectionHeaderTable || index >= Header->e_shnum)
1308     // FIXME: Proper error handling.
1309     report_fatal_error("Invalid section index!");
1310
1311   return reinterpret_cast<const Elf_Shdr *>(
1312          reinterpret_cast<const char *>(SectionHeaderTable)
1313          + (index * Header->e_shentsize));
1314 }
1315
1316 template<support::endianness target_endianness, bool is64Bits>
1317 const char *ELFObjectFile<target_endianness, is64Bits>
1318                          ::getString(uint16_t section,
1319                                      ELF::Elf32_Word offset) const {
1320   return getString(getSection(section), offset);
1321 }
1322
1323 template<support::endianness target_endianness, bool is64Bits>
1324 const char *ELFObjectFile<target_endianness, is64Bits>
1325                          ::getString(const Elf_Shdr *section,
1326                                      ELF::Elf32_Word offset) const {
1327   assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
1328   if (offset >= section->sh_size)
1329     // FIXME: Proper error handling.
1330     report_fatal_error("Symbol name offset outside of string table!");
1331   return (const char *)base() + section->sh_offset + offset;
1332 }
1333
1334 template<support::endianness target_endianness, bool is64Bits>
1335 error_code ELFObjectFile<target_endianness, is64Bits>
1336                         ::getSymbolName(const Elf_Sym *symb,
1337                                         StringRef &Result) const {
1338   if (symb->st_name == 0) {
1339     const Elf_Shdr *section = getSection(getSymbolTableIndex(symb));
1340     if (!section)
1341       Result = "";
1342     else
1343       Result = getString(dot_shstrtab_sec, section->sh_name);
1344     return object_error::success;
1345   }
1346
1347   // Use the default symbol table name section.
1348   Result = getString(dot_strtab_sec, symb->st_name);
1349   return object_error::success;
1350 }
1351
1352 // EI_CLASS, EI_DATA.
1353 static std::pair<unsigned char, unsigned char>
1354 getElfArchType(MemoryBuffer *Object) {
1355   if (Object->getBufferSize() < ELF::EI_NIDENT)
1356     return std::make_pair((uint8_t)ELF::ELFCLASSNONE,(uint8_t)ELF::ELFDATANONE);
1357   return std::make_pair( (uint8_t)Object->getBufferStart()[ELF::EI_CLASS]
1358                        , (uint8_t)Object->getBufferStart()[ELF::EI_DATA]);
1359 }
1360
1361 namespace llvm {
1362
1363   ObjectFile *ObjectFile::createELFObjectFile(MemoryBuffer *Object) {
1364     std::pair<unsigned char, unsigned char> Ident = getElfArchType(Object);
1365     error_code ec;
1366     if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB)
1367       return new ELFObjectFile<support::little, false>(Object, ec);
1368     else if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB)
1369       return new ELFObjectFile<support::big, false>(Object, ec);
1370     else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB)
1371       return new ELFObjectFile<support::little, true>(Object, ec);
1372     else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB)
1373       return new ELFObjectFile<support::big, true>(Object, ec);
1374     // FIXME: Proper error handling.
1375     report_fatal_error("Not an ELF object file!");
1376   }
1377
1378 } // end namespace llvm