ELFObject.hxx revision 1afb83e8507d8285b12826c7693821e3f25d8d8b
1/*
2 * Copyright 2011, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ELF_OBJECT_HXX
18#define ELF_OBJECT_HXX
19
20#include "ELFHeader.h"
21#include "ELFReloc.h"
22#include "ELFSection.h"
23#include "ELFSectionHeaderTable.h"
24#include "StubLayout.h"
25#include "ELF.h"
26
27#include <llvm/ADT/SmallVector.h>
28
29#include "utils/rsl_assert.h"
30
31template <unsigned Bitwidth>
32template <typename Archiver>
33inline ELFObject<Bitwidth> *
34ELFObject<Bitwidth>::read(Archiver &AR) {
35  llvm::OwningPtr<ELFObjectTy> object(new ELFObjectTy());
36
37  // Read header
38  object->header.reset(ELFHeaderTy::read(AR));
39  if (!object->header) {
40    return 0;
41  }
42
43  // Read section table
44  object->shtab.reset(ELFSectionHeaderTableTy::read(AR, object.get()));
45  if (!object->shtab) {
46    return 0;
47  }
48
49  // Read each section
50  llvm::SmallVector<size_t, 4> progbits_ndx;
51  for (size_t i = 0; i < object->header->getSectionHeaderNum(); ++i) {
52    if ((*object->shtab)[i]->getType() == SHT_PROGBITS) {
53      object->stab.push_back(NULL);
54      progbits_ndx.push_back(i);
55    } else {
56      llvm::OwningPtr<ELFSectionTy> sec(
57        ELFSectionTy::read(AR, object.get(), (*object->shtab)[i]));
58      object->stab.push_back(sec.take());
59    }
60  }
61
62  for (size_t i = 0; i < progbits_ndx.size(); ++i) {
63    size_t index = progbits_ndx[i];
64
65    llvm::OwningPtr<ELFSectionTy> sec(
66      ELFSectionTy::read(AR, object.get(), (*object->shtab)[index]));
67    object->stab[index] = sec.take();
68  }
69
70  object->shtab->buildNameMap();
71  ELFSectionSymTabTy *symtab =
72    static_cast<ELFSectionSymTabTy *>(object->getSectionByName(".symtab"));
73  rsl_assert(symtab && "Symtab is required.");
74  symtab->buildNameMap();
75
76  return object.take();
77}
78
79template <unsigned Bitwidth>
80inline char const *ELFObject<Bitwidth>::getSectionName(size_t i) const {
81  ELFSectionTy const *sec = stab[header->getStringSectionIndex()];
82
83  if (sec) {
84    ELFSectionStrTabTy const &st =
85      static_cast<ELFSectionStrTabTy const &>(*sec);
86    return st[i];
87  }
88
89  return NULL;
90}
91
92template <unsigned Bitwidth>
93inline ELFSection<Bitwidth> const *
94ELFObject<Bitwidth>::getSectionByIndex(size_t i) const {
95  return stab[i];
96}
97
98template <unsigned Bitwidth>
99inline ELFSection<Bitwidth> *
100ELFObject<Bitwidth>::getSectionByIndex(size_t i) {
101  return stab[i];
102}
103
104template <unsigned Bitwidth>
105inline ELFSection<Bitwidth> const *
106ELFObject<Bitwidth>::getSectionByName(std::string const &str) const {
107  size_t idx = getSectionHeaderTable()->getByName(str)->getIndex();
108  return stab[idx];
109}
110
111template <unsigned Bitwidth>
112inline ELFSection<Bitwidth> *
113ELFObject<Bitwidth>::getSectionByName(std::string const &str) {
114  ELFObjectTy const *const_this = this;
115  ELFSectionTy const *sptr = const_this->getSectionByName(str);
116  // Const cast for the same API's const and non-const versions.
117  return const_cast<ELFSectionTy *>(sptr);
118}
119
120
121template <unsigned Bitwidth>
122inline void ELFObject<Bitwidth>::
123relocateARM(void *(*find_sym)(void *context, char const *name),
124            void *context,
125            ELFSectionRelTableTy *reltab,
126            ELFSectionProgBitsTy *text) {
127  // FIXME: Should be implement in independent files.
128  rsl_assert(Bitwidth == 32 && "ARM only have 32 bits.");
129
130  ELFSectionSymTabTy *symtab =
131    static_cast<ELFSectionSymTabTy *>(getSectionByName(".symtab"));
132  rsl_assert(symtab && "Symtab is required.");
133
134  for (size_t i = 0; i < reltab->size(); ++i) {
135    // FIXME: Can not implement here, use Fixup!
136    ELFRelocTy *rel = (*reltab)[i];
137    ELFSymbolTy *sym = (*symtab)[rel->getSymTabIndex()];
138
139    // FIXME: May be not uint32_t *.
140    typedef int32_t Inst_t;
141    Inst_t *inst = (Inst_t *)&(*text)[rel->getOffset()];
142    Inst_t P = (Inst_t)(int64_t)inst;
143    Inst_t A = 0;
144    Inst_t S = (Inst_t)(int64_t)sym->getAddress();
145
146    switch (rel->getType()) {
147    default:
148      rsl_assert(0 && "Not implemented relocation type.");
149      break;
150
151    case R_ARM_ABS32:
152      {
153        A = *inst;
154        *inst = (S+A);
155      }
156      break;
157
158      // FIXME: Predefine relocation codes.
159    case R_ARM_CALL:
160      {
161#define SIGN_EXTEND(x, l) (((x)^(1<<((l)-1)))-(1<<(l-1)))
162        A = (Inst_t)(int64_t)SIGN_EXTEND(*inst & 0xFFFFFF, 24);
163#undef SIGN_EXTEND
164
165        switch (sym->getType()) {
166        default:
167          rsl_assert(0 && "Wrong type for R_ARM_CALL relocation.");
168          abort();
169          break;
170
171        case STT_FUNC:
172          if (S == 0) {
173            rsl_assert(0 && "We should get function address at previous "
174                   "sym->getAddress() function call.");
175            abort();
176          }
177          break;
178
179        case STT_NOTYPE:
180          if (S == 0) {
181            void *ext_func = find_sym(context, sym->getName());
182            S = (Inst_t)(uintptr_t)ext_func;
183            sym->setAddress(ext_func);
184
185            uint32_t result = (S >> 2) - (P >> 2) + A;
186            if (result > 0x007fffff && result < 0xff800000) {
187#ifndef __arm__
188              // We have not implement function stub in this runtime env
189              rsl_assert(0 && "Target address is far from call instruction");
190              abort();
191#else
192              void *stub = getStubLayout()->allocateStub(ext_func);
193              if (!stub) {
194                llvm::errs() << "unable to allocate stub." << "\n";
195                exit(EXIT_FAILURE);
196              }
197
198              //out() << "stub: for " << ext_func << " at " << stub << "\n";
199              sym->setAddress(stub);
200              S = (uint32_t)stub;
201#endif
202            }
203          }
204          break;
205        }
206
207        uint32_t result = (S >> 2) - (P >> 2) + A;
208
209        if (result > 0x007fffff && result < 0xff800000) {
210          rsl_assert(0 && "Stub is still too far");
211          abort();
212        }
213
214        *inst = ((result) & 0x00FFFFFF) | (*inst & 0xFF000000);
215      }
216      break;
217    case R_ARM_MOVT_ABS:
218      S >>= 16;
219    case R_ARM_MOVW_ABS_NC:
220      {
221        // No need sign extend.
222        A = ((*inst & 0xF0000) >> 4) | (*inst & 0xFFF);
223        uint32_t result = (S+A);
224        *inst = (((result) & 0xF000) << 4) |
225          ((result) & 0xFFF) |
226          (*inst & 0xFFF0F000);
227      }
228      break;
229    }
230    //llvm::errs() << "S:     " << (void *)S << '\n';
231    //llvm::errs() << "A:     " << (void *)A << '\n';
232    //llvm::errs() << "P:     " << (void *)P << '\n';
233    //llvm::errs() << "S+A:   " << (void *)(S+A) << '\n';
234    //llvm::errs() << "S+A-P: " << (void *)(S+A-P) << '\n';
235  }
236}
237
238template <unsigned Bitwidth>
239inline void ELFObject<Bitwidth>::
240relocateX86_64(void *(*find_sym)(void *context, char const *name),
241               void *context,
242               ELFSectionRelTableTy *reltab,
243               ELFSectionProgBitsTy *text) {
244  rsl_assert(Bitwidth == 64 && "Only support X86_64.");
245
246  ELFSectionSymTabTy *symtab =
247    static_cast<ELFSectionSymTabTy *>(getSectionByName(".symtab"));
248  rsl_assert(symtab && "Symtab is required.");
249
250  for (size_t i = 0; i < reltab->size(); ++i) {
251    // FIXME: Can not implement here, use Fixup!
252    ELFRelocTy *rel = (*reltab)[i];
253    ELFSymbolTy *sym = (*symtab)[rel->getSymTabIndex()];
254
255    //typedef uint64_t Inst_t;
256    typedef int32_t Inst_t;
257    Inst_t *inst = (Inst_t *)&(*text)[rel->getOffset()];
258    Inst_t P = (Inst_t)(int64_t)inst;
259    Inst_t A = (Inst_t)(int64_t)rel->getAddend();
260    Inst_t S = (Inst_t)(int64_t)sym->getAddress();
261
262    if (S == 0) {
263      S = (Inst_t)(int64_t)find_sym(context, sym->getName());
264      sym->setAddress((void *)S);
265    }
266
267    switch (rel->getType()) {
268      default:
269        rsl_assert(0 && "Not implemented relocation type.");
270        break;
271
272      // FIXME: XXX: R_X86_64_64 is 64 bit, there is a big problem here.
273      case 1: // R_X86_64_64
274        *inst = (S+A);
275        break;
276
277      case 2: // R_X86_64_PC32
278        *inst = (S+A-P);
279        break;
280
281      case 10: // R_X86_64_32
282      case 11: // R_X86_64_32S
283        *inst = (S+A);
284        break;
285    }
286  }
287}
288
289template <unsigned Bitwidth>
290inline void ELFObject<Bitwidth>::
291relocateX86_32(void *(*find_sym)(void *context, char const *name),
292               void *context,
293               ELFSectionRelTableTy *reltab,
294               ELFSectionProgBitsTy *text) {
295  rsl_assert(Bitwidth == 32 && "Only support X86.");
296
297  ELFSectionSymTabTy *symtab =
298    static_cast<ELFSectionSymTabTy *>(getSectionByName(".symtab"));
299  rsl_assert(symtab && "Symtab is required.");
300
301  for (size_t i = 0; i < reltab->size(); ++i) {
302    // FIXME: Can not implement here, use Fixup!
303    ELFRelocTy *rel = (*reltab)[i];
304    ELFSymbolTy *sym = (*symtab)[rel->getSymTabIndex()];
305
306    //typedef uint64_t Inst_t;
307    typedef int32_t Inst_t;
308    Inst_t *inst = (Inst_t *)&(*text)[rel->getOffset()];
309    Inst_t P = (Inst_t)(uintptr_t)inst;
310    Inst_t A = (Inst_t)(uintptr_t)*inst;
311    Inst_t S = (Inst_t)(uintptr_t)sym->getAddress();
312
313    if (S == 0) {
314      S = (Inst_t)(uintptr_t)find_sym(context, sym->getName());
315      sym->setAddress((void *)S);
316    }
317
318    switch (rel->getType()) {
319    default:
320      rsl_assert(0 && "Not implemented relocation type.");
321      break;
322
323    case R_386_PC32:
324      *inst = (S+A-P);
325      break;
326
327    case R_386_32:
328      *inst = (S+A);
329      break;
330    }
331  }
332}
333
334template <unsigned Bitwidth>
335inline void ELFObject<Bitwidth>::
336relocate(void *(*find_sym)(void *context, char const *name), void *context) {
337
338  for (size_t i = 0; i < stab.size(); ++i) {
339    ELFSectionHeaderTy *sh = (*shtab)[i];
340    if (sh->getType() != SHT_REL && sh->getType() != SHT_RELA) {
341      continue;
342    }
343    ELFSectionRelTableTy *reltab =
344      static_cast<ELFSectionRelTableTy *>(stab[i]);
345    rsl_assert(reltab && "Relocation section can't be NULL.");
346
347    const char *reltab_name = sh->getName();
348    const char *need_rel_name;
349    if (sh->getType() == SHT_REL) {
350      need_rel_name = reltab_name + 4;
351      // ".rel.xxxx"
352      //      ^ start from here.
353    } else {
354      need_rel_name = reltab_name + 5;
355    }
356
357    ELFSectionProgBitsTy *need_rel =
358      static_cast<ELFSectionProgBitsTy *>(getSectionByName(need_rel_name));
359    rsl_assert(need_rel && "Need be relocated section can't be NULL.");
360
361    switch (getHeader()->getMachine()) {
362      case EM_ARM:
363        relocateARM(find_sym, context, reltab, need_rel);
364        break;
365      case EM_386:
366        relocateX86_32(find_sym, context, reltab, need_rel);
367        break;
368      case EM_X86_64:
369        relocateX86_64(find_sym, context, reltab, need_rel);
370        break;
371
372      default:
373        rsl_assert(0 && "Only support ARM, X86, and X86_64 relocation.");
374        break;
375    }
376  }
377
378  for (size_t i = 0; i < stab.size(); ++i) {
379    ELFSectionHeaderTy *sh = (*shtab)[i];
380    if (sh->getType() == SHT_PROGBITS || sh->getType() == SHT_NOBITS) {
381      if (stab[i]) {
382        static_cast<ELFSectionBitsTy *>(stab[i])->protect();
383      }
384    }
385  }
386}
387
388template <unsigned Bitwidth>
389inline void ELFObject<Bitwidth>::print() const {
390  header->print();
391  shtab->print();
392
393  for (size_t i = 0; i < stab.size(); ++i) {
394    ELFSectionTy *sec = stab[i];
395    if (sec) {
396      sec->print();
397    }
398  }
399}
400
401#endif // ELF_OBJECT_HXX
402