Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:53

0001 //===- ExecutionUtils.h - Utilities for executing code in Orc ---*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // Contains utilities for executing code in Orc.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
0014 #define LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
0015 
0016 #include "llvm/ADT/iterator_range.h"
0017 #include "llvm/ExecutionEngine/JITSymbol.h"
0018 #include "llvm/ExecutionEngine/Orc/Core.h"
0019 #include "llvm/ExecutionEngine/Orc/Mangling.h"
0020 #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
0021 #include "llvm/ExecutionEngine/Orc/Shared/OrcError.h"
0022 #include "llvm/ExecutionEngine/RuntimeDyld.h"
0023 #include "llvm/Object/Archive.h"
0024 #include "llvm/Support/DynamicLibrary.h"
0025 #include <algorithm>
0026 #include <cstdint>
0027 #include <utility>
0028 #include <vector>
0029 
0030 namespace llvm {
0031 
0032 class ConstantArray;
0033 class GlobalVariable;
0034 class Function;
0035 class Module;
0036 class Value;
0037 
0038 namespace object {
0039 class MachOUniversalBinary;
0040 }
0041 
0042 namespace orc {
0043 
0044 class ObjectLayer;
0045 
0046 /// This iterator provides a convenient way to iterate over the elements
0047 ///        of an llvm.global_ctors/llvm.global_dtors instance.
0048 ///
0049 ///   The easiest way to get hold of instances of this class is to use the
0050 /// getConstructors/getDestructors functions.
0051 class CtorDtorIterator {
0052 public:
0053   /// Accessor for an element of the global_ctors/global_dtors array.
0054   ///
0055   ///   This class provides a read-only view of the element with any casts on
0056   /// the function stripped away.
0057   struct Element {
0058     Element(unsigned Priority, Function *Func, Value *Data)
0059       : Priority(Priority), Func(Func), Data(Data) {}
0060 
0061     unsigned Priority;
0062     Function *Func;
0063     Value *Data;
0064   };
0065 
0066   /// Construct an iterator instance. If End is true then this iterator
0067   ///        acts as the end of the range, otherwise it is the beginning.
0068   CtorDtorIterator(const GlobalVariable *GV, bool End);
0069 
0070   /// Test iterators for equality.
0071   bool operator==(const CtorDtorIterator &Other) const;
0072 
0073   /// Test iterators for inequality.
0074   bool operator!=(const CtorDtorIterator &Other) const;
0075 
0076   /// Pre-increment iterator.
0077   CtorDtorIterator& operator++();
0078 
0079   /// Post-increment iterator.
0080   CtorDtorIterator operator++(int);
0081 
0082   /// Dereference iterator. The resulting value provides a read-only view
0083   ///        of this element of the global_ctors/global_dtors list.
0084   Element operator*() const;
0085 
0086 private:
0087   const ConstantArray *InitList;
0088   unsigned I;
0089 };
0090 
0091 /// Create an iterator range over the entries of the llvm.global_ctors
0092 ///        array.
0093 iterator_range<CtorDtorIterator> getConstructors(const Module &M);
0094 
0095 /// Create an iterator range over the entries of the llvm.global_ctors
0096 ///        array.
0097 iterator_range<CtorDtorIterator> getDestructors(const Module &M);
0098 
0099 /// This iterator provides a convenient way to iterate over GlobalValues that
0100 /// have initialization effects.
0101 class StaticInitGVIterator {
0102 public:
0103   StaticInitGVIterator() = default;
0104 
0105   StaticInitGVIterator(Module &M)
0106       : I(M.global_values().begin()), E(M.global_values().end()),
0107         ObjFmt(Triple(M.getTargetTriple()).getObjectFormat()) {
0108     if (I != E) {
0109       if (!isStaticInitGlobal(*I))
0110         moveToNextStaticInitGlobal();
0111     } else
0112       I = E = Module::global_value_iterator();
0113   }
0114 
0115   bool operator==(const StaticInitGVIterator &O) const { return I == O.I; }
0116   bool operator!=(const StaticInitGVIterator &O) const { return I != O.I; }
0117 
0118   StaticInitGVIterator &operator++() {
0119     assert(I != E && "Increment past end of range");
0120     moveToNextStaticInitGlobal();
0121     return *this;
0122   }
0123 
0124   GlobalValue &operator*() { return *I; }
0125 
0126 private:
0127   bool isStaticInitGlobal(GlobalValue &GV);
0128   void moveToNextStaticInitGlobal() {
0129     ++I;
0130     while (I != E && !isStaticInitGlobal(*I))
0131       ++I;
0132     if (I == E)
0133       I = E = Module::global_value_iterator();
0134   }
0135 
0136   Module::global_value_iterator I, E;
0137   Triple::ObjectFormatType ObjFmt;
0138 };
0139 
0140 /// Create an iterator range over the GlobalValues that contribute to static
0141 /// initialization.
0142 inline iterator_range<StaticInitGVIterator> getStaticInitGVs(Module &M) {
0143   return make_range(StaticInitGVIterator(M), StaticInitGVIterator());
0144 }
0145 
0146 class CtorDtorRunner {
0147 public:
0148   CtorDtorRunner(JITDylib &JD) : JD(JD) {}
0149   void add(iterator_range<CtorDtorIterator> CtorDtors);
0150   Error run();
0151 
0152 private:
0153   using CtorDtorList = std::vector<SymbolStringPtr>;
0154   using CtorDtorPriorityMap = std::map<unsigned, CtorDtorList>;
0155 
0156   JITDylib &JD;
0157   CtorDtorPriorityMap CtorDtorsByPriority;
0158 };
0159 
0160 /// Support class for static dtor execution. For hosted (in-process) JITs
0161 ///        only!
0162 ///
0163 ///   If a __cxa_atexit function isn't found C++ programs that use static
0164 /// destructors will fail to link. However, we don't want to use the host
0165 /// process's __cxa_atexit, because it will schedule JIT'd destructors to run
0166 /// after the JIT has been torn down, which is no good. This class makes it easy
0167 /// to override __cxa_atexit (and the related __dso_handle).
0168 ///
0169 ///   To use, clients should manually call searchOverrides from their symbol
0170 /// resolver. This should generally be done after attempting symbol resolution
0171 /// inside the JIT, but before searching the host process's symbol table. When
0172 /// the client determines that destructors should be run (generally at JIT
0173 /// teardown or after a return from main), the runDestructors method should be
0174 /// called.
0175 class LocalCXXRuntimeOverridesBase {
0176 public:
0177   /// Run any destructors recorded by the overriden __cxa_atexit function
0178   /// (CXAAtExitOverride).
0179   void runDestructors();
0180 
0181 protected:
0182   using DestructorPtr = void (*)(void *);
0183   using CXXDestructorDataPair = std::pair<DestructorPtr, void *>;
0184   using CXXDestructorDataPairList = std::vector<CXXDestructorDataPair>;
0185   CXXDestructorDataPairList DSOHandleOverride;
0186   static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
0187                                void *DSOHandle);
0188 };
0189 
0190 class LocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
0191 public:
0192   Error enable(JITDylib &JD, MangleAndInterner &Mangler);
0193 };
0194 
0195 /// An interface for Itanium __cxa_atexit interposer implementations.
0196 class ItaniumCXAAtExitSupport {
0197 public:
0198   struct AtExitRecord {
0199     void (*F)(void *);
0200     void *Ctx;
0201   };
0202 
0203   void registerAtExit(void (*F)(void *), void *Ctx, void *DSOHandle);
0204   void runAtExits(void *DSOHandle);
0205 
0206 private:
0207   std::mutex AtExitsMutex;
0208   DenseMap<void *, std::vector<AtExitRecord>> AtExitRecords;
0209 };
0210 
0211 /// A utility class to expose symbols found via dlsym to the JIT.
0212 ///
0213 /// If an instance of this class is attached to a JITDylib as a fallback
0214 /// definition generator, then any symbol found in the given DynamicLibrary that
0215 /// passes the 'Allow' predicate will be added to the JITDylib.
0216 class DynamicLibrarySearchGenerator : public DefinitionGenerator {
0217 public:
0218   using SymbolPredicate = std::function<bool(const SymbolStringPtr &)>;
0219   using AddAbsoluteSymbolsFn = unique_function<Error(JITDylib &, SymbolMap)>;
0220 
0221   /// Create a DynamicLibrarySearchGenerator that searches for symbols in the
0222   /// given sys::DynamicLibrary.
0223   ///
0224   /// If the Allow predicate is given then only symbols matching the predicate
0225   /// will be searched for. If the predicate is not given then all symbols will
0226   /// be searched for.
0227   ///
0228   /// If \p AddAbsoluteSymbols is provided, it is used to add the symbols to the
0229   /// \c JITDylib; otherwise it uses JD.define(absoluteSymbols(...)).
0230   DynamicLibrarySearchGenerator(
0231       sys::DynamicLibrary Dylib, char GlobalPrefix,
0232       SymbolPredicate Allow = SymbolPredicate(),
0233       AddAbsoluteSymbolsFn AddAbsoluteSymbols = nullptr);
0234 
0235   /// Permanently loads the library at the given path and, on success, returns
0236   /// a DynamicLibrarySearchGenerator that will search it for symbol definitions
0237   /// in the library. On failure returns the reason the library failed to load.
0238   static Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
0239   Load(const char *FileName, char GlobalPrefix,
0240        SymbolPredicate Allow = SymbolPredicate(),
0241        AddAbsoluteSymbolsFn AddAbsoluteSymbols = nullptr);
0242 
0243   /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
0244   /// the current process.
0245   static Expected<std::unique_ptr<DynamicLibrarySearchGenerator>>
0246   GetForCurrentProcess(char GlobalPrefix,
0247                        SymbolPredicate Allow = SymbolPredicate(),
0248                        AddAbsoluteSymbolsFn AddAbsoluteSymbols = nullptr) {
0249     return Load(nullptr, GlobalPrefix, std::move(Allow),
0250                 std::move(AddAbsoluteSymbols));
0251   }
0252 
0253   Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
0254                       JITDylibLookupFlags JDLookupFlags,
0255                       const SymbolLookupSet &Symbols) override;
0256 
0257 private:
0258   sys::DynamicLibrary Dylib;
0259   SymbolPredicate Allow;
0260   AddAbsoluteSymbolsFn AddAbsoluteSymbols;
0261   char GlobalPrefix;
0262 };
0263 
0264 /// A utility class to expose symbols from a static library.
0265 ///
0266 /// If an instance of this class is attached to a JITDylib as a fallback
0267 /// definition generator, then any symbol found in the archive will result in
0268 /// the containing object being added to the JITDylib.
0269 class StaticLibraryDefinitionGenerator : public DefinitionGenerator {
0270 public:
0271   /// Interface builder function for objects loaded from this archive.
0272   using GetObjectFileInterface =
0273       unique_function<Expected<MaterializationUnit::Interface>(
0274           ExecutionSession &ES, MemoryBufferRef ObjBuffer)>;
0275 
0276   /// Callback for visiting archive members at construction time.
0277   /// Con be used to pre-load archive members.
0278   using VisitMembersFunction = unique_function<Error(MemoryBufferRef)>;
0279 
0280   /// A VisitMembersFunction that unconditionally loads all object files from
0281   /// the archive.
0282   /// Archive members that are not valid object files will be skipped.
0283   static VisitMembersFunction loadAllObjectFileMembers(ObjectLayer &L,
0284                                                        JITDylib &JD);
0285 
0286   /// Try to create a StaticLibraryDefinitionGenerator from the given path.
0287   ///
0288   /// This call will succeed if the file at the given path is a static library
0289   /// or a MachO universal binary containing a static library that is compatible
0290   /// with the ExecutionSession's triple. Otherwise it will return an error.
0291   static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
0292   Load(ObjectLayer &L, const char *FileName,
0293        VisitMembersFunction VisitMembers = VisitMembersFunction(),
0294        GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
0295 
0296   /// Try to create a StaticLibrarySearchGenerator from the given memory buffer
0297   /// and Archive object.
0298   static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
0299   Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
0300          std::unique_ptr<object::Archive> Archive,
0301          VisitMembersFunction VisitMembers = VisitMembersFunction(),
0302          GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
0303 
0304   /// Try to create a StaticLibrarySearchGenerator from the given memory buffer.
0305   /// This call will succeed if the buffer contains a valid archive, otherwise
0306   /// it will return an error.
0307   ///
0308   /// This call will succeed if the buffer contains a valid static library or a
0309   /// MachO universal binary containing a static library that is compatible
0310   /// with the ExecutionSession's triple. Otherwise it will return an error.
0311   static Expected<std::unique_ptr<StaticLibraryDefinitionGenerator>>
0312   Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
0313          VisitMembersFunction VisitMembers = VisitMembersFunction(),
0314          GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
0315 
0316   /// Returns a list of filenames of dynamic libraries that this archive has
0317   /// imported. This class does not load these libraries by itself. User is
0318   /// responsible for making sure these libraries are available to the JITDylib.
0319   const std::set<std::string> &getImportedDynamicLibraries() const {
0320     return ImportedDynamicLibraries;
0321   }
0322 
0323   Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
0324                       JITDylibLookupFlags JDLookupFlags,
0325                       const SymbolLookupSet &Symbols) override;
0326 
0327 private:
0328   StaticLibraryDefinitionGenerator(ObjectLayer &L,
0329                                    std::unique_ptr<MemoryBuffer> ArchiveBuffer,
0330                                    std::unique_ptr<object::Archive> Archive,
0331                                    GetObjectFileInterface GetObjFileInterface,
0332                                    Error &Err);
0333   Error buildObjectFilesMap();
0334 
0335   ObjectLayer &L;
0336   GetObjectFileInterface GetObjFileInterface;
0337   std::set<std::string> ImportedDynamicLibraries;
0338   std::unique_ptr<MemoryBuffer> ArchiveBuffer;
0339   std::unique_ptr<object::Archive> Archive;
0340   DenseMap<SymbolStringPtr, MemoryBufferRef> ObjectFilesMap;
0341   BumpPtrAllocator ObjFileNameStorage;
0342 };
0343 
0344 /// A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT
0345 /// stubs.
0346 ///
0347 /// If an instance of this class is attached to a JITDylib as a fallback
0348 /// definition generator, PLT stubs and dllimport __imp_ symbols will be
0349 /// generated for external symbols found outside the given jitdylib. Currently
0350 /// only supports x86_64 architecture.
0351 class DLLImportDefinitionGenerator : public DefinitionGenerator {
0352 public:
0353   /// Creates a DLLImportDefinitionGenerator instance.
0354   static std::unique_ptr<DLLImportDefinitionGenerator>
0355   Create(ExecutionSession &ES, ObjectLinkingLayer &L);
0356 
0357   Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
0358                       JITDylibLookupFlags JDLookupFlags,
0359                       const SymbolLookupSet &Symbols) override;
0360 
0361 private:
0362   DLLImportDefinitionGenerator(ExecutionSession &ES, ObjectLinkingLayer &L)
0363       : ES(ES), L(L) {}
0364 
0365   static Expected<unsigned> getTargetPointerSize(const Triple &TT);
0366   static Expected<llvm::endianness> getEndianness(const Triple &TT);
0367   Expected<std::unique_ptr<jitlink::LinkGraph>>
0368   createStubsGraph(const SymbolMap &Resolved);
0369 
0370   static StringRef getImpPrefix() { return "__imp_"; }
0371 
0372   static StringRef getSectionName() { return "$__DLLIMPORT_STUBS"; }
0373 
0374   ExecutionSession &ES;
0375   ObjectLinkingLayer &L;
0376 };
0377 
0378 } // end namespace orc
0379 } // end namespace llvm
0380 
0381 #endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H