ExecutionUtils.h 11 KB

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