LLVM  14.0.0git
MachOPlatform.h
Go to the documentation of this file.
1 //===-- MachOPlatform.h - Utilities for executing MachO 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 // Utilities for executing JIT'd MachO in Orc.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_EXECUTIONENGINE_ORC_MACHOPLATFORM_H
14 #define LLVM_EXECUTIONENGINE_ORC_MACHOPLATFORM_H
15 
16 #include "llvm/ADT/StringRef.h"
21 
22 #include <future>
23 #include <thread>
24 #include <vector>
25 
26 namespace llvm {
27 namespace orc {
28 
30  using SectionList = std::vector<ExecutorAddrRange>;
31 
33  : Name(std::move(Name)),
35 
36  std::string Name;
39 
41 };
42 
44 
45 using MachOJITDylibInitializerSequence = std::vector<MachOJITDylibInitializers>;
46 
48  std::vector<MachOJITDylibDeinitializers>;
49 
50 /// Mediates between MachO initialization and ExecutionSession state.
51 class MachOPlatform : public Platform {
52 public:
53  /// Try to create a MachOPlatform instance, adding the ORC runtime to the
54  /// given JITDylib.
55  ///
56  /// The ORC runtime requires access to a number of symbols in libc++, and
57  /// requires access to symbols in libobjc, and libswiftCore to support
58  /// Objective-C and Swift code. It is up to the caller to ensure that the
59  /// requried symbols can be referenced by code added to PlatformJD. The
60  /// standard way to achieve this is to first attach dynamic library search
61  /// generators for either the given process, or for the specific required
62  /// libraries, to PlatformJD, then to create the platform instance:
63  ///
64  /// \code{.cpp}
65  /// auto &PlatformJD = ES.createBareJITDylib("stdlib");
66  /// PlatformJD.addGenerator(
67  /// ExitOnErr(EPCDynamicLibrarySearchGenerator
68  /// ::GetForTargetProcess(EPC)));
69  /// ES.setPlatform(
70  /// ExitOnErr(MachOPlatform::Create(ES, ObjLayer, EPC, PlatformJD,
71  /// "/path/to/orc/runtime")));
72  /// \endcode
73  ///
74  /// Alternatively, these symbols could be added to another JITDylib that
75  /// PlatformJD links against.
76  ///
77  /// Clients are also responsible for ensuring that any JIT'd code that
78  /// depends on runtime functions (including any code using TLV or static
79  /// destructors) can reference the runtime symbols. This is usually achieved
80  /// by linking any JITDylibs containing regular code against
81  /// PlatformJD.
82  ///
83  /// By default, MachOPlatform will add the set of aliases returned by the
84  /// standardPlatformAliases function. This includes both required aliases
85  /// (e.g. __cxa_atexit -> __orc_rt_macho_cxa_atexit for static destructor
86  /// support), and optional aliases that provide JIT versions of common
87  /// functions (e.g. dlopen -> __orc_rt_macho_jit_dlopen). Clients can
88  /// override these defaults by passing a non-None value for the
89  /// RuntimeAliases function, in which case the client is responsible for
90  /// setting up all aliases (including the required ones).
92  Create(ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer,
93  JITDylib &PlatformJD, const char *OrcRuntimePath,
94  Optional<SymbolAliasMap> RuntimeAliases = None);
95 
96  ExecutionSession &getExecutionSession() const { return ES; }
97  ObjectLinkingLayer &getObjectLinkingLayer() const { return ObjLinkingLayer; }
98 
99  Error setupJITDylib(JITDylib &JD) override;
100  Error teardownJITDylib(JITDylib &JD) override;
102  const MaterializationUnit &MU) override;
103  Error notifyRemoving(ResourceTracker &RT) override;
104 
105  /// Returns an AliasMap containing the default aliases for the MachOPlatform.
106  /// This can be modified by clients when constructing the platform to add
107  /// or remove aliases.
109 
110  /// Returns the array of required CXX aliases.
112 
113  /// Returns the array of standard runtime utility aliases for MachO.
116 
117  /// Returns true if the given section name is an initializer section.
118  static bool isInitializerSection(StringRef SegName, StringRef SectName);
119 
120 private:
121  // The MachOPlatformPlugin scans/modifies LinkGraphs to support MachO
122  // platform features including initializers, exceptions, TLV, and language
123  // runtime registration.
124  class MachOPlatformPlugin : public ObjectLinkingLayer::Plugin {
125  public:
126  MachOPlatformPlugin(MachOPlatform &MP) : MP(MP) {}
127 
128  void modifyPassConfig(MaterializationResponsibility &MR,
130  jitlink::PassConfiguration &Config) override;
131 
132  SyntheticSymbolDependenciesMap
133  getSyntheticSymbolDependencies(MaterializationResponsibility &MR) override;
134 
135  // FIXME: We should be tentatively tracking scraped sections and discarding
136  // if the MR fails.
137  Error notifyFailed(MaterializationResponsibility &MR) override {
138  return Error::success();
139  }
140 
141  Error notifyRemovingResources(ResourceKey K) override {
142  return Error::success();
143  }
144 
145  void notifyTransferringResources(ResourceKey DstKey,
146  ResourceKey SrcKey) override {}
147 
148  private:
149  using InitSymbolDepMap =
150  DenseMap<MaterializationResponsibility *, JITLinkSymbolSet>;
151 
152  void addEHAndTLVSupportPasses(MaterializationResponsibility &MR,
153  jitlink::PassConfiguration &Config);
154 
155  Error associateJITDylibHeaderSymbol(jitlink::LinkGraph &G,
156  MaterializationResponsibility &MR);
157 
158  Error preserveInitSections(jitlink::LinkGraph &G,
159  MaterializationResponsibility &MR);
160 
161  Error processObjCImageInfo(jitlink::LinkGraph &G,
162  MaterializationResponsibility &MR);
163 
164  Error registerInitSections(jitlink::LinkGraph &G, JITDylib &JD);
165 
166  Error fixTLVSectionsAndEdges(jitlink::LinkGraph &G, JITDylib &JD);
167 
168  Error registerEHAndTLVSections(jitlink::LinkGraph &G);
169 
170  Error registerEHSectionsPhase1(jitlink::LinkGraph &G);
171 
172  std::mutex PluginMutex;
173  MachOPlatform &MP;
174  DenseMap<JITDylib *, std::pair<uint32_t, uint32_t>> ObjCImageInfos;
175  InitSymbolDepMap InitSymbolDeps;
176  };
177 
178  using SendInitializerSequenceFn =
179  unique_function<void(Expected<MachOJITDylibInitializerSequence>)>;
180 
181  using SendDeinitializerSequenceFn =
182  unique_function<void(Expected<MachOJITDylibDeinitializerSequence>)>;
183 
184  using SendSymbolAddressFn = unique_function<void(Expected<ExecutorAddr>)>;
185 
186  static bool supportedTarget(const Triple &TT);
187 
188  MachOPlatform(ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer,
189  JITDylib &PlatformJD,
190  std::unique_ptr<DefinitionGenerator> OrcRuntimeGenerator,
191  Error &Err);
192 
193  // Associate MachOPlatform JIT-side runtime support functions with handlers.
194  Error associateRuntimeSupportFunctions(JITDylib &PlatformJD);
195 
196  void getInitializersBuildSequencePhase(SendInitializerSequenceFn SendResult,
197  JITDylib &JD,
198  std::vector<JITDylibSP> DFSLinkOrder);
199 
200  void getInitializersLookupPhase(SendInitializerSequenceFn SendResult,
201  JITDylib &JD);
202 
203  void rt_getInitializers(SendInitializerSequenceFn SendResult,
204  StringRef JDName);
205 
206  void rt_getDeinitializers(SendDeinitializerSequenceFn SendResult,
207  ExecutorAddr Handle);
208 
209  void rt_lookupSymbol(SendSymbolAddressFn SendResult, ExecutorAddr Handle,
210  StringRef SymbolName);
211 
212  // Records the addresses of runtime symbols used by the platform.
213  Error bootstrapMachORuntime(JITDylib &PlatformJD);
214 
215  Error registerInitInfo(JITDylib &JD, ExecutorAddr ObjCImageInfoAddr,
216  ArrayRef<jitlink::Section *> InitSections);
217 
218  Expected<uint64_t> createPThreadKey();
219 
220  enum PlatformState { BootstrapPhase1, BootstrapPhase2, Initialized };
221 
222  ExecutionSession &ES;
223  ObjectLinkingLayer &ObjLinkingLayer;
224 
225  SymbolStringPtr MachOHeaderStartSymbol;
226  std::atomic<PlatformState> State{BootstrapPhase1};
227 
228  ExecutorAddr orc_rt_macho_platform_bootstrap;
229  ExecutorAddr orc_rt_macho_platform_shutdown;
230  ExecutorAddr orc_rt_macho_register_ehframe_section;
231  ExecutorAddr orc_rt_macho_deregister_ehframe_section;
232  ExecutorAddr orc_rt_macho_register_thread_data_section;
233  ExecutorAddr orc_rt_macho_deregister_thread_data_section;
234  ExecutorAddr orc_rt_macho_create_pthread_key;
235 
236  DenseMap<JITDylib *, SymbolLookupSet> RegisteredInitSymbols;
237 
238  // InitSeqs gets its own mutex to avoid locking the whole session when
239  // aggregating data from the jitlink.
240  std::mutex PlatformMutex;
241  DenseMap<JITDylib *, MachOJITDylibInitializers> InitSeqs;
242 
243  DenseMap<ExecutorAddr, JITDylib *> HeaderAddrToJITDylib;
244  DenseMap<JITDylib *, uint64_t> JITDylibToPThreadKey;
245 };
246 
247 namespace shared {
248 
250  SPSSequence<SPSTuple<SPSString, SPSExecutorAddrRangeSequence>>;
251 
253  SPSTuple<SPSString, SPSExecutorAddr, SPSExecutorAddr,
255 
258 
259 /// Serialization traits for MachOJITDylibInitializers.
260 template <>
263 public:
264  static size_t size(const MachOJITDylibInitializers &MOJDIs) {
266  MOJDIs.Name, MOJDIs.MachOHeaderAddress, MOJDIs.ObjCImageInfoAddress,
267  MOJDIs.InitSections);
268  }
269 
271  const MachOJITDylibInitializers &MOJDIs) {
272  return SPSMachOJITDylibInitializers::AsArgList::serialize(
273  OB, MOJDIs.Name, MOJDIs.MachOHeaderAddress, MOJDIs.ObjCImageInfoAddress,
274  MOJDIs.InitSections);
275  }
276 
277  static bool deserialize(SPSInputBuffer &IB,
278  MachOJITDylibInitializers &MOJDIs) {
279  return SPSMachOJITDylibInitializers::AsArgList::deserialize(
280  IB, MOJDIs.Name, MOJDIs.MachOHeaderAddress, MOJDIs.ObjCImageInfoAddress,
281  MOJDIs.InitSections);
282  }
283 };
284 
286 
289 
290 template <>
293 public:
294  static size_t size(const MachOJITDylibDeinitializers &MOJDDs) { return 0; }
295 
297  const MachOJITDylibDeinitializers &MOJDDs) {
298  return true;
299  }
300 
301  static bool deserialize(SPSInputBuffer &IB,
302  MachOJITDylibDeinitializers &MOJDDs) {
303  MOJDDs = MachOJITDylibDeinitializers();
304  return true;
305  }
306 };
307 
308 } // end namespace shared
309 } // end namespace orc
310 } // end namespace llvm
311 
312 #endif // LLVM_EXECUTIONENGINE_ORC_MACHOPLATFORM_H
llvm::orc::ExecutorAddr
Represents an address in the executor process.
Definition: ExecutorAddress.h:30
llvm::orc::ResourceKey
uintptr_t ResourceKey
Definition: Core.h:50
llvm::orc::MachOPlatform::notifyRemoving
Error notifyRemoving(ResourceTracker &RT) override
This method will be called under the ExecutionSession lock when a ResourceTracker is removed.
Definition: MachOPlatform.cpp:224
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
llvm::orc::JITDylib
Represents a JIT'd dynamic library.
Definition: Core.h:947
llvm::lltok::Error
@ Error
Definition: LLToken.h:21
llvm::orc::shared::SPSSequence
SPS tag type for sequences.
Definition: SimplePackedSerialization.h:204
llvm::orc::shared::SPSSerializationTraits
Specialize to describe how to serialize/deserialize to/from the given concrete type.
Definition: SimplePackedSerialization.h:104
StringRef.h
llvm::orc::MachOJITDylibInitializers
Definition: MachOPlatform.h:29
llvm::orc::shared::SPSOutputBuffer
Output char buffer with overflow check.
Definition: SimplePackedSerialization.h:54
llvm::orc::shared::SPSSerializationTraits< SPSMachOJITDylibInitializers, MachOJITDylibInitializers >::serialize
static bool serialize(SPSOutputBuffer &OB, const MachOJITDylibInitializers &MOJDIs)
Definition: MachOPlatform.h:270
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:331
llvm::orc::MachOPlatform::teardownJITDylib
Error teardownJITDylib(JITDylib &JD) override
This method will be called outside the session lock each time a JITDylib is removed to allow the Plat...
Definition: MachOPlatform.cpp:206
llvm::orc::MachOJITDylibInitializers::SectionList
std::vector< ExecutorAddrRange > SectionList
Definition: MachOPlatform.h:30
llvm::orc::ResourceTracker
API to remove / transfer ownership of JIT resources.
Definition: Core.h:53
llvm::orc::MachOJITDylibDeinitializerSequence
std::vector< MachOJITDylibDeinitializers > MachOJITDylibDeinitializerSequence
Definition: MachOPlatform.h:48
llvm::Optional
Definition: APInt.h:33
llvm::X86II::OB
@ OB
Definition: X86BaseInfo.h:801
llvm::orc::shared::SPSInputBuffer
Input char buffer with underflow check.
Definition: SimplePackedSerialization.h:73
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
llvm::orc::MachOJITDylibInitializerSequence
std::vector< MachOJITDylibInitializers > MachOJITDylibInitializerSequence
Definition: MachOPlatform.h:45
llvm::orc::MachOJITDylibDeinitializers
Definition: MachOPlatform.h:43
llvm::orc::shared::SPSTuple
SPS tag type for tuples.
Definition: SimplePackedSerialization.h:194
llvm::orc::MachOJITDylibInitializers::Name
std::string Name
Definition: MachOPlatform.h:36
llvm::orc::shared::SPSSerializationTraits< SPSMachOJITDylibDeinitializers, MachOJITDylibDeinitializers >::serialize
static bool serialize(SPSOutputBuffer &OB, const MachOJITDylibDeinitializers &MOJDDs)
Definition: MachOPlatform.h:296
llvm::orc::MachOJITDylibInitializers::MachOJITDylibInitializers
MachOJITDylibInitializers(std::string Name, ExecutorAddr MachOHeaderAddress)
Definition: MachOPlatform.h:32
llvm::orc::MaterializationUnit
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
Definition: Core.h:666
llvm::orc::MachOPlatform::Create
static Expected< std::unique_ptr< MachOPlatform > > Create(ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD, const char *OrcRuntimePath, Optional< SymbolAliasMap > RuntimeAliases=None)
Try to create a MachOPlatform instance, adding the ORC runtime to the given JITDylib.
Definition: MachOPlatform.cpp:155
llvm::orc::shared::SPSNamedExecutorAddrRangeSequenceMap
SPSSequence< SPSTuple< SPSString, SPSExecutorAddrRangeSequence > > SPSNamedExecutorAddrRangeSequenceMap
Definition: ELFNixPlatform.h:273
llvm::orc::MachOPlatform::requiredCXXAliases
static ArrayRef< std::pair< const char *, const char * > > requiredCXXAliases()
Returns the array of required CXX aliases.
Definition: MachOPlatform.cpp:246
llvm::orc::shared::SPSEmpty
Definition: SimplePackedSerialization.h:188
llvm::orc::MachOJITDylibInitializers::MachOHeaderAddress
ExecutorAddr MachOHeaderAddress
Definition: MachOPlatform.h:37
llvm::orc::shared::SPSSerializationTraits< SPSMachOJITDylibDeinitializers, MachOJITDylibDeinitializers >::deserialize
static bool deserialize(SPSInputBuffer &IB, MachOJITDylibDeinitializers &MOJDDs)
Definition: MachOPlatform.h:301
llvm::orc::MachOPlatform
Mediates between MachO initialization and ExecutionSession state.
Definition: MachOPlatform.h:51
llvm::None
const NoneType None
Definition: None.h:23
llvm::StringMap< SectionList >
llvm::orc::shared::SPSSerializationTraits< SPSMachOJITDylibInitializers, MachOJITDylibInitializers >::deserialize
static bool deserialize(SPSInputBuffer &IB, MachOJITDylibInitializers &MOJDIs)
Definition: MachOPlatform.h:277
llvm::orc::MachOPlatform::isInitializerSection
static bool isInitializerSection(StringRef SegName, StringRef SectName)
Returns true if the given section name is an initializer section.
Definition: MachOPlatform.cpp:264
llvm::orc::MachOPlatform::notifyAdding
Error notifyAdding(ResourceTracker &RT, const MaterializationUnit &MU) override
This method will be called under the ExecutionSession lock each time a MaterializationUnit is added t...
Definition: MachOPlatform.cpp:208
G
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
llvm::DenseMap< SymbolStringPtr, SymbolAliasMapEntry >
llvm::orc::MachOPlatform::getObjectLinkingLayer
ObjectLinkingLayer & getObjectLinkingLayer() const
Definition: MachOPlatform.h:97
size
i< reg-> size
Definition: README.txt:166
llvm::move
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1707
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: APInt.h:32
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
llvm::orc::Platform
Platforms set up standard symbols and mediate interactions between dynamic initializers (e....
Definition: Core.h:1302
llvm::orc::ObjectLinkingLayer
An ObjectLayer implementation built on JITLink.
Definition: ObjectLinkingLayer.h:50
llvm::orc::MachOPlatform::setupJITDylib
Error setupJITDylib(JITDylib &JD) override
This method will be called outside the session lock each time a JITDylib is created (unless it is cre...
Definition: MachOPlatform.cpp:201
llvm::AMDGPU::HSAMD::Kernel::Key::SymbolName
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
Definition: AMDGPUMetadata.h:381
llvm::orc::shared::SPSSerializationTraits< SPSMachOJITDylibDeinitializers, MachOJITDylibDeinitializers >::size
static size_t size(const MachOJITDylibDeinitializers &MOJDDs)
Definition: MachOPlatform.h:294
std
Definition: BitVector.h:838
ExecutorAddress.h
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
llvm::orc::ExecutionSession
An ExecutionSession represents a running JIT program.
Definition: Core.h:1358
llvm::orc::MachOJITDylibInitializers::ObjCImageInfoAddress
ExecutorAddr ObjCImageInfoAddress
Definition: MachOPlatform.h:38
llvm::orc::MachOPlatform::standardRuntimeUtilityAliases
static ArrayRef< std::pair< const char *, const char * > > standardRuntimeUtilityAliases()
Returns the array of standard runtime utility aliases for MachO.
Definition: MachOPlatform.cpp:254
llvm::orc::shared::SPSMachOJITDylibInitializers
SPSTuple< SPSString, SPSExecutorAddr, SPSExecutorAddr, SPSNamedExecutorAddrRangeSequenceMap > SPSMachOJITDylibInitializers
Definition: MachOPlatform.h:254
Core.h
llvm::orc::MachOJITDylibInitializers::InitSections
StringMap< SectionList > InitSections
Definition: MachOPlatform.h:40
llvm::orc::shared::SPSSerializationTraits< SPSMachOJITDylibInitializers, MachOJITDylibInitializers >::size
static size_t size(const MachOJITDylibInitializers &MOJDIs)
Definition: MachOPlatform.h:264
llvm::orc::ObjectLinkingLayer::Plugin
Plugin instances can be added to the ObjectLinkingLayer to receive callbacks when code is loaded or e...
Definition: ObjectLinkingLayer.h:60
llvm::orc::MachOPlatform::standardPlatformAliases
static SymbolAliasMap standardPlatformAliases(ExecutionSession &ES)
Returns an AliasMap containing the default aliases for the MachOPlatform.
Definition: MachOPlatform.cpp:238
ExecutorProcessControl.h
ObjectLinkingLayer.h
llvm::orc::shared::SPSString
SPSSequence< char > SPSString
SPS tag type for strings, which are equivalent to sequences of chars.
Definition: SimplePackedSerialization.h:207
llvm::orc::MachOPlatform::getExecutionSession
ExecutionSession & getExecutionSession() const
Definition: MachOPlatform.h:96