OSDN Git Service

Re-factored RuntimeDyld.
[android-x86/external-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldImpl.h
1 //===-- RuntimeDyldImpl.h - Run-time dynamic linker for MC-JIT --*- 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 // Interface for the implementations of runtime dynamic linker facilities.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_RUNTIME_DYLD_IMPL_H
15 #define LLVM_RUNTIME_DYLD_IMPL_H
16
17 #include "llvm/ExecutionEngine/RuntimeDyld.h"
18 #include "llvm/Object/ObjectFile.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/Support/Memory.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/system_error.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/ADT/Triple.h"
30 #include <map>
31 #include "llvm/Support/Format.h"
32
33 using namespace llvm;
34 using namespace llvm::object;
35
36 namespace llvm {
37
38 class SectionEntry {
39 public:
40   uint8_t* Address;
41   size_t Size;
42   uint64_t LoadAddress;   // For each section, the address it will be
43                           // considered to live at for relocations. The same
44                           // as the pointer to the above memory block for
45                           // hosted JITs.
46   uintptr_t StubOffset;   // It's used for architecturies with stub
47                           // functions for far relocations like ARM.
48   uintptr_t ObjAddress;   // Section address in object file. It's use for
49                           // calculate MachO relocation addend
50   SectionEntry(uint8_t* address, size_t size, uintptr_t stubOffset,
51                uintptr_t objAddress)
52     : Address(address), Size(size), LoadAddress((uintptr_t)address),
53       StubOffset(stubOffset), ObjAddress(objAddress) {}
54 };
55
56 class RelocationEntry {
57 public:
58   unsigned    SectionID;  // Section the relocation is contained in.
59   uintptr_t   Offset;     // Offset into the section for the relocation.
60   uint32_t    Data;       // Relocatino data. Including type of relocation
61                           // and another flags and parameners from
62   intptr_t    Addend;     // Addend encoded in the instruction itself, if any,
63                           // plus the offset into the source section for
64                           // the symbol once the relocation is resolvable.
65   RelocationEntry(unsigned id, uint64_t offset, uint32_t data, int64_t addend)
66     : SectionID(id), Offset(offset), Data(data), Addend(addend) {}
67 };
68
69 // Raw relocation data from object file
70 class ObjRelocationInfo {
71 public:
72   unsigned  SectionID;
73   uint64_t  Offset;
74   SymbolRef Symbol;
75   uint64_t  Type;
76   int64_t   AdditionalInfo;
77 };
78
79 class RelocationValueRef {
80 public:
81   unsigned  SectionID;
82   intptr_t  Addend;
83   const char *SymbolName;
84   RelocationValueRef(): SectionID(0), Addend(0), SymbolName(0) {}
85
86   inline bool operator==(const RelocationValueRef &Other) const {
87     return std::memcmp(this, &Other, sizeof(RelocationValueRef)) == 0;
88   }
89   inline bool operator <(const RelocationValueRef &Other) const {
90     return std::memcmp(this, &Other, sizeof(RelocationValueRef)) < 0;
91   }
92 };
93
94 class RuntimeDyldImpl {
95 protected:
96   // The MemoryManager to load objects into.
97   RTDyldMemoryManager *MemMgr;
98
99   // A list of emmitted sections.
100   typedef SmallVector<SectionEntry, 64> SectionList;
101   SectionList Sections;
102
103   // Keep a map of sections from object file to the SectionID which
104   // references it.
105   typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
106
107   // Master symbol table. As modules are loaded and external symbols are
108   // resolved, their addresses are stored here as a SectionID/Offset pair.
109   typedef std::pair<unsigned, uintptr_t> SymbolLoc;
110   StringMap<SymbolLoc> SymbolTable;
111   typedef DenseMap<const char*, SymbolLoc> LocalSymbolMap;
112
113   // For each symbol, keep a list of relocations based on it. Anytime
114   // its address is reassigned (the JIT re-compiled the function, e.g.),
115   // the relocations get re-resolved.
116   // The symbol (or section) the relocation is sourced from is the Key
117   // in the relocation list where it's stored.
118   typedef SmallVector<RelocationEntry, 64> RelocationList;
119   // Relocations to sections already loaded. Indexed by SectionID which is the
120   // source of the address. The target where the address will be writen is
121   // SectionID/Offset in the relocation itself.
122   DenseMap<unsigned, RelocationList> Relocations;
123   // Relocations to external symbols that are not yet resolved.
124   // Indexed by symbol name.
125   StringMap<RelocationList> SymbolRelocations;
126
127   typedef std::map<RelocationValueRef, uintptr_t> StubMap;
128
129   Triple::ArchType Arch;
130
131   inline unsigned getMaxStubSize() {
132     if (Arch == Triple::arm || Arch == Triple::thumb)
133       return 8; // 32-bit instruction and 32-bit address
134     else
135       return 0;
136   }
137
138   bool HasError;
139   std::string ErrorStr;
140
141   // Set the error state and record an error string.
142   bool Error(const Twine &Msg) {
143     ErrorStr = Msg.str();
144     HasError = true;
145     return true;
146   }
147
148   uint8_t *getSectionAddress(unsigned SectionID) {
149     return (uint8_t*)Sections[SectionID].Address;
150   }
151
152   /// \brief Emits section data from the object file to the MemoryManager.
153   /// \param IsCode if it's true then allocateCodeSection() will be
154   ///        used for emmits, else allocateDataSection() will be used.
155   /// \return SectionID.
156   unsigned emitSection(const SectionRef &Section, bool IsCode);
157
158   /// \brief Find Section in LocalSections. If the secton is not found - emit
159   ///        it and store in LocalSections.
160   /// \param IsCode if it's true then allocateCodeSection() will be
161   ///        used for emmits, else allocateDataSection() will be used.
162   /// \return SectionID.
163   unsigned findOrEmitSection(const SectionRef &Section, bool IsCode,
164                              ObjSectionToIDMap &LocalSections);
165
166   /// \brief If Value.SymbolName is NULL then store relocation to the
167   ///        Relocations, else store it in the SymbolRelocations.
168   void AddRelocation(const RelocationValueRef &Value, unsigned SectionID,
169                      uintptr_t Offset, uint32_t RelType);
170
171   /// \brief Emits long jump instruction to Addr.
172   /// \return Pointer to the memory area for emitting target address.
173   uint8_t* createStubFunction(uint8_t *Addr);
174
175   /// \brief Resolves relocations from Relocs list with address from Value.
176   void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
177   void resolveRelocationEntry(const RelocationEntry &RE, uint64_t Value);
178
179   /// \brief A object file specific relocation resolver
180   /// \param Address Address to apply the relocation action
181   /// \param Value Target symbol address to apply the relocation action
182   /// \param Type object file specific relocation type
183   /// \param Addend A constant addend used to compute the value to be stored
184   ///        into the relocatable field
185   virtual void resolveRelocation(uint8_t *LocalAddress,
186                                  uint64_t FinalAddress,
187                                  uint64_t Value,
188                                  uint32_t Type,
189                                  int64_t Addend) = 0;
190
191   /// \brief Parses the object file relocation and store it to Relocations
192   ///        or SymbolRelocations. Its depend from object file type.
193   virtual void processRelocationRef(const ObjRelocationInfo &Rel,
194                                     const ObjectFile &Obj,
195                                     ObjSectionToIDMap &ObjSectionToID,
196                                     LocalSymbolMap &Symbols, StubMap &Stubs) = 0;
197
198   void resolveSymbols();
199 public:
200   RuntimeDyldImpl(RTDyldMemoryManager *mm) : MemMgr(mm), HasError(false) {}
201
202   virtual ~RuntimeDyldImpl();
203
204   bool loadObject(const MemoryBuffer *InputBuffer);
205
206   void *getSymbolAddress(StringRef Name) {
207     // FIXME: Just look up as a function for now. Overly simple of course.
208     // Work in progress.
209     if (SymbolTable.find(Name) == SymbolTable.end())
210       return 0;
211     SymbolLoc Loc = SymbolTable.lookup(Name);
212     return getSectionAddress(Loc.first) + Loc.second;
213   }
214
215   void resolveRelocations();
216
217   void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
218
219   void mapSectionAddress(void *LocalAddress, uint64_t TargetAddress);
220
221   // Is the linker in an error state?
222   bool hasError() { return HasError; }
223
224   // Mark the error condition as handled and continue.
225   void clearError() { HasError = false; }
226
227   // Get the error message.
228   StringRef getErrorString() { return ErrorStr; }
229
230   virtual bool isCompatibleFormat(const MemoryBuffer *InputBuffer) const = 0;
231
232 };
233
234 } // end namespace llvm
235
236
237 #endif