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