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;
101  const MaterializationUnit &MU) override;
102  Error notifyRemoving(ResourceTracker &RT) override;
103 
104  /// Returns an AliasMap containing the default aliases for the MachOPlatform.
105  /// This can be modified by clients when constructing the platform to add
106  /// or remove aliases.
108 
109  /// Returns the array of required CXX aliases.
111 
112  /// Returns the array of standard runtime utility aliases for MachO.
115 
116  /// Returns true if the given section name is an initializer section.
117  static bool isInitializerSection(StringRef SegName, StringRef SectName);
118 
119 private:
120  // The MachOPlatformPlugin scans/modifies LinkGraphs to support MachO
121  // platform features including initializers, exceptions, TLV, and language
122  // runtime registration.
123  class MachOPlatformPlugin : public ObjectLinkingLayer::Plugin {
124  public:
125  MachOPlatformPlugin(MachOPlatform &MP) : MP(MP) {}
126 
127  void modifyPassConfig(MaterializationResponsibility &MR,
129  jitlink::PassConfiguration &Config) override;
130 
131  SyntheticSymbolDependenciesMap
132  getSyntheticSymbolDependencies(MaterializationResponsibility &MR) override;
133 
134  // FIXME: We should be tentatively tracking scraped sections and discarding
135  // if the MR fails.
136  Error notifyFailed(MaterializationResponsibility &MR) override {
137  return Error::success();
138  }
139 
140  Error notifyRemovingResources(ResourceKey K) override {
141  return Error::success();
142  }
143 
144  void notifyTransferringResources(ResourceKey DstKey,
145  ResourceKey SrcKey) override {}
146 
147  private:
148  using InitSymbolDepMap =
149  DenseMap<MaterializationResponsibility *, JITLinkSymbolSet>;
150 
151  void addEHAndTLVSupportPasses(MaterializationResponsibility &MR,
152  jitlink::PassConfiguration &Config);
153 
154  Error associateJITDylibHeaderSymbol(jitlink::LinkGraph &G,
155  MaterializationResponsibility &MR);
156 
157  Error preserveInitSections(jitlink::LinkGraph &G,
158  MaterializationResponsibility &MR);
159 
160  Error processObjCImageInfo(jitlink::LinkGraph &G,
161  MaterializationResponsibility &MR);
162 
163  Error registerInitSections(jitlink::LinkGraph &G, JITDylib &JD);
164 
165  Error fixTLVSectionsAndEdges(jitlink::LinkGraph &G, JITDylib &JD);
166 
167  Error registerEHAndTLVSections(jitlink::LinkGraph &G);
168 
169  Error registerEHSectionsPhase1(jitlink::LinkGraph &G);
170 
171  std::mutex PluginMutex;
172  MachOPlatform &MP;
173  DenseMap<JITDylib *, std::pair<uint32_t, uint32_t>> ObjCImageInfos;
174  InitSymbolDepMap InitSymbolDeps;
175  };
176 
177  using SendInitializerSequenceFn =
178  unique_function<void(Expected<MachOJITDylibInitializerSequence>)>;
179 
180  using SendDeinitializerSequenceFn =
181  unique_function<void(Expected<MachOJITDylibDeinitializerSequence>)>;
182 
183  using SendSymbolAddressFn = unique_function<void(Expected<ExecutorAddr>)>;
184 
185  static bool supportedTarget(const Triple &TT);
186 
187  MachOPlatform(ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer,
188  JITDylib &PlatformJD,
189  std::unique_ptr<DefinitionGenerator> OrcRuntimeGenerator,
190  Error &Err);
191 
192  // Associate MachOPlatform JIT-side runtime support functions with handlers.
193  Error associateRuntimeSupportFunctions(JITDylib &PlatformJD);
194 
195  void getInitializersBuildSequencePhase(SendInitializerSequenceFn SendResult,
196  JITDylib &JD,
197  std::vector<JITDylibSP> DFSLinkOrder);
198 
199  void getInitializersLookupPhase(SendInitializerSequenceFn SendResult,
200  JITDylib &JD);
201 
202  void rt_getInitializers(SendInitializerSequenceFn SendResult,
203  StringRef JDName);
204 
205  void rt_getDeinitializers(SendDeinitializerSequenceFn SendResult,
206  ExecutorAddr Handle);
207 
208  void rt_lookupSymbol(SendSymbolAddressFn SendResult, ExecutorAddr Handle,
209  StringRef SymbolName);
210 
211  // Records the addresses of runtime symbols used by the platform.
212  Error bootstrapMachORuntime(JITDylib &PlatformJD);
213 
214  Error registerInitInfo(JITDylib &JD, ExecutorAddr ObjCImageInfoAddr,
215  ArrayRef<jitlink::Section *> InitSections);
216 
217  Expected<uint64_t> createPThreadKey();
218 
219  enum PlatformState { BootstrapPhase1, BootstrapPhase2, Initialized };
220 
221  ExecutionSession &ES;
222  ObjectLinkingLayer &ObjLinkingLayer;
223 
224  SymbolStringPtr MachOHeaderStartSymbol;
225  std::atomic<PlatformState> State{BootstrapPhase1};
226 
227  ExecutorAddr orc_rt_macho_platform_bootstrap;
228  ExecutorAddr orc_rt_macho_platform_shutdown;
229  ExecutorAddr orc_rt_macho_register_ehframe_section;
230  ExecutorAddr orc_rt_macho_deregister_ehframe_section;
231  ExecutorAddr orc_rt_macho_register_thread_data_section;
232  ExecutorAddr orc_rt_macho_deregister_thread_data_section;
233  ExecutorAddr orc_rt_macho_create_pthread_key;
234 
235  DenseMap<JITDylib *, SymbolLookupSet> RegisteredInitSymbols;
236 
237  // InitSeqs gets its own mutex to avoid locking the whole session when
238  // aggregating data from the jitlink.
239  std::mutex PlatformMutex;
240  DenseMap<JITDylib *, MachOJITDylibInitializers> InitSeqs;
241 
242  DenseMap<JITTargetAddress, JITDylib *> HeaderAddrToJITDylib;
243  DenseMap<JITDylib *, uint64_t> JITDylibToPThreadKey;
244 };
245 
246 namespace shared {
247 
249  SPSSequence<SPSTuple<SPSString, SPSExecutorAddrRangeSequence>>;
250 
252  SPSTuple<SPSString, SPSExecutorAddr, SPSExecutorAddr,
254 
257 
258 /// Serialization traits for MachOJITDylibInitializers.
259 template <>
262 public:
263  static size_t size(const MachOJITDylibInitializers &MOJDIs) {
265  MOJDIs.Name, MOJDIs.MachOHeaderAddress, MOJDIs.ObjCImageInfoAddress,
266  MOJDIs.InitSections);
267  }
268 
270  const MachOJITDylibInitializers &MOJDIs) {
271  return SPSMachOJITDylibInitializers::AsArgList::serialize(
272  OB, MOJDIs.Name, MOJDIs.MachOHeaderAddress, MOJDIs.ObjCImageInfoAddress,
273  MOJDIs.InitSections);
274  }
275 
276  static bool deserialize(SPSInputBuffer &IB,
277  MachOJITDylibInitializers &MOJDIs) {
278  return SPSMachOJITDylibInitializers::AsArgList::deserialize(
279  IB, MOJDIs.Name, MOJDIs.MachOHeaderAddress, MOJDIs.ObjCImageInfoAddress,
280  MOJDIs.InitSections);
281  }
282 };
283 
285 
288 
289 template <>
292 public:
293  static size_t size(const MachOJITDylibDeinitializers &MOJDDs) { return 0; }
294 
296  const MachOJITDylibDeinitializers &MOJDDs) {
297  return true;
298  }
299 
300  static bool deserialize(SPSInputBuffer &IB,
301  MachOJITDylibDeinitializers &MOJDDs) {
302  MOJDDs = MachOJITDylibDeinitializers();
303  return true;
304  }
305 };
306 
307 } // end namespace shared
308 } // end namespace orc
309 } // end namespace llvm
310 
311 #endif // LLVM_EXECUTIONENGINE_ORC_MACHOPLATFORM_H
llvm::orc::ExecutorAddr
Represents an address in the executor process.
Definition: ExecutorAddress.h:37
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:221
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:938
llvm::lltok::Error
@ Error
Definition: LLToken.h:21
llvm::orc::shared::SPSSequence
SPS tag type for sequences.
Definition: SimplePackedSerialization.h:193
llvm::orc::shared::SPSSerializationTraits
Specialize to describe how to serialize/deserialize to/from the given concrete type.
Definition: SimplePackedSerialization.h:103
StringRef.h
llvm::orc::MachOJITDylibInitializers
Definition: MachOPlatform.h:29
llvm::orc::shared::SPSOutputBuffer
Output char buffer with overflow check.
Definition: SimplePackedSerialization.h:53
llvm::orc::shared::SPSSerializationTraits< SPSMachOJITDylibInitializers, MachOJITDylibInitializers >::serialize
static bool serialize(SPSOutputBuffer &OB, const MachOJITDylibInitializers &MOJDIs)
Definition: MachOPlatform.h:269
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:331
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::orc::shared::SPSInputBuffer
Input char buffer with underflow check.
Definition: SimplePackedSerialization.h:72
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:183
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:295
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:154
llvm::orc::shared::SPSNamedExecutorAddrRangeSequenceMap
SPSSequence< SPSTuple< SPSString, SPSExecutorAddrRangeSequence > > SPSNamedExecutorAddrRangeSequenceMap
Definition: ELFNixPlatform.h:272
llvm::orc::MachOPlatform::requiredCXXAliases
static ArrayRef< std::pair< const char *, const char * > > requiredCXXAliases()
Returns the array of required CXX aliases.
Definition: MachOPlatform.cpp:243
llvm::orc::shared::SPSEmpty
Definition: SimplePackedSerialization.h:177
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:300
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:276
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:261
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:205
G
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
llvm::DenseMap
Definition: DenseMap.h:714
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:1658
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:1293
llvm::orc::ObjectLinkingLayer
An ObjectLayer implementation built on JITLink.
Definition: ObjectLinkingLayer.h:54
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:200
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:293
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:1346
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:251
llvm::orc::shared::SPSMachOJITDylibInitializers
SPSTuple< SPSString, SPSExecutorAddr, SPSExecutorAddr, SPSNamedExecutorAddrRangeSequenceMap > SPSMachOJITDylibInitializers
Definition: MachOPlatform.h:253
Core.h
llvm::orc::MachOJITDylibInitializers::InitSections
StringMap< SectionList > InitSections
Definition: MachOPlatform.h:40
llvm::X86II::OB
@ OB
Definition: X86BaseInfo.h:801
llvm::orc::shared::SPSSerializationTraits< SPSMachOJITDylibInitializers, MachOJITDylibInitializers >::size
static size_t size(const MachOJITDylibInitializers &MOJDIs)
Definition: MachOPlatform.h:263
llvm::orc::ObjectLinkingLayer::Plugin
Plugin instances can be added to the ObjectLinkingLayer to receive callbacks when code is loaded or e...
Definition: ObjectLinkingLayer.h:64
llvm::orc::MachOPlatform::standardPlatformAliases
static SymbolAliasMap standardPlatformAliases(ExecutionSession &ES)
Returns an AliasMap containing the default aliases for the MachOPlatform.
Definition: MachOPlatform.cpp:235
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:196
llvm::orc::MachOPlatform::getExecutionSession
ExecutionSession & getExecutionSession() const
Definition: MachOPlatform.h:96