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 "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/DebugInfo/DIContext.h"
20 #include "llvm/ExecutionEngine/JITSymbol.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/Error.h"
30 #include <system_error>
35 template <typename T> class OwningBinary;
36 } // end namespace object
38 /// Base class for errors originating in RuntimeDyld, e.g. missing relocation
40 class RuntimeDyldError : public ErrorInfo<RuntimeDyldError> {
44 RuntimeDyldError(std::string ErrMsg) : ErrMsg(std::move(ErrMsg)) {}
46 void log(raw_ostream &OS) const override;
47 const std::string &getErrorMessage() const { return ErrMsg; }
48 std::error_code convertToErrorCode() const override;
54 class RuntimeDyldImpl;
55 class RuntimeDyldCheckerImpl;
58 friend class RuntimeDyldCheckerImpl;
61 // Change the address associated with a section when resolving relocations.
62 // Any relocations already associated with the symbol will be re-resolved.
63 void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
66 /// \brief Information about the loaded object.
67 class LoadedObjectInfo : public llvm::LoadedObjectInfo {
68 friend class RuntimeDyldImpl;
71 typedef std::map<object::SectionRef, unsigned> ObjSectionToIDMap;
73 LoadedObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
74 : RTDyld(RTDyld), ObjSecToIDMap(std::move(ObjSecToIDMap)) {}
76 virtual object::OwningBinary<object::ObjectFile>
77 getObjectForDebug(const object::ObjectFile &Obj) const = 0;
80 getSectionLoadAddress(const object::SectionRef &Sec) const override;
83 virtual void anchor();
85 RuntimeDyldImpl &RTDyld;
86 ObjSectionToIDMap ObjSecToIDMap;
89 template <typename Derived> struct LoadedObjectInfoHelper : LoadedObjectInfo {
91 LoadedObjectInfoHelper(const LoadedObjectInfoHelper &) = default;
92 LoadedObjectInfoHelper() = default;
95 LoadedObjectInfoHelper(RuntimeDyldImpl &RTDyld,
96 LoadedObjectInfo::ObjSectionToIDMap ObjSecToIDMap)
97 : LoadedObjectInfo(RTDyld, std::move(ObjSecToIDMap)) {}
99 std::unique_ptr<llvm::LoadedObjectInfo> clone() const override {
100 return llvm::make_unique<Derived>(static_cast<const Derived &>(*this));
104 /// \brief Memory Management.
105 class MemoryManager {
106 friend class RuntimeDyld;
109 MemoryManager() = default;
110 virtual ~MemoryManager() = default;
112 /// Allocate a memory block of (at least) the given size suitable for
113 /// executable code. The SectionID is a unique identifier assigned by the
114 /// RuntimeDyld instance, and optionally recorded by the memory manager to
115 /// access a loaded section.
116 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
118 StringRef SectionName) = 0;
120 /// Allocate a memory block of (at least) the given size suitable for data.
121 /// The SectionID is a unique identifier assigned by the JIT engine, and
122 /// optionally recorded by the memory manager to access a loaded section.
123 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
125 StringRef SectionName,
126 bool IsReadOnly) = 0;
128 /// Inform the memory manager about the total amount of memory required to
129 /// allocate all sections to be loaded:
130 /// \p CodeSize - the total size of all code sections
131 /// \p DataSizeRO - the total size of all read-only data sections
132 /// \p DataSizeRW - the total size of all read-write data sections
134 /// Note that by default the callback is disabled. To enable it
135 /// redefine the method needsToReserveAllocationSpace to return true.
136 virtual void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
137 uintptr_t RODataSize,
138 uint32_t RODataAlign,
139 uintptr_t RWDataSize,
140 uint32_t RWDataAlign) {}
142 /// Override to return true to enable the reserveAllocationSpace callback.
143 virtual bool needsToReserveAllocationSpace() { return false; }
145 /// Register the EH frames with the runtime so that c++ exceptions work.
147 /// \p Addr parameter provides the local address of the EH frame section
148 /// data, while \p LoadAddr provides the address of the data in the target
149 /// address space. If the section has not been remapped (which will usually
150 /// be the case for local execution) these two values will be the same.
151 virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
153 virtual void deregisterEHFrames(uint8_t *addr, uint64_t LoadAddr,
156 /// This method is called when object loading is complete and section page
157 /// permissions can be applied. It is up to the memory manager implementation
158 /// to decide whether or not to act on this method. The memory manager will
159 /// typically allocate all sections as read-write and then apply specific
160 /// permissions when this method is called. Code sections cannot be executed
161 /// until this function has been called. In addition, any cache coherency
162 /// operations needed to reliably use the memory are also performed.
164 /// Returns true if an error occurred, false otherwise.
165 virtual bool finalizeMemory(std::string *ErrMsg = nullptr) = 0;
167 /// This method is called after an object has been loaded into memory but
168 /// before relocations are applied to the loaded sections.
170 /// Memory managers which are preparing code for execution in an external
171 /// address space can use this call to remap the section addresses for the
172 /// newly loaded object.
174 /// For clients that do not need access to an ExecutionEngine instance this
175 /// method should be preferred to its cousin
176 /// MCJITMemoryManager::notifyObjectLoaded as this method is compatible with
178 virtual void notifyObjectLoaded(RuntimeDyld &RTDyld,
179 const object::ObjectFile &Obj) {}
182 virtual void anchor();
184 bool FinalizationLocked = false;
187 /// \brief Construct a RuntimeDyld instance.
188 RuntimeDyld(MemoryManager &MemMgr, JITSymbolResolver &Resolver);
189 RuntimeDyld(const RuntimeDyld &) = delete;
190 void operator=(const RuntimeDyld &) = delete;
193 /// Add the referenced object file to the list of objects to be loaded and
195 std::unique_ptr<LoadedObjectInfo> loadObject(const object::ObjectFile &O);
197 /// Get the address of our local copy of the symbol. This may or may not
198 /// be the address used for relocation (clients can copy the data around
199 /// and resolve relocatons based on where they put it).
200 void *getSymbolLocalAddress(StringRef Name) const;
202 /// Get the target address and flags for the named symbol.
203 /// This address is the one used for relocation.
204 JITEvaluatedSymbol getSymbol(StringRef Name) const;
206 /// Resolve the relocations for all symbols we currently know about.
207 void resolveRelocations();
209 /// Map a section to its target address space value.
210 /// Map the address of a JIT section as returned from the memory manager
211 /// to the address in the target process as the running code will see it.
212 /// This is the address which will be used for relocation resolution.
213 void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
215 /// Register any EH frame sections that have been loaded but not previously
216 /// registered with the memory manager. Note, RuntimeDyld is responsible
217 /// for identifying the EH frame and calling the memory manager with the
218 /// EH frame section data. However, the memory manager itself will handle
219 /// the actual target-specific EH frame registration.
220 void registerEHFrames();
222 void deregisterEHFrames();
225 StringRef getErrorString();
227 /// By default, only sections that are "required for execution" are passed to
228 /// the RTDyldMemoryManager, and other sections are discarded. Passing 'true'
229 /// to this method will cause RuntimeDyld to pass all sections to its
230 /// memory manager regardless of whether they are "required to execute" in the
231 /// usual sense. This is useful for inspecting metadata sections that may not
232 /// contain relocations, E.g. Debug info, stackmaps.
234 /// Must be called before the first object file is loaded.
235 void setProcessAllSections(bool ProcessAllSections) {
236 assert(!Dyld && "setProcessAllSections must be called before loadObject.");
237 this->ProcessAllSections = ProcessAllSections;
240 /// Perform all actions needed to make the code owned by this RuntimeDyld
241 /// instance executable:
243 /// 1) Apply relocations.
244 /// 2) Register EH frames.
245 /// 3) Update memory permissions*.
247 /// * Finalization is potentially recursive**, and the 3rd step will only be
248 /// applied by the outermost call to finalize. This allows different
249 /// RuntimeDyld instances to share a memory manager without the innermost
250 /// finalization locking the memory and causing relocation fixup errors in
253 /// ** Recursive finalization occurs when one RuntimeDyld instances needs the
254 /// address of a symbol owned by some other instance in order to apply
257 void finalizeWithMemoryManagerLocking();
260 // RuntimeDyldImpl is the actual class. RuntimeDyld is just the public
262 std::unique_ptr<RuntimeDyldImpl> Dyld;
263 MemoryManager &MemMgr;
264 JITSymbolResolver &Resolver;
265 bool ProcessAllSections;
266 RuntimeDyldCheckerImpl *Checker;
269 } // end namespace llvm
271 #endif // LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H