20c63f171a989e292b6248d4d203569a7a12e3ea
[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_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
15 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
16
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ExecutionEngine/RuntimeDyld.h"
22 #include "llvm/ExecutionEngine/RuntimeDyldChecker.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/Host.h"
28 #include "llvm/Support/Mutex.h"
29 #include "llvm/Support/SwapByteOrder.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <map>
32 #include <system_error>
33
34 using namespace llvm;
35 using namespace llvm::object;
36
37 namespace llvm {
38
39   // Helper for extensive error checking in debug builds.
40 inline std::error_code Check(std::error_code Err) {
41   if (Err) {
42     report_fatal_error(Err.message());
43   }
44   return Err;
45 }
46
47 class Twine;
48
49 /// SectionEntry - represents a section emitted into memory by the dynamic
50 /// linker.
51 class SectionEntry {
52 public:
53   /// Name - section name.
54   StringRef Name;
55
56   /// Address - address in the linker's memory where the section resides.
57   uint8_t *Address;
58
59   /// Size - section size. Doesn't include the stubs.
60   size_t Size;
61
62   /// LoadAddress - the address of the section in the target process's memory.
63   /// Used for situations in which JIT-ed code is being executed in the address
64   /// space of a separate process.  If the code executes in the same address
65   /// space where it was JIT-ed, this just equals Address.
66   uint64_t LoadAddress;
67
68   /// StubOffset - used for architectures with stub functions for far
69   /// relocations (like ARM).
70   uintptr_t StubOffset;
71
72   /// ObjAddress - address of the section in the in-memory object file.  Used
73   /// for calculating relocations in some object formats (like MachO).
74   uintptr_t ObjAddress;
75
76   SectionEntry(StringRef name, uint8_t *address, size_t size,
77                uintptr_t objAddress)
78       : Name(name), Address(address), Size(size),
79         LoadAddress(reinterpret_cast<uintptr_t>(address)), StubOffset(size),
80         ObjAddress(objAddress) {}
81 };
82
83 /// RelocationEntry - used to represent relocations internally in the dynamic
84 /// linker.
85 class RelocationEntry {
86 public:
87   /// SectionID - the section this relocation points to.
88   unsigned SectionID;
89
90   /// Offset - offset into the section.
91   uint64_t Offset;
92
93   /// RelType - relocation type.
94   uint32_t RelType;
95
96   /// Addend - the relocation addend encoded in the instruction itself.  Also
97   /// used to make a relocation section relative instead of symbol relative.
98   int64_t Addend;
99
100   struct SectionPair {
101       uint32_t SectionA;
102       uint32_t SectionB;
103   };
104
105   /// SymOffset - Section offset of the relocation entry's symbol (used for GOT
106   /// lookup).
107   union {
108     uint64_t SymOffset;
109     SectionPair Sections;
110   };
111
112   /// True if this is a PCRel relocation (MachO specific).
113   bool IsPCRel;
114
115   /// The size of this relocation (MachO specific).
116   unsigned Size;
117
118   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend)
119       : SectionID(id), Offset(offset), RelType(type), Addend(addend),
120         SymOffset(0), IsPCRel(false), Size(0) {}
121
122   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
123                   uint64_t symoffset)
124       : SectionID(id), Offset(offset), RelType(type), Addend(addend),
125         SymOffset(symoffset), IsPCRel(false), Size(0) {}
126
127   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
128                   bool IsPCRel, unsigned Size)
129       : SectionID(id), Offset(offset), RelType(type), Addend(addend),
130         SymOffset(0), IsPCRel(IsPCRel), Size(Size) {}
131
132   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
133                   unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
134                   uint64_t SectionBOffset, bool IsPCRel, unsigned Size)
135       : SectionID(id), Offset(offset), RelType(type),
136         Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
137         Size(Size) {
138     Sections.SectionA = SectionA;
139     Sections.SectionB = SectionB;
140   }
141 };
142
143 class RelocationValueRef {
144 public:
145   unsigned SectionID;
146   uint64_t Offset;
147   int64_t Addend;
148   const char *SymbolName;
149   RelocationValueRef() : SectionID(0), Offset(0), Addend(0),
150                          SymbolName(nullptr) {}
151
152   inline bool operator==(const RelocationValueRef &Other) const {
153     return SectionID == Other.SectionID && Offset == Other.Offset &&
154            Addend == Other.Addend && SymbolName == Other.SymbolName;
155   }
156   inline bool operator<(const RelocationValueRef &Other) const {
157     if (SectionID != Other.SectionID)
158       return SectionID < Other.SectionID;
159     if (Offset != Other.Offset)
160       return Offset < Other.Offset;
161     if (Addend != Other.Addend)
162       return Addend < Other.Addend;
163     return SymbolName < Other.SymbolName;
164   }
165 };
166
167 /// @brief Symbol info for RuntimeDyld.
168 class SymbolInfo {
169 public:
170   typedef enum { Hidden = 0, Default = 1 } Visibility;
171
172   SymbolInfo() : Offset(0), SectionID(0), Vis(Hidden) {}
173
174   SymbolInfo(unsigned SectionID, uint64_t Offset, Visibility Vis)
175     : Offset(Offset), SectionID(SectionID), Vis(Vis) {}
176
177   unsigned getSectionID() const { return SectionID; }
178   uint64_t getOffset() const { return Offset; }
179   Visibility getVisibility() const { return Vis; }
180
181 private:
182   uint64_t Offset;
183   unsigned SectionID : 31;
184   Visibility Vis : 1;
185 };
186
187 typedef StringMap<SymbolInfo> RTDyldSymbolTable;
188
189 class RuntimeDyldImpl {
190   friend class RuntimeDyld::LoadedObjectInfo;
191   friend class RuntimeDyldCheckerImpl;
192 protected:
193   // The MemoryManager to load objects into.
194   RTDyldMemoryManager *MemMgr;
195
196   // Attached RuntimeDyldChecker instance. Null if no instance attached.
197   RuntimeDyldCheckerImpl *Checker;
198
199   // A list of all sections emitted by the dynamic linker.  These sections are
200   // referenced in the code by means of their index in this list - SectionID.
201   typedef SmallVector<SectionEntry, 64> SectionList;
202   SectionList Sections;
203
204   typedef unsigned SID; // Type for SectionIDs
205 #define RTDYLD_INVALID_SECTION_ID ((SID)(-1))
206
207   // Keep a map of sections from object file to the SectionID which
208   // references it.
209   typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
210
211   // A global symbol table for symbols from all loaded modules.
212   RTDyldSymbolTable GlobalSymbolTable;
213
214   // Keep a map of common symbols to their info pairs
215   typedef std::vector<SymbolRef> CommonSymbolList;
216
217   // For each symbol, keep a list of relocations based on it. Anytime
218   // its address is reassigned (the JIT re-compiled the function, e.g.),
219   // the relocations get re-resolved.
220   // The symbol (or section) the relocation is sourced from is the Key
221   // in the relocation list where it's stored.
222   typedef SmallVector<RelocationEntry, 64> RelocationList;
223   // Relocations to sections already loaded. Indexed by SectionID which is the
224   // source of the address. The target where the address will be written is
225   // SectionID/Offset in the relocation itself.
226   DenseMap<unsigned, RelocationList> Relocations;
227
228   // Relocations to external symbols that are not yet resolved.  Symbols are
229   // external when they aren't found in the global symbol table of all loaded
230   // modules.  This map is indexed by symbol name.
231   StringMap<RelocationList> ExternalSymbolRelocations;
232
233
234   typedef std::map<RelocationValueRef, uintptr_t> StubMap;
235
236   Triple::ArchType Arch;
237   bool IsTargetLittleEndian;
238
239   // True if all sections should be passed to the memory manager, false if only
240   // sections containing relocations should be. Defaults to 'false'.
241   bool ProcessAllSections;
242
243   // This mutex prevents simultaneously loading objects from two different
244   // threads.  This keeps us from having to protect individual data structures
245   // and guarantees that section allocation requests to the memory manager
246   // won't be interleaved between modules.  It is also used in mapSectionAddress
247   // and resolveRelocations to protect write access to internal data structures.
248   //
249   // loadObject may be called on the same thread during the handling of of
250   // processRelocations, and that's OK.  The handling of the relocation lists
251   // is written in such a way as to work correctly if new elements are added to
252   // the end of the list while the list is being processed.
253   sys::Mutex lock;
254
255   virtual unsigned getMaxStubSize() = 0;
256   virtual unsigned getStubAlignment() = 0;
257
258   bool HasError;
259   std::string ErrorStr;
260
261   // Set the error state and record an error string.
262   bool Error(const Twine &Msg) {
263     ErrorStr = Msg.str();
264     HasError = true;
265     return true;
266   }
267
268   uint64_t getSectionLoadAddress(unsigned SectionID) const {
269     return Sections[SectionID].LoadAddress;
270   }
271
272   uint8_t *getSectionAddress(unsigned SectionID) const {
273     return (uint8_t *)Sections[SectionID].Address;
274   }
275
276   void writeInt16BE(uint8_t *Addr, uint16_t Value) {
277     if (IsTargetLittleEndian)
278       sys::swapByteOrder(Value);
279     *Addr       = (Value >> 8) & 0xFF;
280     *(Addr + 1) = Value & 0xFF;
281   }
282
283   void writeInt32BE(uint8_t *Addr, uint32_t Value) {
284     if (IsTargetLittleEndian)
285       sys::swapByteOrder(Value);
286     *Addr       = (Value >> 24) & 0xFF;
287     *(Addr + 1) = (Value >> 16) & 0xFF;
288     *(Addr + 2) = (Value >> 8) & 0xFF;
289     *(Addr + 3) = Value & 0xFF;
290   }
291
292   void writeInt64BE(uint8_t *Addr, uint64_t Value) {
293     if (IsTargetLittleEndian)
294       sys::swapByteOrder(Value);
295     *Addr       = (Value >> 56) & 0xFF;
296     *(Addr + 1) = (Value >> 48) & 0xFF;
297     *(Addr + 2) = (Value >> 40) & 0xFF;
298     *(Addr + 3) = (Value >> 32) & 0xFF;
299     *(Addr + 4) = (Value >> 24) & 0xFF;
300     *(Addr + 5) = (Value >> 16) & 0xFF;
301     *(Addr + 6) = (Value >> 8) & 0xFF;
302     *(Addr + 7) = Value & 0xFF;
303   }
304
305   /// Endian-aware read Read the least significant Size bytes from Src.
306   uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const;
307
308   /// Endian-aware write. Write the least significant Size bytes from Value to
309   /// Dst.
310   void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const;
311
312   /// \brief Given the common symbols discovered in the object file, emit a
313   /// new section for them and update the symbol mappings in the object and
314   /// symbol table.
315   void emitCommonSymbols(const ObjectFile &Obj, CommonSymbolList &CommonSymbols);
316
317   /// \brief Emits section data from the object file to the MemoryManager.
318   /// \param IsCode if it's true then allocateCodeSection() will be
319   ///        used for emits, else allocateDataSection() will be used.
320   /// \return SectionID.
321   unsigned emitSection(const ObjectFile &Obj, const SectionRef &Section,
322                        bool IsCode);
323
324   /// \brief Find Section in LocalSections. If the secton is not found - emit
325   ///        it and store in LocalSections.
326   /// \param IsCode if it's true then allocateCodeSection() will be
327   ///        used for emmits, else allocateDataSection() will be used.
328   /// \return SectionID.
329   unsigned findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section,
330                              bool IsCode, ObjSectionToIDMap &LocalSections);
331
332   // \brief Add a relocation entry that uses the given section.
333   void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
334
335   // \brief Add a relocation entry that uses the given symbol.  This symbol may
336   // be found in the global symbol table, or it may be external.
337   void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName);
338
339   /// \brief Emits long jump instruction to Addr.
340   /// \return Pointer to the memory area for emitting target address.
341   uint8_t *createStubFunction(uint8_t *Addr, unsigned AbiVariant = 0);
342
343   /// \brief Resolves relocations from Relocs list with address from Value.
344   void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
345
346   /// \brief A object file specific relocation resolver
347   /// \param RE The relocation to be resolved
348   /// \param Value Target symbol address to apply the relocation action
349   virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value) = 0;
350
351   /// \brief Parses one or more object file relocations (some object files use
352   ///        relocation pairs) and stores it to Relocations or SymbolRelocations
353   ///        (this depends on the object file type).
354   /// \return Iterator to the next relocation that needs to be parsed.
355   virtual relocation_iterator
356   processRelocationRef(unsigned SectionID, relocation_iterator RelI,
357                        const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
358                        StubMap &Stubs) = 0;
359
360   /// \brief Resolve relocations to external symbols.
361   void resolveExternalSymbols();
362
363   /// \brief Update GOT entries for external symbols.
364   // The base class does nothing.  ELF overrides this.
365   virtual void updateGOTEntries(StringRef Name, uint64_t Addr) {}
366
367   // \brief Compute an upper bound of the memory that is required to load all
368   // sections
369   void computeTotalAllocSize(const ObjectFile &Obj, uint64_t &CodeSize,
370                              uint64_t &DataSizeRO, uint64_t &DataSizeRW);
371
372   // \brief Compute the stub buffer size required for a section
373   unsigned computeSectionStubBufSize(const ObjectFile &Obj,
374                                      const SectionRef &Section);
375
376   // \brief Implementation of the generic part of the loadObject algorithm.
377   std::pair<unsigned, unsigned> loadObjectImpl(const object::ObjectFile &Obj);
378
379 public:
380   RuntimeDyldImpl(RTDyldMemoryManager *mm)
381     : MemMgr(mm), Checker(nullptr), ProcessAllSections(false), HasError(false) {
382   }
383
384   virtual ~RuntimeDyldImpl();
385
386   void setProcessAllSections(bool ProcessAllSections) {
387     this->ProcessAllSections = ProcessAllSections;
388   }
389
390   void setRuntimeDyldChecker(RuntimeDyldCheckerImpl *Checker) {
391     this->Checker = Checker;
392   }
393
394   virtual std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
395   loadObject(const object::ObjectFile &Obj) = 0;
396
397   uint8_t* getSymbolAddress(StringRef Name) const {
398     // FIXME: Just look up as a function for now. Overly simple of course.
399     // Work in progress.
400     RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
401     if (pos == GlobalSymbolTable.end())
402       return nullptr;
403     const auto &SymInfo = pos->second;
404     return getSectionAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
405   }
406
407   uint64_t getSymbolLoadAddress(StringRef Name) const {
408     // FIXME: Just look up as a function for now. Overly simple of course.
409     // Work in progress.
410     RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
411     if (pos == GlobalSymbolTable.end())
412       return 0;
413     const auto &SymInfo = pos->second;
414     return getSectionLoadAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
415   }
416
417   uint64_t getExportedSymbolLoadAddress(StringRef Name) const {
418     RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
419     if (pos == GlobalSymbolTable.end())
420       return 0;
421     const auto &SymInfo = pos->second;
422     if (SymInfo.getVisibility() == SymbolInfo::Hidden)
423       return 0;
424     return getSectionLoadAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
425   }
426
427   void resolveRelocations();
428
429   void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
430
431   void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
432
433   // Is the linker in an error state?
434   bool hasError() { return HasError; }
435
436   // Mark the error condition as handled and continue.
437   void clearError() { HasError = false; }
438
439   // Get the error message.
440   StringRef getErrorString() { return ErrorStr; }
441
442   virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
443
444   virtual void registerEHFrames();
445
446   virtual void deregisterEHFrames();
447
448   virtual void finalizeLoad(const ObjectFile &ObjImg,
449                             ObjSectionToIDMap &SectionMap) {}
450 };
451
452 } // end namespace llvm
453
454 #endif