5723f058f72f0aa9757acc3753bfc5c99a7c9491
[oota-llvm.git] / include / llvm / ExecutionEngine / RuntimeDyld.h
1 //===-- RuntimeDyld.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 runtime dynamic linker facilities of the MC-JIT.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
15 #define LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
16
17 #include "JITSymbolFlags.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Support/Memory.h"
20 #include <memory>
21
22 namespace llvm {
23
24 namespace object {
25   class ObjectFile;
26   template <typename T> class OwningBinary;
27 }
28
29 class RuntimeDyldImpl;
30 class RuntimeDyldCheckerImpl;
31
32 class RuntimeDyld {
33   friend class RuntimeDyldCheckerImpl;
34
35   RuntimeDyld(const RuntimeDyld &) = delete;
36   void operator=(const RuntimeDyld &) = delete;
37
38 protected:
39   // Change the address associated with a section when resolving relocations.
40   // Any relocations already associated with the symbol will be re-resolved.
41   void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
42 public:
43
44   /// \brief Information about a named symbol.
45   class SymbolInfo : public JITSymbolBase {
46   public:
47     SymbolInfo(std::nullptr_t) : JITSymbolBase(JITSymbolFlags::None), Address(0) {}
48     SymbolInfo(uint64_t Address, JITSymbolFlags Flags)
49       : JITSymbolBase(Flags), Address(Address) {}
50     explicit operator bool() const { return Address != 0; }
51     uint64_t getAddress() const { return Address; }
52   private:
53     uint64_t Address;
54   };
55
56   /// \brief Information about the loaded object.
57   class LoadedObjectInfo {
58     friend class RuntimeDyldImpl;
59   public:
60     LoadedObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
61                      unsigned EndIdx)
62       : RTDyld(RTDyld), BeginIdx(BeginIdx), EndIdx(EndIdx) { }
63
64     virtual ~LoadedObjectInfo() {}
65
66     virtual object::OwningBinary<object::ObjectFile>
67     getObjectForDebug(const object::ObjectFile &Obj) const = 0;
68
69     uint64_t getSectionLoadAddress(StringRef Name) const;
70
71   protected:
72     virtual void anchor();
73
74     RuntimeDyldImpl &RTDyld;
75     unsigned BeginIdx, EndIdx;
76   };
77
78   /// \brief Memory Management.
79   class MemoryManager {
80   public:
81     virtual ~MemoryManager() {};
82
83     /// Allocate a memory block of (at least) the given size suitable for
84     /// executable code. The SectionID is a unique identifier assigned by the
85     /// RuntimeDyld instance, and optionally recorded by the memory manager to
86     /// access a loaded section.
87     virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
88                                          unsigned SectionID,
89                                          StringRef SectionName) = 0;
90
91     /// Allocate a memory block of (at least) the given size suitable for data.
92     /// The SectionID is a unique identifier assigned by the JIT engine, and
93     /// optionally recorded by the memory manager to access a loaded section.
94     virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
95                                          unsigned SectionID,
96                                          StringRef SectionName,
97                                          bool IsReadOnly) = 0;
98
99     /// Inform the memory manager about the total amount of memory required to
100     /// allocate all sections to be loaded:
101     /// \p CodeSize - the total size of all code sections
102     /// \p DataSizeRO - the total size of all read-only data sections
103     /// \p DataSizeRW - the total size of all read-write data sections
104     ///
105     /// Note that by default the callback is disabled. To enable it
106     /// redefine the method needsToReserveAllocationSpace to return true.
107     virtual void reserveAllocationSpace(uintptr_t CodeSize,
108                                         uintptr_t DataSizeRO,
109                                         uintptr_t DataSizeRW) {}
110
111     /// Override to return true to enable the reserveAllocationSpace callback.
112     virtual bool needsToReserveAllocationSpace() { return false; }
113
114     /// Register the EH frames with the runtime so that c++ exceptions work.
115     ///
116     /// \p Addr parameter provides the local address of the EH frame section
117     /// data, while \p LoadAddr provides the address of the data in the target
118     /// address space.  If the section has not been remapped (which will usually
119     /// be the case for local execution) these two values will be the same.
120     virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
121                                   size_t Size) = 0;
122     virtual void deregisterEHFrames(uint8_t *addr, uint64_t LoadAddr,
123                                     size_t Size) = 0;
124
125     /// This method is called when object loading is complete and section page
126     /// permissions can be applied.  It is up to the memory manager implementation
127     /// to decide whether or not to act on this method.  The memory manager will
128     /// typically allocate all sections as read-write and then apply specific
129     /// permissions when this method is called.  Code sections cannot be executed
130     /// until this function has been called.  In addition, any cache coherency
131     /// operations needed to reliably use the memory are also performed.
132     ///
133     /// Returns true if an error occurred, false otherwise.
134     virtual bool finalizeMemory(std::string *ErrMsg = nullptr) = 0;
135
136   private:
137     virtual void anchor();
138   };
139
140   /// \brief Symbol resolution.
141   class SymbolResolver {
142   public:
143     virtual ~SymbolResolver() {};
144
145     /// This method returns the address of the specified function or variable.
146     /// It is used to resolve symbols during module linking.
147     virtual SymbolInfo findSymbol(const std::string &Name) = 0;
148
149     /// This method returns the address of the specified symbol if it exists
150     /// within the logical dynamic library represented by this
151     /// RTDyldMemoryManager. Unlike getSymbolAddress, queries through this
152     /// interface should return addresses for hidden symbols.
153     ///
154     /// This is of particular importance for the Orc JIT APIs, which support lazy
155     /// compilation by breaking up modules: Each of those broken out modules
156     /// must be able to resolve hidden symbols provided by the others. Clients
157     /// writing memory managers for MCJIT can usually ignore this method.
158     ///
159     /// This method will be queried by RuntimeDyld when checking for previous
160     /// definitions of common symbols. It will *not* be queried by default when
161     /// resolving external symbols (this minimises the link-time overhead for
162     /// MCJIT clients who don't care about Orc features). If you are writing a
163     /// RTDyldMemoryManager for Orc and want "external" symbol resolution to
164     /// search the logical dylib, you should override your getSymbolAddress
165     /// method call this method directly.
166     virtual SymbolInfo findSymbolInLogicalDylib(const std::string &Name) = 0;
167   private:
168     virtual void anchor();
169   };
170
171   /// \brief Construct a RuntimeDyld instance.
172   RuntimeDyld(MemoryManager &MemMgr, SymbolResolver &Resolver);
173   ~RuntimeDyld();
174
175   /// Add the referenced object file to the list of objects to be loaded and
176   /// relocated.
177   std::unique_ptr<LoadedObjectInfo> loadObject(const object::ObjectFile &O);
178
179   /// Get the address of our local copy of the symbol. This may or may not
180   /// be the address used for relocation (clients can copy the data around
181   /// and resolve relocatons based on where they put it).
182   void *getSymbolLocalAddress(StringRef Name) const;
183
184   /// Get the target address and flags for the named symbol.
185   /// This address is the one used for relocation.
186   SymbolInfo getSymbol(StringRef Name) const;
187
188   /// Resolve the relocations for all symbols we currently know about.
189   void resolveRelocations();
190
191   /// Map a section to its target address space value.
192   /// Map the address of a JIT section as returned from the memory manager
193   /// to the address in the target process as the running code will see it.
194   /// This is the address which will be used for relocation resolution.
195   void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
196
197   /// Register any EH frame sections that have been loaded but not previously
198   /// registered with the memory manager.  Note, RuntimeDyld is responsible
199   /// for identifying the EH frame and calling the memory manager with the
200   /// EH frame section data.  However, the memory manager itself will handle
201   /// the actual target-specific EH frame registration.
202   void registerEHFrames();
203
204   void deregisterEHFrames();
205
206   bool hasError();
207   StringRef getErrorString();
208
209   /// By default, only sections that are "required for execution" are passed to
210   /// the RTDyldMemoryManager, and other sections are discarded. Passing 'true'
211   /// to this method will cause RuntimeDyld to pass all sections to its
212   /// memory manager regardless of whether they are "required to execute" in the
213   /// usual sense. This is useful for inspecting metadata sections that may not
214   /// contain relocations, E.g. Debug info, stackmaps.
215   ///
216   /// Must be called before the first object file is loaded.
217   void setProcessAllSections(bool ProcessAllSections) {
218     assert(!Dyld && "setProcessAllSections must be called before loadObject.");
219     this->ProcessAllSections = ProcessAllSections;
220   }
221
222 private:
223   // RuntimeDyldImpl is the actual class. RuntimeDyld is just the public
224   // interface.
225   std::unique_ptr<RuntimeDyldImpl> Dyld;
226   MemoryManager &MemMgr;
227   SymbolResolver &Resolver;
228   bool ProcessAllSections;
229   RuntimeDyldCheckerImpl *Checker;
230 };
231
232 } // end namespace llvm
233
234 #endif