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