LLVM 24.0.0git
RuntimeDyld.h
Go to the documentation of this file.
1//===- RuntimeDyld.h - Run-time dynamic linker for MC-JIT -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Interface for the runtime dynamic linker facilities of the MC-JIT.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
14#define LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
15
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/Error.h"
24#include <algorithm>
25#include <cassert>
26#include <cstddef>
27#include <cstdint>
28#include <map>
29#include <memory>
30#include <string>
31#include <system_error>
32
33namespace llvm {
34
35namespace object {
36
37template <typename T> class OwningBinary;
38
39} // end namespace object
40
41/// Base class for errors originating in RuntimeDyld, e.g. missing relocation
42/// support.
43class LLVM_ABI RuntimeDyldError : public ErrorInfo<RuntimeDyldError> {
44public:
45 static char ID;
46
47 RuntimeDyldError(std::string ErrMsg) : ErrMsg(std::move(ErrMsg)) {}
48
49 void log(raw_ostream &OS) const override;
50 const std::string &getErrorMessage() const { return ErrMsg; }
51 std::error_code convertToErrorCode() const override;
52
53private:
54 std::string ErrMsg;
55};
56
57class RuntimeDyldImpl;
58
60public:
61 // Change the address associated with a section when resolving relocations.
62 // Any relocations already associated with the symbol will be re-resolved.
63 LLVM_ABI void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
64
65 using NotifyStubEmittedFunction = std::function<void(
66 StringRef FileName, StringRef SectionName, StringRef SymbolName,
67 unsigned SectionID, uint32_t StubOffset)>;
68
69 /// Information about the loaded object.
71 friend class RuntimeDyldImpl;
72
73 public:
74 using ObjSectionToIDMap = std::map<object::SectionRef, unsigned>;
75
78
81
83 getSectionLoadAddress(const object::SectionRef &Sec) const override;
84
85 protected:
86 virtual void anchor();
87
90 };
91
92 /// Memory Management.
94 friend class RuntimeDyld;
95
96 public:
97 MemoryManager() = default;
98 virtual ~MemoryManager() = default;
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,
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,
114 bool IsReadOnly) = 0;
115
116 /// An allocated TLS section
117 struct TLSSection {
118 /// The pointer to the initialization image
120 /// The TLS offset
121 intptr_t Offset;
122 };
123
124 /// Allocate a memory block of (at least) the given size to be used for
125 /// thread-local storage (TLS).
126 /// Return a null InitializationImage if allocation is unsupported or fails.
127 virtual TLSSection allocateTLSSection(uintptr_t Size, unsigned Alignment,
128 unsigned SectionID,
130
131 /// Inform the memory manager about the total amount of memory required to
132 /// allocate all sections to be loaded:
133 /// \p CodeSize - the total size of all code sections
134 /// \p DataSizeRO - the total size of all read-only data sections
135 /// \p DataSizeRW - the total size of all read-write data sections
136 ///
137 /// Note that by default the callback is disabled. To enable it
138 /// redefine the method needsToReserveAllocationSpace to return true.
140 uintptr_t RODataSize, Align RODataAlign,
141 uintptr_t RWDataSize,
142 Align RWDataAlign) {}
143
144 /// Override to return true to enable the reserveAllocationSpace callback.
145 virtual bool needsToReserveAllocationSpace() { return false; }
146
147 /// Override to return false to tell LLVM no stub space will be needed.
148 /// This requires some guarantees depending on architecuture, but when
149 /// you know what you are doing it saves allocated space.
150 virtual bool allowStubAllocation() const { return true; }
151
152 /// Register the EH frames with the runtime so that c++ exceptions work.
153 ///
154 /// \p Addr parameter provides the local address of the EH frame section
155 /// data, while \p LoadAddr provides the address of the data in the target
156 /// address space. If the section has not been remapped (which will usually
157 /// be the case for local execution) these two values will be the same.
158 virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
159 size_t Size) = 0;
160 virtual void deregisterEHFrames() = 0;
161
162 /// This method is called when object loading is complete and section page
163 /// permissions can be applied. It is up to the memory manager implementation
164 /// to decide whether or not to act on this method. The memory manager will
165 /// typically allocate all sections as read-write and then apply specific
166 /// permissions when this method is called. Code sections cannot be executed
167 /// until this function has been called. In addition, any cache coherency
168 /// operations needed to reliably use the memory are also performed.
169 ///
170 /// Returns true if an error occurred, false otherwise.
171 virtual bool finalizeMemory(std::string *ErrMsg = nullptr) = 0;
172
173 /// This method is called after an object has been loaded into memory but
174 /// before relocations are applied to the loaded sections.
175 ///
176 /// Memory managers which are preparing code for execution in an external
177 /// address space can use this call to remap the section addresses for the
178 /// newly loaded object.
179 ///
180 /// For clients that do not need access to an ExecutionEngine instance this
181 /// method should be preferred to its cousin
182 /// MCJITMemoryManager::notifyObjectLoaded as this method is compatible with
183 /// ORC JIT stacks.
184 virtual void notifyObjectLoaded(RuntimeDyld &RTDyld,
185 const object::ObjectFile &Obj) {}
186
187 private:
188 virtual void anchor();
189
190 bool FinalizationLocked = false;
191 };
192
193 /// Construct a RuntimeDyld instance.
194 LLVM_ABI RuntimeDyld(MemoryManager &MemMgr, JITSymbolResolver &Resolver);
195 RuntimeDyld(const RuntimeDyld &) = delete;
198
199 /// Add the referenced object file to the list of objects to be loaded and
200 /// relocated.
201 LLVM_ABI std::unique_ptr<LoadedObjectInfo>
203
204 /// Get the address of our local copy of the symbol. This may or may not
205 /// be the address used for relocation (clients can copy the data around
206 /// and resolve relocatons based on where they put it).
207 LLVM_ABI void *getSymbolLocalAddress(StringRef Name) const;
208
209 /// Get the section ID for the section containing the given symbol.
210 LLVM_ABI unsigned getSymbolSectionID(StringRef Name) const;
211
212 /// Get the target address and flags for the named symbol.
213 /// This address is the one used for relocation.
215
216 /// Returns a copy of the symbol table. This can be used by on-finalized
217 /// callbacks to extract the symbol table before throwing away the
218 /// RuntimeDyld instance. Because the map keys (StringRefs) are backed by
219 /// strings inside the RuntimeDyld instance, the map should be processed
220 /// before the RuntimeDyld instance is discarded.
221 LLVM_ABI std::map<StringRef, JITEvaluatedSymbol> getSymbolTable() const;
222
223 /// Resolve the relocations for all symbols we currently know about.
225
226 /// Map a section to its target address space value.
227 /// Map the address of a JIT section as returned from the memory manager
228 /// to the address in the target process as the running code will see it.
229 /// This is the address which will be used for relocation resolution.
230 LLVM_ABI void mapSectionAddress(const void *LocalAddress,
231 uint64_t TargetAddress);
232
233 /// Returns the section's working memory.
234 LLVM_ABI StringRef getSectionContent(unsigned SectionID) const;
235
236 /// If the section was loaded, return the section's load address,
237 /// otherwise return std::nullopt.
238 LLVM_ABI uint64_t getSectionLoadAddress(unsigned SectionID) const;
239
240 /// Set the NotifyStubEmitted callback. This is used for debugging
241 /// purposes. A callback is made for each stub that is generated.
243 this->NotifyStubEmitted = std::move(NotifyStubEmitted);
244 }
245
246 /// Register any EH frame sections that have been loaded but not previously
247 /// registered with the memory manager. Note, RuntimeDyld is responsible
248 /// for identifying the EH frame and calling the memory manager with the
249 /// EH frame section data. However, the memory manager itself will handle
250 /// the actual target-specific EH frame registration.
252
254
255 LLVM_ABI bool hasError();
257
258 /// By default, only sections that are "required for execution" are passed to
259 /// the RTDyldMemoryManager, and other sections are discarded. Passing 'true'
260 /// to this method will cause RuntimeDyld to pass all sections to its
261 /// memory manager regardless of whether they are "required to execute" in the
262 /// usual sense. This is useful for inspecting metadata sections that may not
263 /// contain relocations, E.g. Debug info, stackmaps.
264 ///
265 /// Must be called before the first object file is loaded.
266 void setProcessAllSections(bool ProcessAllSections) {
267 assert(!Dyld && "setProcessAllSections must be called before loadObject.");
268 this->ProcessAllSections = ProcessAllSections;
269 }
270
271 /// Perform all actions needed to make the code owned by this RuntimeDyld
272 /// instance executable:
273 ///
274 /// 1) Apply relocations.
275 /// 2) Register EH frames.
276 /// 3) Update memory permissions*.
277 ///
278 /// * Finalization is potentially recursive**, and the 3rd step will only be
279 /// applied by the outermost call to finalize. This allows different
280 /// RuntimeDyld instances to share a memory manager without the innermost
281 /// finalization locking the memory and causing relocation fixup errors in
282 /// outer instances.
283 ///
284 /// ** Recursive finalization occurs when one RuntimeDyld instances needs the
285 /// address of a symbol owned by some other instance in order to apply
286 /// relocations.
287 ///
289
290private:
294 bool ProcessAllSections,
296 std::map<StringRef, JITEvaluatedSymbol>)>
297 OnLoaded,
299 std::unique_ptr<LoadedObjectInfo>, Error)>
300 OnEmitted);
301
302 // RuntimeDyldImpl is the actual class. RuntimeDyld is just the public
303 // interface.
304 std::unique_ptr<RuntimeDyldImpl> Dyld;
305 MemoryManager &MemMgr;
306 JITSymbolResolver &Resolver;
307 bool ProcessAllSections;
308 NotifyStubEmittedFunction NotifyStubEmitted;
309};
310
311// Asynchronous JIT link for ORC.
312//
313// Warning: This API is experimental and probably should not be used by anyone
314// but ORC's RTDyldObjectLinkingLayer2. Internally it constructs a RuntimeDyld
315// instance and uses continuation passing to perform the fix-up and finalize
316// steps asynchronously.
320 bool ProcessAllSections,
323 std::map<StringRef, JITEvaluatedSymbol>)>
324 OnLoaded,
326 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
327 OnEmitted);
328
329} // end namespace llvm
330
331#endif // LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
#define LLVM_ABI
Definition Compiler.h:215
This file provides a collection of function (or more generally, callable) type erasure utilities supp...
This file contains some templates that are useful if you are working with the STL at all.
Base class for user error types.
Definition Error.h:354
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Represents a symbol that has been evaluated to an address already.
Definition JITSymbol.h:231
Symbol resolution interface.
Definition JITSymbol.h:373
An inferface for inquiring the load address of a loaded object file to be used by the DIContext imple...
Definition DIContext.h:282
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition Record.h:2233
const std::string & getErrorMessage() const
Definition RuntimeDyld.h:50
RuntimeDyldError(std::string ErrMsg)
Definition RuntimeDyld.h:47
Information about the loaded object.
Definition RuntimeDyld.h:70
uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override
Obtain the Load Address of a section by SectionRef.
std::map< object::SectionRef, unsigned > ObjSectionToIDMap
Definition RuntimeDyld.h:74
virtual object::OwningBinary< object::ObjectFile > getObjectForDebug(const object::ObjectFile &Obj) const =0
LoadedObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
Definition RuntimeDyld.h:76
virtual void reserveAllocationSpace(uintptr_t CodeSize, Align CodeAlign, uintptr_t RODataSize, Align RODataAlign, uintptr_t RWDataSize, Align RWDataAlign)
Inform the memory manager about the total amount of memory required to allocate all sections to be lo...
virtual bool needsToReserveAllocationSpace()
Override to return true to enable the reserveAllocationSpace callback.
virtual void notifyObjectLoaded(RuntimeDyld &RTDyld, const object::ObjectFile &Obj)
This method is called after an object has been loaded into memory but before relocations are applied ...
virtual uint8_t * allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly)=0
Allocate a memory block of (at least) the given size suitable for data.
virtual TLSSection allocateTLSSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName)
Allocate a memory block of (at least) the given size to be used for thread-local storage (TLS).
virtual ~MemoryManager()=default
virtual uint8_t * allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName)=0
Allocate a memory block of (at least) the given size suitable for executable code.
virtual void deregisterEHFrames()=0
virtual bool finalizeMemory(std::string *ErrMsg=nullptr)=0
This method is called when object loading is complete and section page permissions can be applied.
virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size)=0
Register the EH frames with the runtime so that c++ exceptions work.
virtual bool allowStubAllocation() const
Override to return false to tell LLVM no stub space will be needed.
RuntimeDyld(const RuntimeDyld &)=delete
LLVM_ABI void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress)
Map a section to its target address space value.
void setProcessAllSections(bool ProcessAllSections)
By default, only sections that are "required for execution" are passed to the RTDyldMemoryManager,...
LLVM_ABI void reassignSectionAddress(unsigned SectionID, uint64_t Addr)
LLVM_ABI uint64_t getSectionLoadAddress(unsigned SectionID) const
If the section was loaded, return the section's load address, otherwise return std::nullopt.
LLVM_ABI void * getSymbolLocalAddress(StringRef Name) const
Get the address of our local copy of the symbol.
LLVM_ABI std::map< StringRef, JITEvaluatedSymbol > getSymbolTable() const
Returns a copy of the symbol table.
LLVM_ABI void resolveRelocations()
Resolve the relocations for all symbols we currently know about.
LLVM_ABI void finalizeWithMemoryManagerLocking()
Perform all actions needed to make the code owned by this RuntimeDyld instance executable:
void setNotifyStubEmitted(NotifyStubEmittedFunction NotifyStubEmitted)
Set the NotifyStubEmitted callback.
std::function< void( StringRef FileName, StringRef SectionName, StringRef SymbolName, unsigned SectionID, uint32_t StubOffset)> NotifyStubEmittedFunction
Definition RuntimeDyld.h:65
LLVM_ABI void deregisterEHFrames()
LLVM_ABI void registerEHFrames()
Register any EH frame sections that have been loaded but not previously registered with the memory ma...
LLVM_ABI ~RuntimeDyld()
LLVM_ABI StringRef getSectionContent(unsigned SectionID) const
Returns the section's working memory.
LLVM_ABI JITEvaluatedSymbol getSymbol(StringRef Name) const
Get the target address and flags for the named symbol.
LLVM_ABI friend void jitLinkForORC(object::OwningBinary< object::ObjectFile > O, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver, bool ProcessAllSections, unique_function< Error(const object::ObjectFile &Obj, LoadedObjectInfo &, std::map< StringRef, JITEvaluatedSymbol >)> OnLoaded, unique_function< void(object::OwningBinary< object::ObjectFile > O, std::unique_ptr< LoadedObjectInfo >, Error)> OnEmitted)
LLVM_ABI RuntimeDyld(MemoryManager &MemMgr, JITSymbolResolver &Resolver)
Construct a RuntimeDyld instance.
LLVM_ABI bool hasError()
RuntimeDyld & operator=(const RuntimeDyld &)=delete
LLVM_ABI std::unique_ptr< LoadedObjectInfo > loadObject(const object::ObjectFile &O)
Add the referenced object file to the list of objects to be loaded and relocated.
LLVM_ABI StringRef getErrorString()
LLVM_ABI unsigned getSymbolSectionID(StringRef Name) const
Get the section ID for the section containing the given symbol.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
This class is the base class for all object file types.
Definition ObjectFile.h:231
This is a value type class that represents a single section in the list of sections in the object fil...
Definition ObjectFile.h:83
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unique_function is a type-erasing functor similar to std::function.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void jitLinkForORC(object::OwningBinary< object::ObjectFile > O, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver, bool ProcessAllSections, unique_function< Error(const object::ObjectFile &Obj, RuntimeDyld::LoadedObjectInfo &, std::map< StringRef, JITEvaluatedSymbol >)> OnLoaded, unique_function< void(object::OwningBinary< object::ObjectFile >, std::unique_ptr< RuntimeDyld::LoadedObjectInfo >, Error)> OnEmitted)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
uint8_t * InitializationImage
The pointer to the initialization image.