LLVM  10.0.0
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 
16 #include "llvm/ADT/StringMap.h"
22 #include "llvm/Object/Archive.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.
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 {
67  : Priority(Priority), Func(Func), Data(Data) {}
68 
69  unsigned Priority;
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.
86 
87  /// Post-increment iterator.
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.
102 
103 /// Create an iterator range over the entries of the llvm.global_ctors
104 /// array.
106 
107 /// Convenience class for recording constructor/destructor names for
108 /// later execution.
109 template <typename JITLayerT>
111 public:
112  /// Construct a CtorDtorRunner for the given range using the given
113  /// name mangling function.
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 
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>
154  std::vector<std::string> CtorDtorNames, VModuleKey K)
155  : CtorDtorNames(std::move(CtorDtorNames)), K(K) {}
156 
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.
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>;
201  static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
202  void *DSOHandle);
203 };
204 
206 public:
207  /// Create a runtime-overrides class.
208  template <typename MangleFtorT>
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>
216  const MangleFtorT &Mangle) {
217  addOverride(Mangle("__dso_handle"), toTargetAddress(&DSOHandleOverride));
218  addOverride(Mangle("__cxa_atexit"), toTargetAddress(&CXAAtExitOverride));
219  }
220 
221  /// Search overrided symbols.
223  auto I = CXXRuntimeOverrides.find(Name);
224  if (I != CXXRuntimeOverrides.end())
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>
239  const MangleFtorT &Mangle) {
240  addOverride(Mangle("__dso_handle"), toTargetAddress(&DSOHandleOverride));
241  addOverride(Mangle("__cxa_atexit"), toTargetAddress(&CXAAtExitOverride));
242 }
243 
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.
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.
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.
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.
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.
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.
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.
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:
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
JITTargetAddress toTargetAddress(PtrTy *P)
Accessor for an element of the global_ctors/global_dtors array.
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:89
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
JITEvaluatedSymbol searchOverrides(const std::string &Name)
Search overrided symbols.
Convenience class for recording constructor/destructor names for later execution. ...
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
Element(unsigned Priority, Function *Func, Value *Data)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
CtorDtorIterator & operator++()
Pre-increment iterator.
Definition: BitVector.h:937
A utility class to expose symbols from a static library.
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Core.h:1310
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
CXXDestructorDataPairList DSOHandleOverride
iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
CtorDtorIterator(const GlobalVariable *GV, bool End)
Construct an iterator instance.
ORCv1DeprecationAcknowledgement
uint64_t JITTargetAddress
Represents an address in the target process&#39;s address space.
Definition: JITSymbol.h:41
#define P(N)
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Support class for static dtor execution.
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition: Core.h:781
std::pair< DestructorPtr, void * > CXXDestructorDataPair
#define LLVM_ATTRIBUTE_DEPRECATED(decl, message)
Definition: Compiler.h:310
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
A utility class to expose symbols found via dlsym to the JIT.
static uint64_t add(uint64_t LeftOp, uint64_t RightOp)
Definition: FileCheck.cpp:208
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm.global_dtors instance.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:115
LegacyCtorDtorRunner(ORCv1DeprecationAcknowledgement, std::vector< std::string > CtorDtorNames, VModuleKey K)
A range adaptor for a pair of iterators.
ConstantArray - Constant Array Declarations.
Definition: Constants.h:413
Represents a symbol that has been evaluated to an address already.
Definition: JITSymbol.h:208
uint8_t uint64_t VModuleKey
VModuleKey provides a unique identifier (allocated and managed by ExecutionSessions) for a module add...
Definition: Core.h:42
iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
#define I(x, y, z)
Definition: MD5.cpp:58
int runAsMain(int(*Main)(int, char *[]), ArrayRef< std::string > Args, Optional< StringRef > ProgramName=None)
Run a main function, returning the result.
LLVM Value Representation.
Definition: Value.h:74
Element operator*() const
Dereference iterator.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
Interface for Layers that accept object files.
Definition: Layer.h:126
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
LegacyLocalCXXRuntimeOverrides(ORCv1DeprecationAcknowledgement, const MangleFtorT &Mangle)
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > GetForCurrentProcess(char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Creates a DynamicLibrarySearchGenerator that searches for symbols in the current process.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:67
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Error runViaLayer(JITLayerT &JITLayer) const
Run the recorded constructors/destructors through the given JIT layer.
A symbol table that supports asynchoronous symbol queries.
Definition: Core.h:774