bd6d287a91e58e729d9bc44adfd4a4b668c628d2
[oota-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 "ObjectImage.h"
18 #include "llvm/ExecutionEngine/RuntimeDyld.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Object/ObjectFile.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/system_error.h"
29 #include <map>
30
31 using namespace llvm;
32 using namespace llvm::object;
33
34 namespace llvm {
35
36 class MemoryBuffer;
37 class Twine;
38
39
40 /// SectionEntry - represents a section emitted into memory by the dynamic
41 /// linker.
42 class SectionEntry {
43 public:
44   /// Address - address in the linker's memory where the section resides.
45   uint8_t *Address;
46
47   /// Size - section size.
48   size_t Size;
49
50   /// LoadAddress - the address of the section in the target process's memory.
51   /// Used for situations in which JIT-ed code is being executed in the address
52   /// space of a separate process.  If the code executes in the same address
53   /// space where it was JIT-ed, this just equals Address.
54   uint64_t LoadAddress;
55
56   /// StubOffset - used for architectures with stub functions for far
57   /// relocations (like ARM).
58   uintptr_t StubOffset;
59
60   /// ObjAddress - address of the section in the in-memory object file.  Used
61   /// for calculating relocations in some object formats (like MachO).
62   uintptr_t ObjAddress;
63
64   SectionEntry(uint8_t *address, size_t size, uintptr_t stubOffset,
65                uintptr_t objAddress)
66     : Address(address), Size(size), LoadAddress((uintptr_t)address),
67       StubOffset(stubOffset), ObjAddress(objAddress) {}
68 };
69
70 /// RelocationEntry - used to represent relocations internally in the dynamic
71 /// linker.
72 class RelocationEntry {
73 public:
74   /// SectionID - the section this relocation points to.
75   unsigned SectionID;
76
77   /// Offset - offset into the section.
78   uintptr_t Offset;
79
80   /// RelType - relocation type.
81   uint32_t RelType;
82
83   /// Addend - the relocation addend encoded in the instruction itself.  Also
84   /// used to make a relocation section relative instead of symbol relative.
85   intptr_t Addend;
86
87   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend)
88     : SectionID(id), Offset(offset), RelType(type), Addend(addend) {}
89 };
90
91 /// ObjRelocationInfo - relocation information as read from the object file.
92 /// Used to pass around data taken from object::RelocationRef, together with
93 /// the section to which the relocation points (represented by a SectionID).
94 class ObjRelocationInfo {
95 public:
96   unsigned  SectionID;
97   uint64_t  Offset;
98   SymbolRef Symbol;
99   uint64_t  Type;
100   int64_t   AdditionalInfo;
101 };
102
103 class RelocationValueRef {
104 public:
105   unsigned  SectionID;
106   intptr_t  Addend;
107   const char *SymbolName;
108   RelocationValueRef(): SectionID(0), Addend(0), SymbolName(0) {}
109
110   inline bool operator==(const RelocationValueRef &Other) const {
111     return std::memcmp(this, &Other, sizeof(RelocationValueRef)) == 0;
112   }
113   inline bool operator <(const RelocationValueRef &Other) const {
114     return std::memcmp(this, &Other, sizeof(RelocationValueRef)) < 0;
115   }
116 };
117
118 class RuntimeDyldImpl {
119 protected:
120   // The MemoryManager to load objects into.
121   RTDyldMemoryManager *MemMgr;
122
123   // A list of all sections emitted by the dynamic linker.  These sections are
124   // referenced in the code by means of their index in this list - SectionID.
125   typedef SmallVector<SectionEntry, 64> SectionList;
126   SectionList Sections;
127
128   // Keep a map of sections from object file to the SectionID which
129   // references it.
130   typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
131
132   // A global symbol table for symbols from all loaded modules.  Maps the
133   // symbol name to a (SectionID, offset in section) pair.
134   typedef std::pair<unsigned, uintptr_t> SymbolLoc;
135   typedef StringMap<SymbolLoc> SymbolTableMap;
136   SymbolTableMap GlobalSymbolTable;
137
138   // Keep a map of common symbols to their sizes
139   typedef std::map<SymbolRef, unsigned> CommonSymbolMap;
140
141   // For each symbol, keep a list of relocations based on it. Anytime
142   // its address is reassigned (the JIT re-compiled the function, e.g.),
143   // the relocations get re-resolved.
144   // The symbol (or section) the relocation is sourced from is the Key
145   // in the relocation list where it's stored.
146   typedef SmallVector<RelocationEntry, 64> RelocationList;
147   // Relocations to sections already loaded. Indexed by SectionID which is the
148   // source of the address. The target where the address will be writen is
149   // SectionID/Offset in the relocation itself.
150   DenseMap<unsigned, RelocationList> Relocations;
151
152   // Relocations to external symbols that are not yet resolved.  Symbols are
153   // external when they aren't found in the global symbol table of all loaded
154   // modules.  This map is indexed by symbol name.
155   StringMap<RelocationList> ExternalSymbolRelocations;
156
157   typedef std::map<RelocationValueRef, uintptr_t> StubMap;
158
159   Triple::ArchType Arch;
160
161   inline unsigned getMaxStubSize() {
162     if (Arch == Triple::arm || Arch == Triple::thumb)
163       return 8; // 32-bit instruction and 32-bit address
164     else
165       return 0;
166   }
167
168   bool HasError;
169   std::string ErrorStr;
170
171   // Set the error state and record an error string.
172   bool Error(const Twine &Msg) {
173     ErrorStr = Msg.str();
174     HasError = true;
175     return true;
176   }
177
178   uint8_t *getSectionAddress(unsigned SectionID) {
179     return (uint8_t*)Sections[SectionID].Address;
180   }
181
182   /// \brief Given the common symbols discovered in the object file, emit a
183   /// new section for them and update the symbol mappings in the object and
184   /// symbol table.
185   void emitCommonSymbols(ObjectImage &Obj,
186                          const CommonSymbolMap &CommonSymbols,
187                          uint64_t TotalSize,
188                          SymbolTableMap &SymbolTable);
189
190   /// \brief Emits section data from the object file to the MemoryManager.
191   /// \param IsCode if it's true then allocateCodeSection() will be
192   ///        used for emits, else allocateDataSection() will be used.
193   /// \return SectionID.
194   unsigned emitSection(ObjectImage &Obj,
195                        const SectionRef &Section,
196                        bool IsCode);
197
198   /// \brief Find Section in LocalSections. If the secton is not found - emit
199   ///        it and store in LocalSections.
200   /// \param IsCode if it's true then allocateCodeSection() will be
201   ///        used for emmits, else allocateDataSection() will be used.
202   /// \return SectionID.
203   unsigned findOrEmitSection(ObjectImage &Obj,
204                              const SectionRef &Section,
205                              bool IsCode,
206                              ObjSectionToIDMap &LocalSections);
207
208   // \brief Add a relocation entry that uses the given section.
209   void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
210
211   // \brief Add a relocation entry that uses the given symbol.  This symbol may
212   // be found in the global symbol table, or it may be external.
213   void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName);
214
215   /// \brief Emits long jump instruction to Addr.
216   /// \return Pointer to the memory area for emitting target address.
217   uint8_t* createStubFunction(uint8_t *Addr);
218
219   /// \brief Resolves relocations from Relocs list with address from Value.
220   void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
221   void resolveRelocationEntry(const RelocationEntry &RE, uint64_t Value);
222
223   /// \brief A object file specific relocation resolver
224   /// \param Address Address to apply the relocation action
225   /// \param Value Target symbol address to apply the relocation action
226   /// \param Type object file specific relocation type
227   /// \param Addend A constant addend used to compute the value to be stored
228   ///        into the relocatable field
229   virtual void resolveRelocation(uint8_t *LocalAddress,
230                                  uint64_t FinalAddress,
231                                  uint64_t Value,
232                                  uint32_t Type,
233                                  int64_t Addend) = 0;
234
235   /// \brief Parses the object file relocation and stores it to Relocations
236   ///        or SymbolRelocations (this depends on the object file type).
237   virtual void processRelocationRef(const ObjRelocationInfo &Rel,
238                                     ObjectImage &Obj,
239                                     ObjSectionToIDMap &ObjSectionToID,
240                                     const SymbolTableMap &Symbols,
241                                     StubMap &Stubs) = 0;
242
243   /// \brief Resolve relocations to external symbols.
244   void resolveExternalSymbols();
245   virtual ObjectImage *createObjectImage(const MemoryBuffer *InputBuffer);
246   virtual void handleObjectLoaded(ObjectImage *Obj)
247   {
248     // Subclasses may choose to retain this image if they have a use for it
249     delete Obj;
250   }
251
252 public:
253   RuntimeDyldImpl(RTDyldMemoryManager *mm) : MemMgr(mm), HasError(false) {}
254
255   virtual ~RuntimeDyldImpl();
256
257   bool loadObject(const MemoryBuffer *InputBuffer);
258
259   void *getSymbolAddress(StringRef Name) {
260     // FIXME: Just look up as a function for now. Overly simple of course.
261     // Work in progress.
262     if (GlobalSymbolTable.find(Name) == GlobalSymbolTable.end())
263       return 0;
264     SymbolLoc Loc = GlobalSymbolTable.lookup(Name);
265     return getSectionAddress(Loc.first) + Loc.second;
266   }
267
268   void resolveRelocations();
269
270   void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
271
272   void mapSectionAddress(void *LocalAddress, uint64_t TargetAddress);
273
274   // Is the linker in an error state?
275   bool hasError() { return HasError; }
276
277   // Mark the error condition as handled and continue.
278   void clearError() { HasError = false; }
279
280   // Get the error message.
281   StringRef getErrorString() { return ErrorStr; }
282
283   virtual bool isCompatibleFormat(const MemoryBuffer *InputBuffer) const = 0;
284
285 };
286
287 } // end namespace llvm
288
289
290 #endif