LLVM 20.0.0git
ExecutionUtils.h
Go to the documentation of this file.
1//===- ExecutionUtils.h - Utilities for executing code in Orc ---*- 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// Contains utilities for executing code in Orc.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
14#define LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
15
23#include "llvm/Object/Archive.h"
25#include <algorithm>
26#include <cstdint>
27#include <utility>
28#include <vector>
29
30namespace llvm {
31
32class ConstantArray;
33class GlobalVariable;
34class Function;
35class Module;
36class Value;
37
38namespace object {
39class MachOUniversalBinary;
40}
41
42namespace orc {
43
44class ObjectLayer;
45
46/// This iterator provides a convenient way to iterate over the elements
47/// of an llvm.global_ctors/llvm.global_dtors instance.
48///
49/// The easiest way to get hold of instances of this class is to use the
50/// getConstructors/getDestructors functions.
52public:
53 /// Accessor for an element of the global_ctors/global_dtors array.
54 ///
55 /// This class provides a read-only view of the element with any casts on
56 /// the function stripped away.
57 struct Element {
60
61 unsigned Priority;
64 };
65
66 /// Construct an iterator instance. If End is true then this iterator
67 /// acts as the end of the range, otherwise it is the beginning.
68 CtorDtorIterator(const GlobalVariable *GV, bool End);
69
70 /// Test iterators for equality.
71 bool operator==(const CtorDtorIterator &Other) const;
72
73 /// Test iterators for inequality.
74 bool operator!=(const CtorDtorIterator &Other) const;
75
76 /// Pre-increment iterator.
78
79 /// Post-increment iterator.
81
82 /// Dereference iterator. The resulting value provides a read-only view
83 /// of this element of the global_ctors/global_dtors list.
84 Element operator*() const;
85
86private:
87 const ConstantArray *InitList;
88 unsigned I;
89};
90
91/// Create an iterator range over the entries of the llvm.global_ctors
92/// array.
94
95/// Create an iterator range over the entries of the llvm.global_ctors
96/// array.
98
99/// This iterator provides a convenient way to iterate over GlobalValues that
100/// have initialization effects.
102public:
104
106 : I(M.global_values().begin()), E(M.global_values().end()),
107 ObjFmt(Triple(M.getTargetTriple()).getObjectFormat()) {
108 if (I != E) {
109 if (!isStaticInitGlobal(*I))
110 moveToNextStaticInitGlobal();
111 } else
113 }
114
115 bool operator==(const StaticInitGVIterator &O) const { return I == O.I; }
116 bool operator!=(const StaticInitGVIterator &O) const { return I != O.I; }
117
119 assert(I != E && "Increment past end of range");
120 moveToNextStaticInitGlobal();
121 return *this;
122 }
123
124 GlobalValue &operator*() { return *I; }
125
126private:
127 bool isStaticInitGlobal(GlobalValue &GV);
128 void moveToNextStaticInitGlobal() {
129 ++I;
130 while (I != E && !isStaticInitGlobal(*I))
131 ++I;
132 if (I == E)
134 }
135
138};
139
140/// Create an iterator range over the GlobalValues that contribute to static
141/// initialization.
144}
145
147public:
148 CtorDtorRunner(JITDylib &JD) : JD(JD) {}
150 Error run();
151
152private:
153 using CtorDtorList = std::vector<SymbolStringPtr>;
154 using CtorDtorPriorityMap = std::map<unsigned, CtorDtorList>;
155
156 JITDylib &JD;
157 CtorDtorPriorityMap CtorDtorsByPriority;
158};
159
160/// Support class for static dtor execution. For hosted (in-process) JITs
161/// only!
162///
163/// If a __cxa_atexit function isn't found C++ programs that use static
164/// destructors will fail to link. However, we don't want to use the host
165/// process's __cxa_atexit, because it will schedule JIT'd destructors to run
166/// after the JIT has been torn down, which is no good. This class makes it easy
167/// to override __cxa_atexit (and the related __dso_handle).
168///
169/// To use, clients should manually call searchOverrides from their symbol
170/// resolver. This should generally be done after attempting symbol resolution
171/// inside the JIT, but before searching the host process's symbol table. When
172/// the client determines that destructors should be run (generally at JIT
173/// teardown or after a return from main), the runDestructors method should be
174/// called.
176public:
177 /// Run any destructors recorded by the overriden __cxa_atexit function
178 /// (CXAAtExitOverride).
179 void runDestructors();
180
181protected:
182 using DestructorPtr = void (*)(void *);
183 using CXXDestructorDataPair = std::pair<DestructorPtr, void *>;
184 using CXXDestructorDataPairList = std::vector<CXXDestructorDataPair>;
186 static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
187 void *DSOHandle);
188};
189
191public:
193};
194
195/// An interface for Itanium __cxa_atexit interposer implementations.
197public:
199 void (*F)(void *);
200 void *Ctx;
201 };
202
203 void registerAtExit(void (*F)(void *), void *Ctx, void *DSOHandle);
204 void runAtExits(void *DSOHandle);
205
206private:
207 std::mutex AtExitsMutex;
209};
210
211/// A utility class to expose symbols found via dlsym to the JIT.
212///
213/// If an instance of this class is attached to a JITDylib as a fallback
214/// definition generator, then any symbol found in the given DynamicLibrary that
215/// passes the 'Allow' predicate will be added to the JITDylib.
217public:
218 using SymbolPredicate = std::function<bool(const SymbolStringPtr &)>;
220
221 /// Create a DynamicLibrarySearchGenerator that searches for symbols in the
222 /// given sys::DynamicLibrary.
223 ///
224 /// If the Allow predicate is given then only symbols matching the predicate
225 /// will be searched for. If the predicate is not given then all symbols will
226 /// be searched for.
227 ///
228 /// If \p AddAbsoluteSymbols is provided, it is used to add the symbols to the
229 /// \c JITDylib; otherwise it uses JD.define(absoluteSymbols(...)).
231 sys::DynamicLibrary Dylib, char GlobalPrefix,
233 AddAbsoluteSymbolsFn AddAbsoluteSymbols = nullptr);
234
235 /// Permanently loads the library at the given path and, on success, returns
236 /// a DynamicLibrarySearchGenerator that will search it for symbol definitions
237 /// in the library. On failure returns the reason the library failed to load.
239 Load(const char *FileName, char GlobalPrefix,
241 AddAbsoluteSymbolsFn AddAbsoluteSymbols = nullptr);
242
243 /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
244 /// the current process.
246 GetForCurrentProcess(char GlobalPrefix,
248 AddAbsoluteSymbolsFn AddAbsoluteSymbols = nullptr) {
249 return Load(nullptr, GlobalPrefix, std::move(Allow),
250 std::move(AddAbsoluteSymbols));
251 }
252
254 JITDylibLookupFlags JDLookupFlags,
255 const SymbolLookupSet &Symbols) override;
256
257private:
259 SymbolPredicate Allow;
260 AddAbsoluteSymbolsFn AddAbsoluteSymbols;
261 char GlobalPrefix;
262};
263
264/// A utility class to expose symbols from a static library.
265///
266/// If an instance of this class is attached to a JITDylib as a fallback
267/// definition generator, then any symbol found in the archive will result in
268/// the containing object being added to the JITDylib.
270public:
271 // Interface builder function for objects loaded from this archive.
274 ExecutionSession &ES, MemoryBufferRef ObjBuffer)>;
275
276 /// Try to create a StaticLibraryDefinitionGenerator from the given path.
277 ///
278 /// This call will succeed if the file at the given path is a static library
279 /// or a MachO universal binary containing a static library that is compatible
280 /// with the ExecutionSession's triple. Otherwise it will return an error.
282 Load(ObjectLayer &L, const char *FileName,
283 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
284
285 /// Try to create a StaticLibrarySearchGenerator from the given memory buffer
286 /// and Archive object.
288 Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
289 std::unique_ptr<object::Archive> Archive,
290 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
291
292 /// Try to create a StaticLibrarySearchGenerator from the given memory buffer.
293 /// This call will succeed if the buffer contains a valid archive, otherwise
294 /// it will return an error.
295 ///
296 /// This call will succeed if the buffer contains a valid static library or a
297 /// MachO universal binary containing a static library that is compatible
298 /// with the ExecutionSession's triple. Otherwise it will return an error.
300 Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
301 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
302
303 /// Returns a list of filenames of dynamic libraries that this archive has
304 /// imported. This class does not load these libraries by itself. User is
305 /// responsible for making sure these libraries are avaliable to the JITDylib.
306 const std::set<std::string> &getImportedDynamicLibraries() const {
307 return ImportedDynamicLibraries;
308 }
309
311 JITDylibLookupFlags JDLookupFlags,
312 const SymbolLookupSet &Symbols) override;
313
314private:
316 std::unique_ptr<MemoryBuffer> ArchiveBuffer,
317 std::unique_ptr<object::Archive> Archive,
318 GetObjectFileInterface GetObjFileInterface,
319 Error &Err);
320 Error buildObjectFilesMap();
321
322 ObjectLayer &L;
323 GetObjectFileInterface GetObjFileInterface;
324 std::set<std::string> ImportedDynamicLibraries;
325 std::unique_ptr<MemoryBuffer> ArchiveBuffer;
326 std::unique_ptr<object::Archive> Archive;
328 BumpPtrAllocator ObjFileNameStorage;
329};
330
331/// A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT
332/// stubs.
333///
334/// If an instance of this class is attached to a JITDylib as a fallback
335/// definition generator, PLT stubs and dllimport __imp_ symbols will be
336/// generated for external symbols found outside the given jitdylib. Currently
337/// only supports x86_64 architecture.
339public:
340 /// Creates a DLLImportDefinitionGenerator instance.
341 static std::unique_ptr<DLLImportDefinitionGenerator>
343
345 JITDylibLookupFlags JDLookupFlags,
346 const SymbolLookupSet &Symbols) override;
347
348private:
350 : ES(ES), L(L) {}
351
352 static Expected<unsigned> getTargetPointerSize(const Triple &TT);
353 static Expected<llvm::endianness> getEndianness(const Triple &TT);
355 createStubsGraph(const SymbolMap &Resolved);
356
357 static StringRef getImpPrefix() { return "__imp_"; }
358
359 static StringRef getSectionName() { return "$__DLLIMPORT_STUBS"; }
360
363};
364
365} // end namespace orc
366} // end namespace llvm
367
368#endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
@ GlobalPrefix
Definition: AsmWriter.cpp:376
bool End
Definition: ELF_riscv.cpp:480
#define F(x, y, z)
Definition: MD5.cpp:55
Machine Check Debug Module
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
ConstantArray - Constant Array Declarations.
Definition: Constants.h:424
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
concat_iterator< GlobalValue, iterator, global_iterator, alias_iterator, ifunc_iterator > global_value_iterator
Definition: Module.h:779
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ObjectFormatType
Definition: Triple.h:297
LLVM Value Representation.
Definition: Value.h:74
A range adaptor for a pair of iterators.
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm....
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
Element operator*() const
Dereference iterator.
CtorDtorIterator & operator++()
Pre-increment iterator.
bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
void add(iterator_range< CtorDtorIterator > CtorDtors)
A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT stubs.
static std::unique_ptr< DLLImportDefinitionGenerator > Create(ExecutionSession &ES, ObjectLinkingLayer &L)
Creates a DLLImportDefinitionGenerator instance.
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition: Core.h:946
A utility class to expose symbols found via dlsym to the JIT.
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
unique_function< Error(JITDylib &, SymbolMap)> AddAbsoluteSymbolsFn
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > Load(const char *FileName, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Permanently loads the library at the given path and, on success, returns a DynamicLibrarySearchGenera...
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > GetForCurrentProcess(char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Creates a DynamicLibrarySearchGenerator that searches for symbols in the current process.
An ExecutionSession represents a running JIT program.
Definition: Core.h:1431
An interface for Itanium __cxa_atexit interposer implementations.
void registerAtExit(void(*F)(void *), void *Ctx, void *DSOHandle)
Represents a JIT'd dynamic library.
Definition: Core.h:989
Support class for static dtor execution.
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
CXXDestructorDataPairList DSOHandleOverride
std::pair< DestructorPtr, void * > CXXDestructorDataPair
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
Error enable(JITDylib &JD, MangleAndInterner &Mangler)
Wraps state for a lookup-in-progress.
Definition: Core.h:921
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Mangling.h:26
Interface for Layers that accept object files.
Definition: Layer.h:133
An ObjectLayer implementation built on JITLink.
This iterator provides a convenient way to iterate over GlobalValues that have initialization effects...
StaticInitGVIterator & operator++()
bool operator!=(const StaticInitGVIterator &O) const
bool operator==(const StaticInitGVIterator &O) const
A utility class to expose symbols from a static library.
const std::set< std::string > & getImportedDynamicLibraries() const
Returns a list of filenames of dynamic libraries that this archive has imported.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName, GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibraryDefinitionGenerator from the given path.
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Create(ObjectLayer &L, std::unique_ptr< MemoryBuffer > ArchiveBuffer, std::unique_ptr< object::Archive > Archive, GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibrarySearchGenerator from the given memory buffer and Archive object.
unique_function< Expected< MaterializationUnit::Interface >(ExecutionSession &ES, MemoryBufferRef ObjBuffer)> GetObjectFileInterface
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:183
Pointer to a pooled string representing a symbol name.
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
iterator_range< StaticInitGVIterator > getStaticInitGVs(Module &M)
Create an iterator range over the GlobalValues that contribute to static initialization.
iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:135
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:157
@ Resolved
Queried, materialization begun.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
@ Other
Any other memory.
Accessor for an element of the global_ctors/global_dtors array.
Element(unsigned Priority, Function *Func, Value *Data)