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/OrcError.h"
21 #include "llvm/ExecutionEngine/RuntimeDyld.h"
22 #include "llvm/Object/Archive.h"
23 #include "llvm/Support/DynamicLibrary.h"
24 #include <algorithm>
25 #include <cstdint>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 
30 namespace llvm {
31 
32 class ConstantArray;
33 class GlobalVariable;
34 class Function;
35 class Module;
36 class TargetMachine;
37 class Value;
38 
39 namespace orc {
40 
41 class ObjectLayer;
42 
43 /// Run a main function, returning the result.
44 ///
45 /// If the optional ProgramName argument is given then it will be inserted
46 /// before the strings in Args as the first argument to the called function.
47 ///
48 /// It is legal to have an empty argument list and no program name, however
49 /// many main functions will expect a name argument at least, and will fail
50 /// if none is provided.
51 int runAsMain(int (*Main)(int, char *[]), ArrayRef<std::string> Args,
52               Optional<StringRef> ProgramName = None);
53 
54 /// This iterator provides a convenient way to iterate over the elements
55 ///        of an llvm.global_ctors/llvm.global_dtors instance.
56 ///
57 ///   The easiest way to get hold of instances of this class is to use the
58 /// getConstructors/getDestructors functions.
59 class CtorDtorIterator {
60 public:
61   /// Accessor for an element of the global_ctors/global_dtors array.
62   ///
63   ///   This class provides a read-only view of the element with any casts on
64   /// the function stripped away.
65   struct Element {
66     Element(unsigned Priority, Function *Func, Value *Data)
67       : Priority(Priority), Func(Func), Data(Data) {}
68 
69     unsigned Priority;
70     Function *Func;
71     Value *Data;
72   };
73 
74   /// Construct an iterator instance. If End is true then this iterator
75   ///        acts as the end of the range, otherwise it is the beginning.
76   CtorDtorIterator(const GlobalVariable *GV, bool End);
77 
78   /// Test iterators for equality.
79   bool operator==(const CtorDtorIterator &Other) const;
80 
81   /// Test iterators for inequality.
82   bool operator!=(const CtorDtorIterator &Other) const;
83 
84   /// Pre-increment iterator.
85   CtorDtorIterator& operator++();
86 
87   /// Post-increment iterator.
88   CtorDtorIterator operator++(int);
89 
90   /// Dereference iterator. The resulting value provides a read-only view
91   ///        of this element of the global_ctors/global_dtors list.
92   Element operator*() const;
93 
94 private:
95   const ConstantArray *InitList;
96   unsigned I;
97 };
98 
99 /// Create an iterator range over the entries of the llvm.global_ctors
100 ///        array.
101 iterator_range<CtorDtorIterator> getConstructors(const Module &M);
102 
103 /// Create an iterator range over the entries of the llvm.global_ctors
104 ///        array.
105 iterator_range<CtorDtorIterator> getDestructors(const Module &M);
106 
107 /// Convenience class for recording constructor/destructor names for
108 ///        later execution.
109 template <typename JITLayerT>
110 class LegacyCtorDtorRunner {
111 public:
112   /// Construct a CtorDtorRunner for the given range using the given
113   ///        name mangling function.
114   LLVM_ATTRIBUTE_DEPRECATED(
115       LegacyCtorDtorRunner(std::vector<std::string> CtorDtorNames,
116                            VModuleKey K),
117       "ORCv1 utilities (utilities with the 'Legacy' prefix) are deprecated. "
118       "Please use the ORCv2 CtorDtorRunner utility instead");
119 
120   LegacyCtorDtorRunner(ORCv1DeprecationAcknowledgement,
121                        std::vector<std::string> CtorDtorNames, VModuleKey K)
122       : CtorDtorNames(std::move(CtorDtorNames)), K(K) {}
123 
124   /// Run the recorded constructors/destructors through the given JIT
125   ///        layer.
126   Error runViaLayer(JITLayerT &JITLayer) const {
127     using CtorDtorTy = void (*)();
128 
129     for (const auto &CtorDtorName : CtorDtorNames) {
130       if (auto CtorDtorSym = JITLayer.findSymbolIn(K, CtorDtorName, false)) {
131         if (auto AddrOrErr = CtorDtorSym.getAddress()) {
132           CtorDtorTy CtorDtor =
133             reinterpret_cast<CtorDtorTy>(static_cast<uintptr_t>(*AddrOrErr));
134           CtorDtor();
135         } else
136           return AddrOrErr.takeError();
137       } else {
138         if (auto Err = CtorDtorSym.takeError())
139           return Err;
140         else
141           return make_error<JITSymbolNotFound>(CtorDtorName);
142       }
143     }
144     return Error::success();
145   }
146 
147 private:
148   std::vector<std::string> CtorDtorNames;
149   orc::VModuleKey K;
150 };
151 
152 template <typename JITLayerT>
153 LegacyCtorDtorRunner<JITLayerT>::LegacyCtorDtorRunner(
154     std::vector<std::string> CtorDtorNames, VModuleKey K)
155     : CtorDtorNames(std::move(CtorDtorNames)), K(K) {}
156 
157 class CtorDtorRunner {
158 public:
159   CtorDtorRunner(JITDylib &JD) : JD(JD) {}
160   void add(iterator_range<CtorDtorIterator> CtorDtors);
161   Error run();
162 
163 private:
164   using CtorDtorList = std::vector<SymbolStringPtr>;
165   using CtorDtorPriorityMap = std::map<unsigned, CtorDtorList>;
166 
167   JITDylib &JD;
168   CtorDtorPriorityMap CtorDtorsByPriority;
169 };
170 
171 /// Support class for static dtor execution. For hosted (in-process) JITs
172 ///        only!
173 ///
174 ///   If a __cxa_atexit function isn't found C++ programs that use static
175 /// destructors will fail to link. However, we don't want to use the host
176 /// process's __cxa_atexit, because it will schedule JIT'd destructors to run
177 /// after the JIT has been torn down, which is no good. This class makes it easy
178 /// to override __cxa_atexit (and the related __dso_handle).
179 ///
180 ///   To use, clients should manually call searchOverrides from their symbol
181 /// resolver. This should generally be done after attempting symbol resolution
182 /// inside the JIT, but before searching the host process's symbol table. When
183 /// the client determines that destructors should be run (generally at JIT
184 /// teardown or after a return from main), the runDestructors method should be
185 /// called.
186 class LocalCXXRuntimeOverridesBase {
187 public:
188   /// Run any destructors recorded by the overriden __cxa_atexit function
189   /// (CXAAtExitOverride).
190   void runDestructors();
191 
192 protected:
193   template <typename PtrTy> JITTargetAddress toTargetAddress(PtrTy *P) {
194     return static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(P));
195   }
196 
197   using DestructorPtr = void (*)(void *);
198   using CXXDestructorDataPair = std::pair<DestructorPtr, void *>;
199   using CXXDestructorDataPairList = std::vector<CXXDestructorDataPair>;
200   CXXDestructorDataPairList DSOHandleOverride;
201   static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
202                                void *DSOHandle);
203 };
204 
205 class LegacyLocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
206 public:
207   /// Create a runtime-overrides class.
208   template <typename MangleFtorT>
209   LLVM_ATTRIBUTE_DEPRECATED(
210       LegacyLocalCXXRuntimeOverrides(const MangleFtorT &Mangle),
211       "ORCv1 utilities (utilities with the 'Legacy' prefix) are deprecated. "
212       "Please use the ORCv2 LocalCXXRuntimeOverrides utility instead");
213 
214   template <typename MangleFtorT>
215   LegacyLocalCXXRuntimeOverrides(ORCv1DeprecationAcknowledgement,
216                                  const MangleFtorT &Mangle) {
217     addOverride(Mangle("__dso_handle"), toTargetAddress(&DSOHandleOverride));
218     addOverride(Mangle("__cxa_atexit"), toTargetAddress(&CXAAtExitOverride));
219   }
220 
221   /// Search overrided symbols.
222   JITEvaluatedSymbol searchOverrides(const std::string &Name) {
223     auto I = CXXRuntimeOverrides.find(Name);
224     if (I != CXXRuntimeOverrides.end())
225       return JITEvaluatedSymbol(I->second, JITSymbolFlags::Exported);
226     return nullptr;
227   }
228 
229 private:
230   void addOverride(const std::string &Name, JITTargetAddress Addr) {
231     CXXRuntimeOverrides.insert(std::make_pair(Name, Addr));
232   }
233 
234   StringMap<JITTargetAddress> CXXRuntimeOverrides;
235 };
236 
237 template <typename MangleFtorT>
238 LegacyLocalCXXRuntimeOverrides::LegacyLocalCXXRuntimeOverrides(
239     const MangleFtorT &Mangle) {
240   addOverride(Mangle("__dso_handle"), toTargetAddress(&DSOHandleOverride));
241   addOverride(Mangle("__cxa_atexit"), toTargetAddress(&CXAAtExitOverride));
242 }
243 
244 class LocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
245 public:
246   Error enable(JITDylib &JD, MangleAndInterner &Mangler);
247 };
248 
249 /// A utility class to expose symbols found via dlsym to the JIT.
250 ///
251 /// If an instance of this class is attached to a JITDylib as a fallback
252 /// definition generator, then any symbol found in the given DynamicLibrary that
253 /// passes the 'Allow' predicate will be added to the JITDylib.
254 class DynamicLibrarySearchGenerator : public JITDylib::DefinitionGenerator {
255 public:
256   using SymbolPredicate = std::function<bool(const SymbolStringPtr &)>;
257 
258   /// Create a DynamicLibrarySearchGenerator that searches for symbols in the
259   /// given sys::DynamicLibrary.
260   ///
261   /// If the Allow predicate is given then only symbols matching the predicate
262   /// will be searched for. If the predicate is not given then all symbols will
263   /// be searched for.
264   DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix,
265                                 SymbolPredicate Allow = SymbolPredicate());
266 
267   /// Permanently loads the library at the given path and, on success, returns
268   /// a DynamicLibrarySearchGenerator that will search it for symbol definitions
269   /// in the library. On failure returns the reason the library failed to load.
270   static Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
271   Load(const char *FileName, char GlobalPrefix,
272        SymbolPredicate Allow = SymbolPredicate());
273 
274   /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
275   /// the current process.
276   static Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
277   GetForCurrentProcess(char GlobalPrefix,
278                        SymbolPredicate Allow = SymbolPredicate()) {
279     return Load(nullptr, GlobalPrefix, std::move(Allow));
280   }
281 
282   Error tryToGenerate(LookupKind K, JITDylib &JD,
283                       JITDylibLookupFlags JDLookupFlags,
284                       const SymbolLookupSet &Symbols) override;
285 
286 private:
287   sys::DynamicLibrary Dylib;
288   SymbolPredicate Allow;
289   char GlobalPrefix;
290 };
291 
292 /// A utility class to expose symbols from a static library.
293 ///
294 /// If an instance of this class is attached to a JITDylib as a fallback
295 /// definition generator, then any symbol found in the archive will result in
296 /// the containing object being added to the JITDylib.
297 class StaticLibraryDefinitionGenerator : public JITDylib::DefinitionGenerator {
298 public:
299   /// Try to create a StaticLibraryDefinitionGenerator from the given path.
300   ///
301   /// This call will succeed if the file at the given path is a static library
302   /// is a valid archive, otherwise it will return an error.
303   static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
304   Load(ObjectLayer &L, const char *FileName);
305 
306   /// Try to create a StaticLibrarySearchGenerator from the given memory buffer.
307   /// This call will succeed if the buffer contains a valid archive, otherwise
308   /// it will return an error.
309   static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
310   Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer);
311 
312   Error tryToGenerate(LookupKind K, JITDylib &JD,
313                       JITDylibLookupFlags JDLookupFlags,
314                       const SymbolLookupSet &Symbols) override;
315 
316 private:
317   StaticLibraryDefinitionGenerator(ObjectLayer &L,
318                                    std::unique_ptr<MemoryBuffer> ArchiveBuffer,
319                                    Error &Err);
320 
321   ObjectLayer &L;
322   std::unique_ptr<MemoryBuffer> ArchiveBuffer;
323   std::unique_ptr<object::Archive> Archive;
324 };
325 
326 } // end namespace orc
327 } // end namespace llvm
328 
329 #endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
330