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