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