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