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
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/Mangling.h"
21 #include "llvm/ExecutionEngine/Orc/OrcError.h"
22 #include "llvm/ExecutionEngine/RuntimeDyld.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Support/DynamicLibrary.h"
25 #include <algorithm>
26 #include <cstdint>
27 #include <string>
28 #include <utility>
29 #include <vector>
30
31 namespace llvm {
32
33 class ConstantArray;
34 class GlobalVariable;
35 class Function;
36 class Module;
37 class TargetMachine;
38 class Value;
39
40 namespace orc {
41
42 class ObjectLayer;
43
44 /// This iterator provides a convenient way to iterate over the elements
45 /// of an llvm.global_ctors/llvm.global_dtors instance.
46 ///
47 /// The easiest way to get hold of instances of this class is to use the
48 /// getConstructors/getDestructors functions.
49 class CtorDtorIterator {
50 public:
51 /// Accessor for an element of the global_ctors/global_dtors array.
52 ///
53 /// This class provides a read-only view of the element with any casts on
54 /// the function stripped away.
55 struct Element {
ElementElement56 Element(unsigned Priority, Function *Func, Value *Data)
57 : Priority(Priority), Func(Func), Data(Data) {}
58
59 unsigned Priority;
60 Function *Func;
61 Value *Data;
62 };
63
64 /// Construct an iterator instance. If End is true then this iterator
65 /// acts as the end of the range, otherwise it is the beginning.
66 CtorDtorIterator(const GlobalVariable *GV, bool End);
67
68 /// Test iterators for equality.
69 bool operator==(const CtorDtorIterator &Other) const;
70
71 /// Test iterators for inequality.
72 bool operator!=(const CtorDtorIterator &Other) const;
73
74 /// Pre-increment iterator.
75 CtorDtorIterator& operator++();
76
77 /// Post-increment iterator.
78 CtorDtorIterator operator++(int);
79
80 /// Dereference iterator. The resulting value provides a read-only view
81 /// of this element of the global_ctors/global_dtors list.
82 Element operator*() const;
83
84 private:
85 const ConstantArray *InitList;
86 unsigned I;
87 };
88
89 /// Create an iterator range over the entries of the llvm.global_ctors
90 /// array.
91 iterator_range<CtorDtorIterator> getConstructors(const Module &M);
92
93 /// Create an iterator range over the entries of the llvm.global_ctors
94 /// array.
95 iterator_range<CtorDtorIterator> getDestructors(const Module &M);
96
97 /// This iterator provides a convenient way to iterate over GlobalValues that
98 /// have initialization effects.
99 class StaticInitGVIterator {
100 public:
101 StaticInitGVIterator() = default;
102
StaticInitGVIterator(Module & M)103 StaticInitGVIterator(Module &M)
104 : I(M.global_values().begin()), E(M.global_values().end()),
105 ObjFmt(Triple(M.getTargetTriple()).getObjectFormat()) {
106 if (I != E) {
107 if (!isStaticInitGlobal(*I))
108 moveToNextStaticInitGlobal();
109 } else
110 I = E = Module::global_value_iterator();
111 }
112
113 bool operator==(const StaticInitGVIterator &O) const { return I == O.I; }
114 bool operator!=(const StaticInitGVIterator &O) const { return I != O.I; }
115
116 StaticInitGVIterator &operator++() {
117 assert(I != E && "Increment past end of range");
118 moveToNextStaticInitGlobal();
119 return *this;
120 }
121
122 GlobalValue &operator*() { return *I; }
123
124 private:
125 bool isStaticInitGlobal(GlobalValue &GV);
moveToNextStaticInitGlobal()126 void moveToNextStaticInitGlobal() {
127 ++I;
128 while (I != E && !isStaticInitGlobal(*I))
129 ++I;
130 if (I == E)
131 I = E = Module::global_value_iterator();
132 }
133
134 Module::global_value_iterator I, E;
135 Triple::ObjectFormatType ObjFmt;
136 };
137
138 /// Create an iterator range over the GlobalValues that contribute to static
139 /// initialization.
getStaticInitGVs(Module & M)140 inline iterator_range<StaticInitGVIterator> getStaticInitGVs(Module &M) {
141 return make_range(StaticInitGVIterator(M), StaticInitGVIterator());
142 }
143
144 class CtorDtorRunner {
145 public:
CtorDtorRunner(JITDylib & JD)146 CtorDtorRunner(JITDylib &JD) : JD(JD) {}
147 void add(iterator_range<CtorDtorIterator> CtorDtors);
148 Error run();
149
150 private:
151 using CtorDtorList = std::vector<SymbolStringPtr>;
152 using CtorDtorPriorityMap = std::map<unsigned, CtorDtorList>;
153
154 JITDylib &JD;
155 CtorDtorPriorityMap CtorDtorsByPriority;
156 };
157
158 /// Support class for static dtor execution. For hosted (in-process) JITs
159 /// only!
160 ///
161 /// If a __cxa_atexit function isn't found C++ programs that use static
162 /// destructors will fail to link. However, we don't want to use the host
163 /// process's __cxa_atexit, because it will schedule JIT'd destructors to run
164 /// after the JIT has been torn down, which is no good. This class makes it easy
165 /// to override __cxa_atexit (and the related __dso_handle).
166 ///
167 /// To use, clients should manually call searchOverrides from their symbol
168 /// resolver. This should generally be done after attempting symbol resolution
169 /// inside the JIT, but before searching the host process's symbol table. When
170 /// the client determines that destructors should be run (generally at JIT
171 /// teardown or after a return from main), the runDestructors method should be
172 /// called.
173 class LocalCXXRuntimeOverridesBase {
174 public:
175 /// Run any destructors recorded by the overriden __cxa_atexit function
176 /// (CXAAtExitOverride).
177 void runDestructors();
178
179 protected:
toTargetAddress(PtrTy * P)180 template <typename PtrTy> JITTargetAddress toTargetAddress(PtrTy *P) {
181 return static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(P));
182 }
183
184 using DestructorPtr = void (*)(void *);
185 using CXXDestructorDataPair = std::pair<DestructorPtr, void *>;
186 using CXXDestructorDataPairList = std::vector<CXXDestructorDataPair>;
187 CXXDestructorDataPairList DSOHandleOverride;
188 static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
189 void *DSOHandle);
190 };
191
192 class LocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
193 public:
194 Error enable(JITDylib &JD, MangleAndInterner &Mangler);
195 };
196
197 /// An interface for Itanium __cxa_atexit interposer implementations.
198 class ItaniumCXAAtExitSupport {
199 public:
200 struct AtExitRecord {
201 void (*F)(void *);
202 void *Ctx;
203 };
204
205 void registerAtExit(void (*F)(void *), void *Ctx, void *DSOHandle);
206 void runAtExits(void *DSOHandle);
207
208 private:
209 std::mutex AtExitsMutex;
210 DenseMap<void *, std::vector<AtExitRecord>> AtExitRecords;
211 };
212
213 /// A utility class to expose symbols found via dlsym to the JIT.
214 ///
215 /// If an instance of this class is attached to a JITDylib as a fallback
216 /// definition generator, then any symbol found in the given DynamicLibrary that
217 /// passes the 'Allow' predicate will be added to the JITDylib.
218 class DynamicLibrarySearchGenerator : public DefinitionGenerator {
219 public:
220 using SymbolPredicate = std::function<bool(const SymbolStringPtr &)>;
221
222 /// Create a DynamicLibrarySearchGenerator that searches for symbols in the
223 /// given sys::DynamicLibrary.
224 ///
225 /// If the Allow predicate is given then only symbols matching the predicate
226 /// will be searched for. If the predicate is not given then all symbols will
227 /// be searched for.
228 DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix,
229 SymbolPredicate Allow = SymbolPredicate());
230
231 /// Permanently loads the library at the given path and, on success, returns
232 /// a DynamicLibrarySearchGenerator that will search it for symbol definitions
233 /// in the library. On failure returns the reason the library failed to load.
234 static Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
235 Load(const char *FileName, char GlobalPrefix,
236 SymbolPredicate Allow = SymbolPredicate());
237
238 /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
239 /// the current process.
240 static Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
241 GetForCurrentProcess(char GlobalPrefix,
242 SymbolPredicate Allow = SymbolPredicate()) {
243 return Load(nullptr, GlobalPrefix, std::move(Allow));
244 }
245
246 Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
247 JITDylibLookupFlags JDLookupFlags,
248 const SymbolLookupSet &Symbols) override;
249
250 private:
251 sys::DynamicLibrary Dylib;
252 SymbolPredicate Allow;
253 char GlobalPrefix;
254 };
255
256 /// A utility class to expose symbols from a static library.
257 ///
258 /// If an instance of this class is attached to a JITDylib as a fallback
259 /// definition generator, then any symbol found in the archive will result in
260 /// the containing object being added to the JITDylib.
261 class StaticLibraryDefinitionGenerator : public DefinitionGenerator {
262 public:
263 /// Try to create a StaticLibraryDefinitionGenerator from the given path.
264 ///
265 /// This call will succeed if the file at the given path is a static library
266 /// is a valid archive, otherwise it will return an error.
267 static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
268 Load(ObjectLayer &L, const char *FileName);
269
270 /// Try to create a StaticLibraryDefinitionGenerator from the given path.
271 ///
272 /// This call will succeed if the file at the given path is a static library
273 /// or a MachO universal binary containing a static library that is compatible
274 /// with the given triple. Otherwise it will return an error.
275 static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
276 Load(ObjectLayer &L, const char *FileName, const Triple &TT);
277
278 /// Try to create a StaticLibrarySearchGenerator from the given memory buffer.
279 /// This call will succeed if the buffer contains a valid archive, otherwise
280 /// it will return an error.
281 static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
282 Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer);
283
284 Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
285 JITDylibLookupFlags JDLookupFlags,
286 const SymbolLookupSet &Symbols) override;
287
288 private:
289 StaticLibraryDefinitionGenerator(ObjectLayer &L,
290 std::unique_ptr<MemoryBuffer> ArchiveBuffer,
291 Error &Err);
292
293 ObjectLayer &L;
294 std::unique_ptr<MemoryBuffer> ArchiveBuffer;
295 std::unique_ptr<object::Archive> Archive;
296 };
297
298 } // end namespace orc
299 } // end namespace llvm
300
301 #endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
302