Add support for relocations to ObjectFile.
[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 <limits>
24 #include <utility>
25
26 using namespace llvm;
27 using namespace object;
28
29 // Templates to choose Elf_Addr and Elf_Off depending on is64Bits.
30 namespace {
31 template<support::endianness target_endianness>
32 struct ELFDataTypeTypedefHelperCommon {
33   typedef support::detail::packed_endian_specific_integral
34     <uint16_t, target_endianness, support::aligned> Elf_Half;
35   typedef support::detail::packed_endian_specific_integral
36     <uint32_t, target_endianness, support::aligned> Elf_Word;
37   typedef support::detail::packed_endian_specific_integral
38     <int32_t, target_endianness, support::aligned> Elf_Sword;
39   typedef support::detail::packed_endian_specific_integral
40     <uint64_t, target_endianness, support::aligned> Elf_Xword;
41   typedef support::detail::packed_endian_specific_integral
42     <int64_t, target_endianness, support::aligned> Elf_Sxword;
43 };
44 }
45
46 namespace {
47 template<support::endianness target_endianness, bool is64Bits>
48 struct ELFDataTypeTypedefHelper;
49
50 /// ELF 32bit types.
51 template<support::endianness target_endianness>
52 struct ELFDataTypeTypedefHelper<target_endianness, false>
53   : ELFDataTypeTypedefHelperCommon<target_endianness> {
54   typedef support::detail::packed_endian_specific_integral
55     <uint32_t, target_endianness, support::aligned> Elf_Addr;
56   typedef support::detail::packed_endian_specific_integral
57     <uint32_t, target_endianness, support::aligned> Elf_Off;
58 };
59
60 /// ELF 64bit types.
61 template<support::endianness target_endianness>
62 struct ELFDataTypeTypedefHelper<target_endianness, true>
63   : ELFDataTypeTypedefHelperCommon<target_endianness>{
64   typedef support::detail::packed_endian_specific_integral
65     <uint64_t, target_endianness, support::aligned> Elf_Addr;
66   typedef support::detail::packed_endian_specific_integral
67     <uint64_t, target_endianness, support::aligned> Elf_Off;
68 };
69 }
70
71 // I really don't like doing this, but the alternative is copypasta.
72 #define LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits) \
73 typedef typename \
74   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Addr Elf_Addr; \
75 typedef typename \
76   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Off Elf_Off; \
77 typedef typename \
78   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Half Elf_Half; \
79 typedef typename \
80   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Word Elf_Word; \
81 typedef typename \
82   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sword Elf_Sword; \
83 typedef typename \
84   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Xword Elf_Xword; \
85 typedef typename \
86   ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sxword Elf_Sxword;
87
88   // Section header.
89 namespace {
90 template<support::endianness target_endianness, bool is64Bits>
91 struct Elf_Shdr_Base;
92
93 template<support::endianness target_endianness>
94 struct Elf_Shdr_Base<target_endianness, false> {
95   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
96   Elf_Word sh_name;     // Section name (index into string table)
97   Elf_Word sh_type;     // Section type (SHT_*)
98   Elf_Word sh_flags;    // Section flags (SHF_*)
99   Elf_Addr sh_addr;     // Address where section is to be loaded
100   Elf_Off  sh_offset;   // File offset of section data, in bytes
101   Elf_Word sh_size;     // Size of section, in bytes
102   Elf_Word sh_link;     // Section type-specific header table index link
103   Elf_Word sh_info;     // Section type-specific extra information
104   Elf_Word sh_addralign;// Section address alignment
105   Elf_Word sh_entsize;  // Size of records contained within the section
106 };
107
108 template<support::endianness target_endianness>
109 struct Elf_Shdr_Base<target_endianness, true> {
110   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
111   Elf_Word  sh_name;     // Section name (index into string table)
112   Elf_Word  sh_type;     // Section type (SHT_*)
113   Elf_Xword sh_flags;    // Section flags (SHF_*)
114   Elf_Addr  sh_addr;     // Address where section is to be loaded
115   Elf_Off   sh_offset;   // File offset of section data, in bytes
116   Elf_Xword sh_size;     // Size of section, in bytes
117   Elf_Word  sh_link;     // Section type-specific header table index link
118   Elf_Word  sh_info;     // Section type-specific extra information
119   Elf_Xword sh_addralign;// Section address alignment
120   Elf_Xword sh_entsize;  // Size of records contained within the section
121 };
122
123 template<support::endianness target_endianness, bool is64Bits>
124 struct Elf_Shdr_Impl : Elf_Shdr_Base<target_endianness, is64Bits> {
125   using Elf_Shdr_Base<target_endianness, is64Bits>::sh_entsize;
126   using Elf_Shdr_Base<target_endianness, is64Bits>::sh_size;
127
128   /// @brief Get the number of entities this section contains if it has any.
129   unsigned getEntityCount() const {
130     if (sh_entsize == 0)
131       return 0;
132     return sh_size / sh_entsize;
133   }
134 };
135 }
136
137 namespace {
138 template<support::endianness target_endianness, bool is64Bits>
139 struct Elf_Sym_Base;
140
141 template<support::endianness target_endianness>
142 struct Elf_Sym_Base<target_endianness, false> {
143   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
144   Elf_Word      st_name;  // Symbol name (index into string table)
145   Elf_Addr      st_value; // Value or address associated with the symbol
146   Elf_Word      st_size;  // Size of the symbol
147   unsigned char st_info;  // Symbol's type and binding attributes
148   unsigned char st_other; // Must be zero; reserved
149   Elf_Half      st_shndx; // Which section (header table index) it's defined in
150 };
151
152 template<support::endianness target_endianness>
153 struct Elf_Sym_Base<target_endianness, true> {
154   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
155   Elf_Word      st_name;  // Symbol name (index into string table)
156   unsigned char st_info;  // Symbol's type and binding attributes
157   unsigned char st_other; // Must be zero; reserved
158   Elf_Half      st_shndx; // Which section (header table index) it's defined in
159   Elf_Addr      st_value; // Value or address associated with the symbol
160   Elf_Xword     st_size;  // Size of the symbol
161 };
162
163 template<support::endianness target_endianness, bool is64Bits>
164 struct Elf_Sym_Impl : Elf_Sym_Base<target_endianness, is64Bits> {
165   using Elf_Sym_Base<target_endianness, is64Bits>::st_info;
166
167   // These accessors and mutators correspond to the ELF32_ST_BIND,
168   // ELF32_ST_TYPE, and ELF32_ST_INFO macros defined in the ELF specification:
169   unsigned char getBinding() const { return st_info >> 4; }
170   unsigned char getType() const { return st_info & 0x0f; }
171   void setBinding(unsigned char b) { setBindingAndType(b, getType()); }
172   void setType(unsigned char t) { setBindingAndType(getBinding(), t); }
173   void setBindingAndType(unsigned char b, unsigned char t) {
174     st_info = (b << 4) + (t & 0x0f);
175   }
176 };
177 }
178
179 namespace {
180 template<support::endianness target_endianness, bool is64Bits, bool isRela>
181 struct Elf_Rel_Base;
182
183 template<support::endianness target_endianness>
184 struct Elf_Rel_Base<target_endianness, false, false> {
185   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
186   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
187   Elf_Word      r_info;  // Symbol table index and type of relocation to apply
188 };
189
190 template<support::endianness target_endianness>
191 struct Elf_Rel_Base<target_endianness, true, false> {
192   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
193   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
194   Elf_Xword     r_info;   // Symbol table index and type of relocation to apply
195 };
196
197 template<support::endianness target_endianness>
198 struct Elf_Rel_Base<target_endianness, false, true> {
199   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
200   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
201   Elf_Word      r_info;   // Symbol table index and type of relocation to apply
202   Elf_Sword     r_addend; // Compute value for relocatable field by adding this
203 };
204
205 template<support::endianness target_endianness>
206 struct Elf_Rel_Base<target_endianness, true, true> {
207   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
208   Elf_Addr      r_offset; // Location (file byte offset, or program virtual addr)
209   Elf_Xword     r_info;   // Symbol table index and type of relocation to apply
210   Elf_Sxword    r_addend; // Compute value for relocatable field by adding this.
211 };
212
213 template<support::endianness target_endianness, bool is64Bits, bool isRela>
214 struct Elf_Rel_Impl;
215
216 template<support::endianness target_endianness, bool isRela>
217 struct Elf_Rel_Impl<target_endianness, true, isRela>
218        : Elf_Rel_Base<target_endianness, true, isRela> {
219   using Elf_Rel_Base<target_endianness, true, isRela>::r_info;
220   LLVM_ELF_IMPORT_TYPES(target_endianness, true)
221
222   // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_TYPE,
223   // and ELF64_R_INFO macros defined in the ELF specification:
224   uint64_t getSymbol() const { return (r_info >> 32); }
225   unsigned char getType() const {
226     return (unsigned char) (r_info & 0xffffffffL);
227   }
228   void setSymbol(uint64_t s) { setSymbolAndType(s, getType()); }
229   void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
230   void setSymbolAndType(uint64_t s, unsigned char t) {
231     r_info = (s << 32) + (t&0xffffffffL);
232   }
233 };
234
235 template<support::endianness target_endianness, bool isRela>
236 struct Elf_Rel_Impl<target_endianness, false, isRela>
237        : Elf_Rel_Base<target_endianness, false, isRela> {
238   using Elf_Rel_Base<target_endianness, false, isRela>::r_info;
239   LLVM_ELF_IMPORT_TYPES(target_endianness, false)
240
241   // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_TYPE,
242   // and ELF32_R_INFO macros defined in the ELF specification:
243   uint32_t getSymbol() const { return (r_info >> 8); }
244   unsigned char getType() const { return (unsigned char) (r_info & 0x0ff); }
245   void setSymbol(uint32_t s) { setSymbolAndType(s, getType()); }
246   void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
247   void setSymbolAndType(uint32_t s, unsigned char t) {
248     r_info = (s << 8) + t;
249   }
250 };
251
252 }
253
254 namespace {
255 template<support::endianness target_endianness, bool is64Bits>
256 class ELFObjectFile : public ObjectFile {
257   LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
258
259   typedef Elf_Shdr_Impl<target_endianness, is64Bits> Elf_Shdr;
260   typedef Elf_Sym_Impl<target_endianness, is64Bits> Elf_Sym;
261   typedef Elf_Rel_Impl<target_endianness, is64Bits, false> Elf_Rel;
262   typedef Elf_Rel_Impl<target_endianness, is64Bits, true> Elf_Rela;
263
264   struct Elf_Ehdr {
265     unsigned char e_ident[ELF::EI_NIDENT]; // ELF Identification bytes
266     Elf_Half e_type;     // Type of file (see ET_*)
267     Elf_Half e_machine;  // Required architecture for this file (see EM_*)
268     Elf_Word e_version;  // Must be equal to 1
269     Elf_Addr e_entry;    // Address to jump to in order to start program
270     Elf_Off  e_phoff;    // Program header table's file offset, in bytes
271     Elf_Off  e_shoff;    // Section header table's file offset, in bytes
272     Elf_Word e_flags;    // Processor-specific flags
273     Elf_Half e_ehsize;   // Size of ELF header, in bytes
274     Elf_Half e_phentsize;// Size of an entry in the program header table
275     Elf_Half e_phnum;    // Number of entries in the program header table
276     Elf_Half e_shentsize;// Size of an entry in the section header table
277     Elf_Half e_shnum;    // Number of entries in the section header table
278     Elf_Half e_shstrndx; // Section header table index of section name
279                                   // string table
280     bool checkMagic() const {
281       return (memcmp(e_ident, ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
282     }
283     unsigned char getFileClass() const { return e_ident[ELF::EI_CLASS]; }
284     unsigned char getDataEncoding() const { return e_ident[ELF::EI_DATA]; }
285   };
286
287   typedef SmallVector<const Elf_Shdr*, 1> Sections_t;
288   typedef DenseMap<unsigned, unsigned> IndexMap_t;
289
290   const Elf_Ehdr *Header;
291   const Elf_Shdr *SectionHeaderTable;
292   const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
293   const Elf_Shdr *dot_strtab_sec;   // Symbol header string table.
294   Sections_t SymbolTableSections;
295   IndexMap_t SymbolTableSectionsIndexMap;
296   Sections_t RelocationTableSections;
297
298   void            validateSymbol(DataRefImpl Symb) const;
299   bool            isRelocationHasAddend(DataRefImpl Rel) const;
300   template<typename T>
301   const T        *getEntry(DataRefImpl Entry, Sections_t Sections) const;
302   const Elf_Sym  *getSymbol(DataRefImpl Symb) const;
303   const Elf_Shdr *getSection(DataRefImpl index) const;
304   const Elf_Shdr *getSection(uint16_t index) const;
305   const Elf_Rel  *getRel(DataRefImpl Rel) const;
306   const Elf_Rela *getRela(DataRefImpl Rela) const;
307   const char     *getString(uint16_t section, uint32_t offset) const;
308   const char     *getString(const Elf_Shdr *section, uint32_t offset) const;
309
310 protected:
311   virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
312   virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
313   virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const;
314   virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
315   virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const;
316   virtual error_code isSymbolInternal(DataRefImpl Symb, bool &Res) const;
317
318   virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
319   virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
320   virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
321   virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
322   virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
323   virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
324   virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
325                                            bool &Result) const;
326
327   virtual error_code getRelocationNext(DataRefImpl Rel,
328                                        RelocationRef &Res) const;
329   virtual error_code getRelocationAddress(DataRefImpl Rel,
330                                           uint64_t &Res) const;
331   virtual error_code getRelocationSymbol(DataRefImpl Rel,
332                                          SymbolRef &Res) const;
333   virtual error_code getRelocationType(DataRefImpl Rel,
334                                        uint32_t &Res) const;
335   virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
336                                                  int64_t &Res) const;
337
338 public:
339   ELFObjectFile(MemoryBuffer *Object, error_code &ec);
340   virtual symbol_iterator begin_symbols() const;
341   virtual symbol_iterator end_symbols() const;
342   virtual section_iterator begin_sections() const;
343   virtual section_iterator end_sections() const;
344   virtual relocation_iterator begin_relocations() const;
345   virtual relocation_iterator end_relocations() const;
346
347   virtual uint8_t getBytesInAddress() const;
348   virtual StringRef getFileFormatName() const;
349   virtual unsigned getArch() const;
350 };
351 } // end namespace
352
353 template<support::endianness target_endianness, bool is64Bits>
354 void ELFObjectFile<target_endianness, is64Bits>
355                   ::validateSymbol(DataRefImpl Symb) const {
356   const Elf_Sym  *symb = getSymbol(Symb);
357   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
358   // FIXME: We really need to do proper error handling in the case of an invalid
359   //        input file. Because we don't use exceptions, I think we'll just pass
360   //        an error object around.
361   if (!(  symb
362         && SymbolTableSection
363         && symb >= (const Elf_Sym*)(base()
364                    + SymbolTableSection->sh_offset)
365         && symb <  (const Elf_Sym*)(base()
366                    + SymbolTableSection->sh_offset
367                    + SymbolTableSection->sh_size)))
368     // FIXME: Proper error handling.
369     report_fatal_error("Symb must point to a valid symbol!");
370 }
371
372 template<support::endianness target_endianness, bool is64Bits>
373 error_code ELFObjectFile<target_endianness, is64Bits>
374                         ::getSymbolNext(DataRefImpl Symb,
375                                         SymbolRef &Result) const {
376   validateSymbol(Symb);
377   const Elf_Shdr *SymbolTableSection = SymbolTableSections[Symb.d.b];
378
379   ++Symb.d.a;
380   // Check to see if we are at the end of this symbol table.
381   if (Symb.d.a >= SymbolTableSection->getEntityCount()) {
382     // We are at the end. If there are other symbol tables, jump to them.
383     ++Symb.d.b;
384     Symb.d.a = 1; // The 0th symbol in ELF is fake.
385     // Otherwise return the terminator.
386     if (Symb.d.b >= SymbolTableSections.size()) {
387       Symb.d.a = std::numeric_limits<uint32_t>::max();
388       Symb.d.b = std::numeric_limits<uint32_t>::max();
389     }
390   }
391
392   Result = SymbolRef(Symb, this);
393   return object_error::success;
394 }
395
396 template<support::endianness target_endianness, bool is64Bits>
397 error_code ELFObjectFile<target_endianness, is64Bits>
398                         ::getSymbolName(DataRefImpl Symb,
399                                         StringRef &Result) const {
400   validateSymbol(Symb);
401   const Elf_Sym  *symb = getSymbol(Symb);
402   if (symb->st_name == 0) {
403     const Elf_Shdr *section = getSection(symb->st_shndx);
404     if (!section)
405       Result = "";
406     else
407       Result = getString(dot_shstrtab_sec, section->sh_name);
408     return object_error::success;
409   }
410
411   // Use the default symbol table name section.
412   Result = getString(dot_strtab_sec, symb->st_name);
413   return object_error::success;
414 }
415
416 template<support::endianness target_endianness, bool is64Bits>
417 error_code ELFObjectFile<target_endianness, is64Bits>
418                         ::getSymbolAddress(DataRefImpl Symb,
419                                            uint64_t &Result) const {
420   validateSymbol(Symb);
421   const Elf_Sym  *symb = getSymbol(Symb);
422   const Elf_Shdr *Section;
423   switch (symb->st_shndx) {
424   case ELF::SHN_COMMON:
425    // Undefined symbols have no address yet.
426   case ELF::SHN_UNDEF:
427     Result = UnknownAddressOrSize;
428     return object_error::success;
429   case ELF::SHN_ABS:
430     Result = symb->st_value;
431     return object_error::success;
432   default: Section = getSection(symb->st_shndx);
433   }
434
435   switch (symb->getType()) {
436   case ELF::STT_SECTION:
437     Result = Section ? Section->sh_addr : UnknownAddressOrSize;
438     return object_error::success;
439   case ELF::STT_FUNC:
440   case ELF::STT_OBJECT:
441   case ELF::STT_NOTYPE:
442     Result = symb->st_value;
443     return object_error::success;
444   default:
445     Result = UnknownAddressOrSize;
446     return object_error::success;
447   }
448 }
449
450 template<support::endianness target_endianness, bool is64Bits>
451 error_code ELFObjectFile<target_endianness, is64Bits>
452                         ::getSymbolSize(DataRefImpl Symb,
453                                         uint64_t &Result) const {
454   validateSymbol(Symb);
455   const Elf_Sym  *symb = getSymbol(Symb);
456   if (symb->st_size == 0)
457     Result = UnknownAddressOrSize;
458   Result = symb->st_size;
459   return object_error::success;
460 }
461
462 template<support::endianness target_endianness, bool is64Bits>
463 error_code ELFObjectFile<target_endianness, is64Bits>
464                         ::getSymbolNMTypeChar(DataRefImpl Symb,
465                                               char &Result) const {
466   validateSymbol(Symb);
467   const Elf_Sym  *symb = getSymbol(Symb);
468   const Elf_Shdr *Section = getSection(symb->st_shndx);
469
470   char ret = '?';
471
472   if (Section) {
473     switch (Section->sh_type) {
474     case ELF::SHT_PROGBITS:
475     case ELF::SHT_DYNAMIC:
476       switch (Section->sh_flags) {
477       case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
478         ret = 't'; break;
479       case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
480         ret = 'd'; break;
481       case ELF::SHF_ALLOC:
482       case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
483       case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
484         ret = 'r'; break;
485       }
486       break;
487     case ELF::SHT_NOBITS: ret = 'b';
488     }
489   }
490
491   switch (symb->st_shndx) {
492   case ELF::SHN_UNDEF:
493     if (ret == '?')
494       ret = 'U';
495     break;
496   case ELF::SHN_ABS: ret = 'a'; break;
497   case ELF::SHN_COMMON: ret = 'c'; break;
498   }
499
500   switch (symb->getBinding()) {
501   case ELF::STB_GLOBAL: ret = ::toupper(ret); break;
502   case ELF::STB_WEAK:
503     if (symb->st_shndx == ELF::SHN_UNDEF)
504       ret = 'w';
505     else
506       if (symb->getType() == ELF::STT_OBJECT)
507         ret = 'V';
508       else
509         ret = 'W';
510   }
511
512   if (ret == '?' && symb->getType() == ELF::STT_SECTION) {
513     StringRef name;
514     if (error_code ec = getSymbolName(Symb, name))
515       return ec;
516     Result = StringSwitch<char>(name)
517       .StartsWith(".debug", 'N')
518       .StartsWith(".note", 'n')
519       .Default('?');
520     return object_error::success;
521   }
522
523   Result = ret;
524   return object_error::success;
525 }
526
527 template<support::endianness target_endianness, bool is64Bits>
528 error_code ELFObjectFile<target_endianness, is64Bits>
529                         ::isSymbolInternal(DataRefImpl Symb,
530                                            bool &Result) const {
531   validateSymbol(Symb);
532   const Elf_Sym  *symb = getSymbol(Symb);
533
534   if (  symb->getType() == ELF::STT_FILE
535      || symb->getType() == ELF::STT_SECTION)
536     Result = true;
537   Result = false;
538   return object_error::success;
539 }
540
541 template<support::endianness target_endianness, bool is64Bits>
542 error_code ELFObjectFile<target_endianness, is64Bits>
543                         ::getSectionNext(DataRefImpl Sec, SectionRef &Result) const {
544   const uint8_t *sec = reinterpret_cast<const uint8_t *>(Sec.p);
545   sec += Header->e_shentsize;
546   Sec.p = reinterpret_cast<intptr_t>(sec);
547   Result = SectionRef(Sec, this);
548   return object_error::success;
549 }
550
551 template<support::endianness target_endianness, bool is64Bits>
552 error_code ELFObjectFile<target_endianness, is64Bits>
553                         ::getSectionName(DataRefImpl Sec,
554                                          StringRef &Result) const {
555   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
556   Result = StringRef(getString(dot_shstrtab_sec, sec->sh_name));
557   return object_error::success;
558 }
559
560 template<support::endianness target_endianness, bool is64Bits>
561 error_code ELFObjectFile<target_endianness, is64Bits>
562                         ::getSectionAddress(DataRefImpl Sec,
563                                             uint64_t &Result) const {
564   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
565   Result = sec->sh_addr;
566   return object_error::success;
567 }
568
569 template<support::endianness target_endianness, bool is64Bits>
570 error_code ELFObjectFile<target_endianness, is64Bits>
571                         ::getSectionSize(DataRefImpl Sec,
572                                          uint64_t &Result) const {
573   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
574   Result = sec->sh_size;
575   return object_error::success;
576 }
577
578 template<support::endianness target_endianness, bool is64Bits>
579 error_code ELFObjectFile<target_endianness, is64Bits>
580                         ::getSectionContents(DataRefImpl Sec,
581                                              StringRef &Result) const {
582   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
583   const char *start = (const char*)base() + sec->sh_offset;
584   Result = StringRef(start, sec->sh_size);
585   return object_error::success;
586 }
587
588 template<support::endianness target_endianness, bool is64Bits>
589 error_code ELFObjectFile<target_endianness, is64Bits>
590                         ::isSectionText(DataRefImpl Sec,
591                                         bool &Result) const {
592   const Elf_Shdr *sec = reinterpret_cast<const Elf_Shdr *>(Sec.p);
593   if (sec->sh_flags & ELF::SHF_EXECINSTR)
594     Result = true;
595   else
596     Result = false;
597   return object_error::success;
598 }
599
600 template<support::endianness target_endianness, bool is64Bits>
601 error_code ELFObjectFile<target_endianness, is64Bits>
602                           ::sectionContainsSymbol(DataRefImpl Sec,
603                                                   DataRefImpl Symb,
604                                                   bool &Result) const {
605   // FIXME: Unimplemented.
606   Result = false;
607   return object_error::success;
608 }
609
610 // Relocations
611 template<support::endianness target_endianness, bool is64Bits>
612 error_code ELFObjectFile<target_endianness, is64Bits>
613                         ::getRelocationNext(DataRefImpl Rel,
614                                             RelocationRef &Result) const {
615   const Elf_Shdr *RelocationTableSection = RelocationTableSections[Rel.d.b];
616
617   // Check to see if we are at the end of this relocation table.
618   if (++Rel.d.a >= RelocationTableSection->getEntityCount()) {
619     // We are at the end. If there are other relocation tables, jump to them.
620     Rel.d.a = 0;
621     // Otherwise return the terminator.
622     if (++Rel.d.b >= SymbolTableSections.size()) {
623       Rel.d.a = std::numeric_limits<uint32_t>::max();
624       Rel.d.b = std::numeric_limits<uint32_t>::max();
625     }
626   }
627
628   Result = RelocationRef(Rel, this);
629   return object_error::success;
630 }
631
632 template<support::endianness target_endianness, bool is64Bits>
633 error_code ELFObjectFile<target_endianness, is64Bits>
634                         ::getRelocationSymbol(DataRefImpl Rel,
635                                               SymbolRef &Result) const {
636   uint32_t symbolIdx;
637   const Elf_Shdr *sec = RelocationTableSections[Rel.d.b];
638   switch (sec->sh_type) {
639     default :
640       report_fatal_error("Invalid section type in Rel!");
641     case ELF::SHT_REL : {
642       symbolIdx = getRel(Rel)->getSymbol();
643       break;
644     }
645     case ELF::SHT_RELA : {
646       symbolIdx = getRela(Rel)->getSymbol();
647       break;
648     }
649   }
650   DataRefImpl SymbolData;
651   IndexMap_t::const_iterator it = SymbolTableSectionsIndexMap.find(sec->sh_link);
652   if (it == SymbolTableSectionsIndexMap.end())
653     report_fatal_error("Relocation symbol table not found!");
654   SymbolData.d.a = symbolIdx;
655   SymbolData.d.b = it->second;
656   Result = SymbolRef(SymbolData, this);
657   return object_error::success;
658 }
659
660 template<support::endianness target_endianness, bool is64Bits>
661 error_code ELFObjectFile<target_endianness, is64Bits>
662                         ::getRelocationAddress(DataRefImpl Rel,
663                                                uint64_t &Result) const {
664   uint64_t offset;
665   const Elf_Shdr *sec = RelocationTableSections[Rel.d.b];
666   switch (sec->sh_type) {
667     default :
668       report_fatal_error("Invalid section type in Rel!");
669     case ELF::SHT_REL : {
670       offset = getRel(Rel)->r_offset;
671       break;
672     }
673     case ELF::SHT_RELA : {
674       offset = getRela(Rel)->r_offset;
675       break;
676     }
677   }
678
679   const Elf_Shdr *secAddr = getSection(sec->sh_info);
680   Result = offset + reinterpret_cast<uintptr_t>(base() + secAddr->sh_offset);
681   return object_error::success;
682 }
683
684 template<support::endianness target_endianness, bool is64Bits>
685 error_code ELFObjectFile<target_endianness, is64Bits>
686                         ::getRelocationType(DataRefImpl Rel,
687                                             uint32_t &Result) const {
688   const Elf_Shdr *sec = RelocationTableSections[Rel.d.b];
689   switch (sec->sh_type) {
690     default :
691       report_fatal_error("Invalid section type in Rel!");
692     case ELF::SHT_REL : {
693       Result = getRel(Rel)->getType();
694       break;
695     }
696     case ELF::SHT_RELA : {
697       Result = getRela(Rel)->getType();
698       break;
699     }
700   }
701   return object_error::success;
702 }
703
704 template<support::endianness target_endianness, bool is64Bits>
705 error_code ELFObjectFile<target_endianness, is64Bits>
706                         ::getRelocationAdditionalInfo(DataRefImpl Rel,
707                                                       int64_t &Result) const {
708   const Elf_Shdr *sec = RelocationTableSections[Rel.d.b];
709   switch (sec->sh_type) {
710     default :
711       report_fatal_error("Invalid section type in Rel!");
712     case ELF::SHT_REL : {
713       Result = 0;
714       return object_error::success;
715     }
716     case ELF::SHT_RELA : {
717       Result = getRela(Rel)->r_addend;
718       return object_error::success;
719     }
720   }
721 }
722
723
724
725 template<support::endianness target_endianness, bool is64Bits>
726 ELFObjectFile<target_endianness, is64Bits>::ELFObjectFile(MemoryBuffer *Object
727                                                           , error_code &ec)
728   : ObjectFile(Binary::isELF, Object, ec)
729   , SectionHeaderTable(0)
730   , dot_shstrtab_sec(0)
731   , dot_strtab_sec(0) {
732   Header = reinterpret_cast<const Elf_Ehdr *>(base());
733
734   if (Header->e_shoff == 0)
735     return;
736
737   SectionHeaderTable =
738     reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
739   uint32_t SectionTableSize = Header->e_shnum * Header->e_shentsize;
740   if (!(  (const uint8_t *)SectionHeaderTable + SectionTableSize
741          <= base() + Data->getBufferSize()))
742     // FIXME: Proper error handling.
743     report_fatal_error("Section table goes past end of file!");
744
745
746   // To find the symbol tables we walk the section table to find SHT_STMTAB.
747   const Elf_Shdr* sh =
748                     reinterpret_cast<const Elf_Shdr*>(SectionHeaderTable);
749   for (unsigned i = 0; i < Header->e_shnum; ++i) {
750     if (sh->sh_type == ELF::SHT_SYMTAB) {
751       SymbolTableSectionsIndexMap[i] = SymbolTableSections.size();
752       SymbolTableSections.push_back(sh);
753     }
754     if (sh->sh_type == ELF::SHT_REL || sh->sh_type == ELF::SHT_RELA) {
755       RelocationTableSections.push_back(sh);
756     }
757     ++sh;
758   }
759
760   // Get string table sections.
761   dot_shstrtab_sec = getSection(Header->e_shstrndx);
762   if (dot_shstrtab_sec) {
763     // Verify that the last byte in the string table in a null.
764     if (((const char*)base() + dot_shstrtab_sec->sh_offset)
765         [dot_shstrtab_sec->sh_size - 1] != 0)
766       // FIXME: Proper error handling.
767       report_fatal_error("String table must end with a null terminator!");
768   }
769
770   // Merge this into the above loop.
771   for (const char *i = reinterpret_cast<const char *>(SectionHeaderTable),
772                   *e = i + Header->e_shnum * Header->e_shentsize;
773                    i != e; i += Header->e_shentsize) {
774     const Elf_Shdr *sh = reinterpret_cast<const Elf_Shdr*>(i);
775     if (sh->sh_type == ELF::SHT_STRTAB) {
776       StringRef SectionName(getString(dot_shstrtab_sec, sh->sh_name));
777       if (SectionName == ".strtab") {
778         if (dot_strtab_sec != 0)
779           // FIXME: Proper error handling.
780           report_fatal_error("Already found section named .strtab!");
781         dot_strtab_sec = sh;
782         const char *dot_strtab = (const char*)base() + sh->sh_offset;
783           if (dot_strtab[sh->sh_size - 1] != 0)
784             // FIXME: Proper error handling.
785             report_fatal_error("String table must end with a null terminator!");
786       }
787     }
788   }
789 }
790
791 template<support::endianness target_endianness, bool is64Bits>
792 ObjectFile::symbol_iterator ELFObjectFile<target_endianness, is64Bits>
793                                          ::begin_symbols() const {
794   DataRefImpl SymbolData;
795   memset(&SymbolData, 0, sizeof(SymbolData));
796   if (SymbolTableSections.size() == 0) {
797     SymbolData.d.a = std::numeric_limits<uint32_t>::max();
798     SymbolData.d.b = std::numeric_limits<uint32_t>::max();
799   } else {
800     SymbolData.d.a = 1; // The 0th symbol in ELF is fake.
801     SymbolData.d.b = 0;
802   }
803   return symbol_iterator(SymbolRef(SymbolData, this));
804 }
805
806 template<support::endianness target_endianness, bool is64Bits>
807 ObjectFile::symbol_iterator ELFObjectFile<target_endianness, is64Bits>
808                                          ::end_symbols() const {
809   DataRefImpl SymbolData;
810   memset(&SymbolData, 0, sizeof(SymbolData));
811   SymbolData.d.a = std::numeric_limits<uint32_t>::max();
812   SymbolData.d.b = std::numeric_limits<uint32_t>::max();
813   return symbol_iterator(SymbolRef(SymbolData, this));
814 }
815
816 template<support::endianness target_endianness, bool is64Bits>
817 ObjectFile::section_iterator ELFObjectFile<target_endianness, is64Bits>
818                                           ::begin_sections() const {
819   DataRefImpl ret;
820   memset(&ret, 0, sizeof(DataRefImpl));
821   ret.p = reinterpret_cast<intptr_t>(base() + Header->e_shoff);
822   return section_iterator(SectionRef(ret, this));
823 }
824
825 template<support::endianness target_endianness, bool is64Bits>
826 ObjectFile::section_iterator ELFObjectFile<target_endianness, is64Bits>
827                                           ::end_sections() const {
828   DataRefImpl ret;
829   memset(&ret, 0, sizeof(DataRefImpl));
830   ret.p = reinterpret_cast<intptr_t>(base()
831                                      + Header->e_shoff
832                                      + (Header->e_shentsize * Header->e_shnum));
833   return section_iterator(SectionRef(ret, this));
834 }
835
836 template<support::endianness target_endianness, bool is64Bits>
837 ObjectFile::relocation_iterator ELFObjectFile<target_endianness, is64Bits>
838                                          ::begin_relocations() const {
839   DataRefImpl RelData;
840   memset(&RelData, 0, sizeof(RelData));
841   if (RelocationTableSections.size() == 0) {
842     RelData.d.a = std::numeric_limits<uint32_t>::max();
843     RelData.d.b = std::numeric_limits<uint32_t>::max();
844   } else {
845     RelData.d.a = 0;
846     RelData.d.b = 0;
847   }
848   return relocation_iterator(RelocationRef(RelData, this));
849 }
850
851 template<support::endianness target_endianness, bool is64Bits>
852 ObjectFile::relocation_iterator ELFObjectFile<target_endianness, is64Bits>
853                                          ::end_relocations() const {
854   DataRefImpl RelData;
855   memset(&RelData, 0, sizeof(RelData));
856   RelData.d.a = std::numeric_limits<uint32_t>::max();
857   RelData.d.b = std::numeric_limits<uint32_t>::max();
858   return relocation_iterator(RelocationRef(RelData, this));
859 }
860
861 template<support::endianness target_endianness, bool is64Bits>
862 uint8_t ELFObjectFile<target_endianness, is64Bits>::getBytesInAddress() const {
863   return is64Bits ? 8 : 4;
864 }
865
866 template<support::endianness target_endianness, bool is64Bits>
867 StringRef ELFObjectFile<target_endianness, is64Bits>
868                        ::getFileFormatName() const {
869   switch(Header->e_ident[ELF::EI_CLASS]) {
870   case ELF::ELFCLASS32:
871     switch(Header->e_machine) {
872     case ELF::EM_386:
873       return "ELF32-i386";
874     case ELF::EM_X86_64:
875       return "ELF32-x86-64";
876     case ELF::EM_ARM:
877       return "ELF32-arm";
878     default:
879       return "ELF32-unknown";
880     }
881   case ELF::ELFCLASS64:
882     switch(Header->e_machine) {
883     case ELF::EM_386:
884       return "ELF64-i386";
885     case ELF::EM_X86_64:
886       return "ELF64-x86-64";
887     default:
888       return "ELF64-unknown";
889     }
890   default:
891     // FIXME: Proper error handling.
892     report_fatal_error("Invalid ELFCLASS!");
893   }
894 }
895
896 template<support::endianness target_endianness, bool is64Bits>
897 unsigned ELFObjectFile<target_endianness, is64Bits>::getArch() const {
898   switch(Header->e_machine) {
899   case ELF::EM_386:
900     return Triple::x86;
901   case ELF::EM_X86_64:
902     return Triple::x86_64;
903   case ELF::EM_ARM:
904     return Triple::arm;
905   default:
906     return Triple::UnknownArch;
907   }
908 }
909
910 template<support::endianness target_endianness, bool is64Bits>
911 template<typename T>
912 inline const T *
913 ELFObjectFile<target_endianness, is64Bits>::getEntry(DataRefImpl Entry,
914                                                      Sections_t Sections) const {
915   const Elf_Shdr *sec = Sections[Entry.d.b];
916   return reinterpret_cast<const T *>(
917            base()
918            + sec->sh_offset
919            + (Entry.d.a * sec->sh_entsize));
920 }
921
922 template<support::endianness target_endianness, bool is64Bits>
923 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
924 ELFObjectFile<target_endianness, is64Bits>::getSymbol(DataRefImpl Symb) const {
925   return getEntry<Elf_Sym>(Symb, SymbolTableSections);
926 }
927
928 template<support::endianness target_endianness, bool is64Bits>
929 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rel *
930 ELFObjectFile<target_endianness, is64Bits>::getRel(DataRefImpl Rel) const {
931   return getEntry<Elf_Rel>(Rel, RelocationTableSections);
932 }
933
934 template<support::endianness target_endianness, bool is64Bits>
935 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rela *
936 ELFObjectFile<target_endianness, is64Bits>::getRela(DataRefImpl Rela) const {
937   return getEntry<Elf_Rela>(Rela, RelocationTableSections);
938 }
939
940 template<support::endianness target_endianness, bool is64Bits>
941 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
942 ELFObjectFile<target_endianness, is64Bits>::getSection(DataRefImpl Symb) const {
943   const Elf_Shdr *sec = getSection(Symb.d.b);
944   if (sec->sh_type != ELF::SHT_SYMTAB)
945     // FIXME: Proper error handling.
946     report_fatal_error("Invalid symbol table section!");
947   return sec;
948 }
949
950 template<support::endianness target_endianness, bool is64Bits>
951 const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
952 ELFObjectFile<target_endianness, is64Bits>::getSection(uint16_t index) const {
953   if (index == 0 || index >= ELF::SHN_LORESERVE)
954     return 0;
955   if (!SectionHeaderTable || index >= Header->e_shnum)
956     // FIXME: Proper error handling.
957     report_fatal_error("Invalid section index!");
958
959   return reinterpret_cast<const Elf_Shdr *>(
960          reinterpret_cast<const char *>(SectionHeaderTable)
961          + (index * Header->e_shentsize));
962 }
963
964 template<support::endianness target_endianness, bool is64Bits>
965 const char *ELFObjectFile<target_endianness, is64Bits>
966                          ::getString(uint16_t section,
967                                      ELF::Elf32_Word offset) const {
968   return getString(getSection(section), offset);
969 }
970
971 template<support::endianness target_endianness, bool is64Bits>
972 const char *ELFObjectFile<target_endianness, is64Bits>
973                          ::getString(const Elf_Shdr *section,
974                                      ELF::Elf32_Word offset) const {
975   assert(section && section->sh_type == ELF::SHT_STRTAB && "Invalid section!");
976   if (offset >= section->sh_size)
977     // FIXME: Proper error handling.
978     report_fatal_error("Symbol name offset outside of string table!");
979   return (const char *)base() + section->sh_offset + offset;
980 }
981
982 // EI_CLASS, EI_DATA.
983 static std::pair<unsigned char, unsigned char>
984 getElfArchType(MemoryBuffer *Object) {
985   if (Object->getBufferSize() < ELF::EI_NIDENT)
986     return std::make_pair((uint8_t)ELF::ELFCLASSNONE,(uint8_t)ELF::ELFDATANONE);
987   return std::make_pair( (uint8_t)Object->getBufferStart()[ELF::EI_CLASS]
988                        , (uint8_t)Object->getBufferStart()[ELF::EI_DATA]);
989 }
990
991 namespace llvm {
992
993   ObjectFile *ObjectFile::createELFObjectFile(MemoryBuffer *Object) {
994     std::pair<unsigned char, unsigned char> Ident = getElfArchType(Object);
995     error_code ec;
996     if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB)
997       return new ELFObjectFile<support::little, false>(Object, ec);
998     else if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB)
999       return new ELFObjectFile<support::big, false>(Object, ec);
1000     else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB)
1001       return new ELFObjectFile<support::little, true>(Object, ec);
1002     else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB)
1003       return new ELFObjectFile<support::big, true>(Object, ec);
1004     // FIXME: Proper error handling.
1005     report_fatal_error("Not an ELF object file!");
1006   }
1007
1008 } // end namespace llvm