1 //===-- RuntimeDyld.h - Run-time dynamic linker for MC-JIT ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Interface for the runtime dynamic linker facilities of the MC-JIT.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
15 #define LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
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"
30 template <typename T> class OwningBinary;
33 class RuntimeDyldImpl;
34 class RuntimeDyldCheckerImpl;
37 friend class RuntimeDyldCheckerImpl;
39 RuntimeDyld(const RuntimeDyld &) = delete;
40 void operator=(const RuntimeDyld &) = delete;
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);
48 /// \brief Information about a named symbol.
49 class SymbolInfo : public JITSymbolBase {
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; }
60 /// \brief Information about the loaded object.
61 class LoadedObjectInfo : public llvm::LoadedObjectInfo {
62 friend class RuntimeDyldImpl;
64 typedef std::map<object::SectionRef, unsigned> ObjSectionToIDMap;
66 LoadedObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
67 : RTDyld(RTDyld), ObjSecToIDMap(ObjSecToIDMap) { }
69 virtual object::OwningBinary<object::ObjectFile>
70 getObjectForDebug(const object::ObjectFile &Obj) const = 0;
73 getSectionLoadAddress(const object::SectionRef &Sec) const override;
76 virtual void anchor();
78 RuntimeDyldImpl &RTDyld;
79 ObjSectionToIDMap ObjSecToIDMap;
82 template <typename Derived> struct LoadedObjectInfoHelper : LoadedObjectInfo {
84 LoadedObjectInfoHelper(const LoadedObjectInfoHelper &) = default;
85 LoadedObjectInfoHelper() = default;
88 LoadedObjectInfoHelper(RuntimeDyldImpl &RTDyld,
89 LoadedObjectInfo::ObjSectionToIDMap ObjSecToIDMap)
90 : LoadedObjectInfo(RTDyld, std::move(ObjSecToIDMap)) {}
91 std::unique_ptr<llvm::LoadedObjectInfo> clone() const override {
92 return llvm::make_unique<Derived>(static_cast<const Derived &>(*this));
96 /// \brief Memory Management.
98 friend class RuntimeDyld;
100 MemoryManager() : FinalizationLocked(false) {}
101 virtual ~MemoryManager() {}
103 /// Allocate a memory block of (at least) the given size suitable for
104 /// executable code. The SectionID is a unique identifier assigned by the
105 /// RuntimeDyld instance, and optionally recorded by the memory manager to
106 /// access a loaded section.
107 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
109 StringRef SectionName) = 0;
111 /// Allocate a memory block of (at least) the given size suitable for data.
112 /// The SectionID is a unique identifier assigned by the JIT engine, and
113 /// optionally recorded by the memory manager to access a loaded section.
114 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
116 StringRef SectionName,
117 bool IsReadOnly) = 0;
119 /// Inform the memory manager about the total amount of memory required to
120 /// allocate all sections to be loaded:
121 /// \p CodeSize - the total size of all code sections
122 /// \p DataSizeRO - the total size of all read-only data sections
123 /// \p DataSizeRW - the total size of all read-write data sections
125 /// Note that by default the callback is disabled. To enable it
126 /// redefine the method needsToReserveAllocationSpace to return true.
127 virtual void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
128 uintptr_t RODataSize,
129 uint32_t RODataAlign,
130 uintptr_t RWDataSize,
131 uint32_t RWDataAlign) {}
133 /// Override to return true to enable the reserveAllocationSpace callback.
134 virtual bool needsToReserveAllocationSpace() { return false; }
136 /// Register the EH frames with the runtime so that c++ exceptions work.
138 /// \p Addr parameter provides the local address of the EH frame section
139 /// data, while \p LoadAddr provides the address of the data in the target
140 /// address space. If the section has not been remapped (which will usually
141 /// be the case for local execution) these two values will be the same.
142 virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
144 virtual void deregisterEHFrames(uint8_t *addr, uint64_t LoadAddr,
147 /// This method is called when object loading is complete and section page
148 /// permissions can be applied. It is up to the memory manager implementation
149 /// to decide whether or not to act on this method. The memory manager will
150 /// typically allocate all sections as read-write and then apply specific
151 /// permissions when this method is called. Code sections cannot be executed
152 /// until this function has been called. In addition, any cache coherency
153 /// operations needed to reliably use the memory are also performed.
155 /// Returns true if an error occurred, false otherwise.
156 virtual bool finalizeMemory(std::string *ErrMsg = nullptr) = 0;
158 /// This method is called after an object has been loaded into memory but
159 /// before relocations are applied to the loaded sections.
161 /// Memory managers which are preparing code for execution in an external
162 /// address space can use this call to remap the section addresses for the
163 /// newly loaded object.
165 /// For clients that do not need access to an ExecutionEngine instance this
166 /// method should be preferred to its cousin
167 /// MCJITMemoryManager::notifyObjectLoaded as this method is compatible with
169 virtual void notifyObjectLoaded(RuntimeDyld &RTDyld,
170 const object::ObjectFile &Obj) {}
173 virtual void anchor();
174 bool FinalizationLocked;
177 /// \brief Symbol resolution.
178 class SymbolResolver {
180 virtual ~SymbolResolver() {}
182 /// This method returns the address of the specified function or variable.
183 /// It is used to resolve symbols during module linking.
185 /// If the returned symbol's address is equal to ~0ULL then RuntimeDyld will
186 /// skip all relocations for that symbol, and the client will be responsible
187 /// for handling them manually.
188 virtual SymbolInfo findSymbol(const std::string &Name) = 0;
190 /// This method returns the address of the specified symbol if it exists
191 /// within the logical dynamic library represented by this
192 /// RTDyldMemoryManager. Unlike getSymbolAddress, queries through this
193 /// interface should return addresses for hidden symbols.
195 /// This is of particular importance for the Orc JIT APIs, which support lazy
196 /// compilation by breaking up modules: Each of those broken out modules
197 /// must be able to resolve hidden symbols provided by the others. Clients
198 /// writing memory managers for MCJIT can usually ignore this method.
200 /// This method will be queried by RuntimeDyld when checking for previous
201 /// definitions of common symbols. It will *not* be queried by default when
202 /// resolving external symbols (this minimises the link-time overhead for
203 /// MCJIT clients who don't care about Orc features). If you are writing a
204 /// RTDyldMemoryManager for Orc and want "external" symbol resolution to
205 /// search the logical dylib, you should override your getSymbolAddress
206 /// method call this method directly.
207 virtual SymbolInfo findSymbolInLogicalDylib(const std::string &Name) = 0;
209 virtual void anchor();
212 /// \brief Construct a RuntimeDyld instance.
213 RuntimeDyld(MemoryManager &MemMgr, SymbolResolver &Resolver);
216 /// Add the referenced object file to the list of objects to be loaded and
218 std::unique_ptr<LoadedObjectInfo> loadObject(const object::ObjectFile &O);
220 /// Get the address of our local copy of the symbol. This may or may not
221 /// be the address used for relocation (clients can copy the data around
222 /// and resolve relocatons based on where they put it).
223 void *getSymbolLocalAddress(StringRef Name) const;
225 /// Get the target address and flags for the named symbol.
226 /// This address is the one used for relocation.
227 SymbolInfo getSymbol(StringRef Name) const;
229 /// Resolve the relocations for all symbols we currently know about.
230 void resolveRelocations();
232 /// Map a section to its target address space value.
233 /// Map the address of a JIT section as returned from the memory manager
234 /// to the address in the target process as the running code will see it.
235 /// This is the address which will be used for relocation resolution.
236 void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
238 /// Register any EH frame sections that have been loaded but not previously
239 /// registered with the memory manager. Note, RuntimeDyld is responsible
240 /// for identifying the EH frame and calling the memory manager with the
241 /// EH frame section data. However, the memory manager itself will handle
242 /// the actual target-specific EH frame registration.
243 void registerEHFrames();
245 void deregisterEHFrames();
248 StringRef getErrorString();
250 /// By default, only sections that are "required for execution" are passed to
251 /// the RTDyldMemoryManager, and other sections are discarded. Passing 'true'
252 /// to this method will cause RuntimeDyld to pass all sections to its
253 /// memory manager regardless of whether they are "required to execute" in the
254 /// usual sense. This is useful for inspecting metadata sections that may not
255 /// contain relocations, E.g. Debug info, stackmaps.
257 /// Must be called before the first object file is loaded.
258 void setProcessAllSections(bool ProcessAllSections) {
259 assert(!Dyld && "setProcessAllSections must be called before loadObject.");
260 this->ProcessAllSections = ProcessAllSections;
263 /// Perform all actions needed to make the code owned by this RuntimeDyld
264 /// instance executable:
266 /// 1) Apply relocations.
267 /// 2) Register EH frames.
268 /// 3) Update memory permissions*.
270 /// * Finalization is potentially recursive**, and the 3rd step will only be
271 /// applied by the outermost call to finalize. This allows different
272 /// RuntimeDyld instances to share a memory manager without the innermost
273 /// finalization locking the memory and causing relocation fixup errors in
276 /// ** Recursive finalization occurs when one RuntimeDyld instances needs the
277 /// address of a symbol owned by some other instance in order to apply
280 void finalizeWithMemoryManagerLocking();
283 // RuntimeDyldImpl is the actual class. RuntimeDyld is just the public
285 std::unique_ptr<RuntimeDyldImpl> Dyld;
286 MemoryManager &MemMgr;
287 SymbolResolver &Resolver;
288 bool ProcessAllSections;
289 RuntimeDyldCheckerImpl *Checker;
292 } // end namespace llvm
294 #endif // LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H