1 //===- ExecutionUtils.h - Utilities for executing code in Orc ---*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // Contains utilities for executing code in Orc.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
14 #define LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/iterator_range.h"
18 #include "llvm/ExecutionEngine/JITSymbol.h"
19 #include "llvm/ExecutionEngine/Orc/Core.h"
20 #include "llvm/ExecutionEngine/Orc/OrcError.h"
21 #include "llvm/ExecutionEngine/RuntimeDyld.h"
22 #include "llvm/Support/DynamicLibrary.h"
40 /// This iterator provides a convenient way to iterate over the elements
41 /// of an llvm.global_ctors/llvm.global_dtors instance.
43 /// The easiest way to get hold of instances of this class is to use the
44 /// getConstructors/getDestructors functions.
45 class CtorDtorIterator {
47 /// Accessor for an element of the global_ctors/global_dtors array.
49 /// This class provides a read-only view of the element with any casts on
50 /// the function stripped away.
52 Element(unsigned Priority, Function *Func, Value *Data)
53 : Priority(Priority), Func(Func), Data(Data) {}
60 /// Construct an iterator instance. If End is true then this iterator
61 /// acts as the end of the range, otherwise it is the beginning.
62 CtorDtorIterator(const GlobalVariable *GV, bool End);
64 /// Test iterators for equality.
65 bool operator==(const CtorDtorIterator &Other) const;
67 /// Test iterators for inequality.
68 bool operator!=(const CtorDtorIterator &Other) const;
70 /// Pre-increment iterator.
71 CtorDtorIterator& operator++();
73 /// Post-increment iterator.
74 CtorDtorIterator operator++(int);
76 /// Dereference iterator. The resulting value provides a read-only view
77 /// of this element of the global_ctors/global_dtors list.
78 Element operator*() const;
81 const ConstantArray *InitList;
85 /// Create an iterator range over the entries of the llvm.global_ctors
87 iterator_range<CtorDtorIterator> getConstructors(const Module &M);
89 /// Create an iterator range over the entries of the llvm.global_ctors
91 iterator_range<CtorDtorIterator> getDestructors(const Module &M);
93 /// Convenience class for recording constructor/destructor names for
95 template <typename JITLayerT>
96 class LegacyCtorDtorRunner {
98 /// Construct a CtorDtorRunner for the given range using the given
99 /// name mangling function.
100 LLVM_ATTRIBUTE_DEPRECATED(
101 LegacyCtorDtorRunner(std::vector<std::string> CtorDtorNames,
103 "ORCv1 utilities (utilities with the 'Legacy' prefix) are deprecated. "
104 "Please use the ORCv2 CtorDtorRunner utility instead");
106 LegacyCtorDtorRunner(ORCv1DeprecationAcknowledgement,
107 std::vector<std::string> CtorDtorNames, VModuleKey K)
108 : CtorDtorNames(std::move(CtorDtorNames)), K(K) {}
110 /// Run the recorded constructors/destructors through the given JIT
112 Error runViaLayer(JITLayerT &JITLayer) const {
113 using CtorDtorTy = void (*)();
115 for (const auto &CtorDtorName : CtorDtorNames) {
116 if (auto CtorDtorSym = JITLayer.findSymbolIn(K, CtorDtorName, false)) {
117 if (auto AddrOrErr = CtorDtorSym.getAddress()) {
118 CtorDtorTy CtorDtor =
119 reinterpret_cast<CtorDtorTy>(static_cast<uintptr_t>(*AddrOrErr));
122 return AddrOrErr.takeError();
124 if (auto Err = CtorDtorSym.takeError())
127 return make_error<JITSymbolNotFound>(CtorDtorName);
130 return Error::success();
134 std::vector<std::string> CtorDtorNames;
138 template <typename JITLayerT>
139 LegacyCtorDtorRunner<JITLayerT>::LegacyCtorDtorRunner(
140 std::vector<std::string> CtorDtorNames, VModuleKey K)
141 : CtorDtorNames(std::move(CtorDtorNames)), K(K) {}
143 class CtorDtorRunner {
145 CtorDtorRunner(JITDylib &JD) : JD(JD) {}
146 void add(iterator_range<CtorDtorIterator> CtorDtors);
150 using CtorDtorList = std::vector<SymbolStringPtr>;
151 using CtorDtorPriorityMap = std::map<unsigned, CtorDtorList>;
154 CtorDtorPriorityMap CtorDtorsByPriority;
157 /// Support class for static dtor execution. For hosted (in-process) JITs
160 /// If a __cxa_atexit function isn't found C++ programs that use static
161 /// destructors will fail to link. However, we don't want to use the host
162 /// process's __cxa_atexit, because it will schedule JIT'd destructors to run
163 /// after the JIT has been torn down, which is no good. This class makes it easy
164 /// to override __cxa_atexit (and the related __dso_handle).
166 /// To use, clients should manually call searchOverrides from their symbol
167 /// resolver. This should generally be done after attempting symbol resolution
168 /// inside the JIT, but before searching the host process's symbol table. When
169 /// the client determines that destructors should be run (generally at JIT
170 /// teardown or after a return from main), the runDestructors method should be
172 class LocalCXXRuntimeOverridesBase {
174 /// Run any destructors recorded by the overriden __cxa_atexit function
175 /// (CXAAtExitOverride).
176 void runDestructors();
179 template <typename PtrTy> JITTargetAddress toTargetAddress(PtrTy *P) {
180 return static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(P));
183 using DestructorPtr = void (*)(void *);
184 using CXXDestructorDataPair = std::pair<DestructorPtr, void *>;
185 using CXXDestructorDataPairList = std::vector<CXXDestructorDataPair>;
186 CXXDestructorDataPairList DSOHandleOverride;
187 static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
191 class LegacyLocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
193 /// Create a runtime-overrides class.
194 template <typename MangleFtorT>
195 LLVM_ATTRIBUTE_DEPRECATED(
196 LegacyLocalCXXRuntimeOverrides(const MangleFtorT &Mangle),
197 "ORCv1 utilities (utilities with the 'Legacy' prefix) are deprecated. "
198 "Please use the ORCv2 LocalCXXRuntimeOverrides utility instead");
200 template <typename MangleFtorT>
201 LegacyLocalCXXRuntimeOverrides(ORCv1DeprecationAcknowledgement,
202 const MangleFtorT &Mangle) {
203 addOverride(Mangle("__dso_handle"), toTargetAddress(&DSOHandleOverride));
204 addOverride(Mangle("__cxa_atexit"), toTargetAddress(&CXAAtExitOverride));
207 /// Search overrided symbols.
208 JITEvaluatedSymbol searchOverrides(const std::string &Name) {
209 auto I = CXXRuntimeOverrides.find(Name);
210 if (I != CXXRuntimeOverrides.end())
211 return JITEvaluatedSymbol(I->second, JITSymbolFlags::Exported);
216 void addOverride(const std::string &Name, JITTargetAddress Addr) {
217 CXXRuntimeOverrides.insert(std::make_pair(Name, Addr));
220 StringMap<JITTargetAddress> CXXRuntimeOverrides;
223 template <typename MangleFtorT>
224 LegacyLocalCXXRuntimeOverrides::LegacyLocalCXXRuntimeOverrides(
225 const MangleFtorT &Mangle) {
226 addOverride(Mangle("__dso_handle"), toTargetAddress(&DSOHandleOverride));
227 addOverride(Mangle("__cxa_atexit"), toTargetAddress(&CXAAtExitOverride));
230 class LocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
232 Error enable(JITDylib &JD, MangleAndInterner &Mangler);
235 /// A utility class to expose symbols found via dlsym to the JIT.
237 /// If an instance of this class is attached to a JITDylib as a fallback
238 /// definition generator, then any symbol found in the given DynamicLibrary that
239 /// passes the 'Allow' predicate will be added to the JITDylib.
240 class DynamicLibrarySearchGenerator {
242 using SymbolPredicate = std::function<bool(SymbolStringPtr)>;
244 /// Create a DynamicLibrarySearchGenerator that searches for symbols in the
245 /// given sys::DynamicLibrary.
247 /// If the Allow predicate is given then only symbols matching the predicate
248 /// will be searched for. If the predicate is not given then all symbols will
250 DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix,
251 SymbolPredicate Allow = SymbolPredicate());
253 /// Permanently loads the library at the given path and, on success, returns
254 /// a DynamicLibrarySearchGenerator that will search it for symbol definitions
255 /// in the library. On failure returns the reason the library failed to load.
256 static Expected<DynamicLibrarySearchGenerator>
257 Load(const char *FileName, char GlobalPrefix,
258 SymbolPredicate Allow = SymbolPredicate());
260 /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
261 /// the current process.
262 static Expected<DynamicLibrarySearchGenerator>
263 GetForCurrentProcess(char GlobalPrefix,
264 SymbolPredicate Allow = SymbolPredicate()) {
265 return Load(nullptr, GlobalPrefix, std::move(Allow));
268 Expected<SymbolNameSet> operator()(JITDylib &JD, const SymbolNameSet &Names);
271 sys::DynamicLibrary Dylib;
272 SymbolPredicate Allow;
276 } // end namespace orc
277 } // end namespace llvm
279 #endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H