1 //===- macho_platform.cpp -------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains code required to load the rest of the MachO runtime.
11 //===----------------------------------------------------------------------===//
13 #include "macho_platform.h"
17 #include "interval_map.h"
18 #include "wrapper_function_utils.h"
25 #include <string_view>
26 #include <unordered_map>
27 #include <unordered_set>
30 #define DEBUG_TYPE "macho_platform"
32 using namespace __orc_rt
;
33 using namespace __orc_rt::macho
;
35 // Declare function tags for functions in the JIT process.
36 ORC_RT_JIT_DISPATCH_TAG(__orc_rt_macho_push_initializers_tag
)
37 ORC_RT_JIT_DISPATCH_TAG(__orc_rt_macho_symbol_lookup_tag
)
41 struct objc_image_info
;
45 using Class
= objc_class
*;
46 using id
= objc_object
*;
47 using SEL
= objc_selector
*;
49 // Objective-C registration functions.
50 // These are weakly imported. If the Objective-C runtime has not been loaded
51 // then code containing Objective-C sections will generate an error.
52 extern "C" id
objc_msgSend(id
, SEL
, ...) ORC_RT_WEAK_IMPORT
;
53 extern "C" Class
objc_readClassPair(Class
,
54 const objc_image_info
*) ORC_RT_WEAK_IMPORT
;
55 extern "C" SEL
sel_registerName(const char *) ORC_RT_WEAK_IMPORT
;
59 class ProtocolConformanceRecord
;
60 class TypeMetadataRecord
;
63 swift_registerProtocols(const ProtocolRecord
*begin
,
64 const ProtocolRecord
*end
) ORC_RT_WEAK_IMPORT
;
66 extern "C" void swift_registerProtocolConformances(
67 const ProtocolConformanceRecord
*begin
,
68 const ProtocolConformanceRecord
*end
) ORC_RT_WEAK_IMPORT
;
70 extern "C" void swift_registerTypeMetadataRecords(
71 const TypeMetadataRecord
*begin
,
72 const TypeMetadataRecord
*end
) ORC_RT_WEAK_IMPORT
;
74 // Libunwind prototypes.
75 struct unw_dynamic_unwind_sections
{
77 uintptr_t dwarf_section
;
78 size_t dwarf_section_length
;
79 uintptr_t compact_unwind_section
;
80 size_t compact_unwind_section_length
;
83 typedef int (*unw_find_dynamic_unwind_sections
)(
84 uintptr_t addr
, struct unw_dynamic_unwind_sections
*info
);
86 extern "C" int __unw_add_find_dynamic_unwind_sections(
87 unw_find_dynamic_unwind_sections find_dynamic_unwind_sections
)
90 extern "C" int __unw_remove_find_dynamic_unwind_sections(
91 unw_find_dynamic_unwind_sections find_dynamic_unwind_sections
)
96 struct MachOJITDylibDepInfo
{
98 std::vector
<ExecutorAddr
> DepHeaders
;
101 using MachOJITDylibDepInfoMap
=
102 std::unordered_map
<ExecutorAddr
, MachOJITDylibDepInfo
>;
104 } // anonymous namespace
108 using SPSMachOObjectPlatformSectionsMap
=
109 SPSSequence
<SPSTuple
<SPSString
, SPSExecutorAddrRange
>>;
111 using SPSMachOJITDylibDepInfo
= SPSTuple
<bool, SPSSequence
<SPSExecutorAddr
>>;
113 using SPSMachOJITDylibDepInfoMap
=
114 SPSSequence
<SPSTuple
<SPSExecutorAddr
, SPSMachOJITDylibDepInfo
>>;
117 class SPSSerializationTraits
<SPSMachOJITDylibDepInfo
, MachOJITDylibDepInfo
> {
119 static size_t size(const MachOJITDylibDepInfo
&JDI
) {
120 return SPSMachOJITDylibDepInfo::AsArgList::size(JDI
.Sealed
, JDI
.DepHeaders
);
123 static bool serialize(SPSOutputBuffer
&OB
, const MachOJITDylibDepInfo
&JDI
) {
124 return SPSMachOJITDylibDepInfo::AsArgList::serialize(OB
, JDI
.Sealed
,
128 static bool deserialize(SPSInputBuffer
&IB
, MachOJITDylibDepInfo
&JDI
) {
129 return SPSMachOJITDylibDepInfo::AsArgList::deserialize(IB
, JDI
.Sealed
,
134 struct UnwindSectionInfo
{
135 std::vector
<ExecutorAddrRange
> CodeRanges
;
136 ExecutorAddrRange DwarfSection
;
137 ExecutorAddrRange CompactUnwindSection
;
140 using SPSUnwindSectionInfo
=
141 SPSTuple
<SPSSequence
<SPSExecutorAddrRange
>, SPSExecutorAddrRange
,
142 SPSExecutorAddrRange
>;
145 class SPSSerializationTraits
<SPSUnwindSectionInfo
, UnwindSectionInfo
> {
147 static size_t size(const UnwindSectionInfo
&USI
) {
148 return SPSUnwindSectionInfo::AsArgList::size(
149 USI
.CodeRanges
, USI
.DwarfSection
, USI
.CompactUnwindSection
);
152 static bool serialize(SPSOutputBuffer
&OB
, const UnwindSectionInfo
&USI
) {
153 return SPSUnwindSectionInfo::AsArgList::serialize(
154 OB
, USI
.CodeRanges
, USI
.DwarfSection
, USI
.CompactUnwindSection
);
157 static bool deserialize(SPSInputBuffer
&IB
, UnwindSectionInfo
&USI
) {
158 return SPSUnwindSectionInfo::AsArgList::deserialize(
159 IB
, USI
.CodeRanges
, USI
.DwarfSection
, USI
.CompactUnwindSection
);
163 } // namespace __orc_rt
166 struct TLVDescriptor
{
167 void *(*Thunk
)(TLVDescriptor
*) = nullptr;
168 unsigned long Key
= 0;
169 unsigned long DataAddress
= 0;
172 class MachOPlatformRuntimeState
{
175 void (*Func
)(void *);
179 using AtExitsVector
= std::vector
<AtExitEntry
>;
181 /// Used to manage sections of fixed-sized metadata records (e.g. pointer
182 /// sections, selector refs, etc.)
183 template <typename RecordElement
> class RecordSectionsTracker
{
185 /// Add a section to the "new" list.
186 void add(span
<RecordElement
> Sec
) { New
.push_back(std::move(Sec
)); }
188 /// Returns true if there are new sections to process.
189 bool hasNewSections() const { return !New
.empty(); }
191 /// Returns the number of new sections to process.
192 size_t numNewSections() const { return New
.size(); }
194 /// Process all new sections.
195 template <typename ProcessSectionFunc
>
196 std::enable_if_t
<std::is_void_v
<
197 std::invoke_result_t
<ProcessSectionFunc
, span
<RecordElement
>>>>
198 processNewSections(ProcessSectionFunc
&&ProcessSection
) {
199 for (auto &Sec
: New
)
201 moveNewToProcessed();
204 /// Proces all new sections with a fallible handler.
206 /// Successfully handled sections will be moved to the Processed
208 template <typename ProcessSectionFunc
>
210 std::is_same_v
<Error
, std::invoke_result_t
<ProcessSectionFunc
,
211 span
<RecordElement
>>>,
213 processNewSections(ProcessSectionFunc
&&ProcessSection
) {
214 for (size_t I
= 0; I
!= New
.size(); ++I
) {
215 if (auto Err
= ProcessSection(New
[I
])) {
216 for (size_t J
= 0; J
!= I
; ++J
)
217 Processed
.push_back(New
[J
]);
218 New
.erase(New
.begin(), New
.begin() + I
);
222 moveNewToProcessed();
223 return Error::success();
226 /// Move all sections back to New for reprocessing.
228 moveNewToProcessed();
229 New
= std::move(Processed
);
232 /// Remove the section with the given range.
233 bool removeIfPresent(ExecutorAddrRange R
) {
234 if (removeIfPresent(New
, R
))
236 return removeIfPresent(Processed
, R
);
240 void moveNewToProcessed() {
241 if (Processed
.empty())
242 Processed
= std::move(New
);
244 Processed
.reserve(Processed
.size() + New
.size());
245 std::copy(New
.begin(), New
.end(), std::back_inserter(Processed
));
250 bool removeIfPresent(std::vector
<span
<RecordElement
>> &V
,
251 ExecutorAddrRange R
) {
252 auto RI
= std::find_if(
253 V
.rbegin(), V
.rend(),
254 [RS
= R
.toSpan
<RecordElement
>()](const span
<RecordElement
> &E
) {
255 return E
.data() == RS
.data();
257 if (RI
!= V
.rend()) {
258 V
.erase(std::next(RI
).base());
264 std::vector
<span
<RecordElement
>> Processed
;
265 std::vector
<span
<RecordElement
>> New
;
268 struct UnwindSections
{
269 UnwindSections(const UnwindSectionInfo
&USI
)
270 : DwarfSection(USI
.DwarfSection
.toSpan
<char>()),
271 CompactUnwindSection(USI
.CompactUnwindSection
.toSpan
<char>()) {}
273 span
<char> DwarfSection
;
274 span
<char> CompactUnwindSection
;
277 using UnwindSectionsMap
=
278 IntervalMap
<char *, UnwindSections
, IntervalCoalescing::Disabled
>;
280 struct JITDylibState
{
282 void *Header
= nullptr;
284 size_t LinkedAgainstRefCount
= 0;
285 size_t DlRefCount
= 0;
286 std::vector
<JITDylibState
*> Deps
;
287 AtExitsVector AtExits
;
288 const objc_image_info
*ObjCImageInfo
= nullptr;
289 std::unordered_map
<void *, std::vector
<char>> DataSectionContent
;
290 std::unordered_map
<void *, size_t> ZeroInitRanges
;
291 UnwindSectionsMap UnwindSections
;
292 RecordSectionsTracker
<void (*)()> ModInitsSections
;
293 RecordSectionsTracker
<void *> ObjCClassListSections
;
294 RecordSectionsTracker
<void *> ObjCSelRefsSections
;
295 RecordSectionsTracker
<char> Swift5ProtocolsSections
;
296 RecordSectionsTracker
<char> Swift5ProtocolConformancesSections
;
297 RecordSectionsTracker
<char> Swift5TypesSections
;
299 bool referenced() const {
300 return LinkedAgainstRefCount
!= 0 || DlRefCount
!= 0;
305 static Error
create();
306 static MachOPlatformRuntimeState
&get();
307 static Error
destroy();
309 MachOPlatformRuntimeState() = default;
311 // Delete copy and move constructors.
312 MachOPlatformRuntimeState(const MachOPlatformRuntimeState
&) = delete;
313 MachOPlatformRuntimeState
&
314 operator=(const MachOPlatformRuntimeState
&) = delete;
315 MachOPlatformRuntimeState(MachOPlatformRuntimeState
&&) = delete;
316 MachOPlatformRuntimeState
&operator=(MachOPlatformRuntimeState
&&) = delete;
321 Error
registerJITDylib(std::string Name
, void *Header
);
322 Error
deregisterJITDylib(void *Header
);
323 Error
registerThreadDataSection(span
<const char> ThreadDataSection
);
324 Error
deregisterThreadDataSection(span
<const char> ThreadDataSection
);
325 Error
registerObjectPlatformSections(
326 ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> UnwindSections
,
327 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>> Secs
);
328 Error
deregisterObjectPlatformSections(
329 ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> UnwindSections
,
330 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>> Secs
);
332 const char *dlerror();
333 void *dlopen(std::string_view Name
, int Mode
);
334 int dlclose(void *DSOHandle
);
335 void *dlsym(void *DSOHandle
, std::string_view Symbol
);
337 int registerAtExit(void (*F
)(void *), void *Arg
, void *DSOHandle
);
338 void runAtExits(std::unique_lock
<std::mutex
> &JDStatesLock
,
340 void runAtExits(void *DSOHandle
);
342 /// Returns the base address of the section containing ThreadData.
343 Expected
<std::pair
<const char *, size_t>>
344 getThreadDataSectionFor(const char *ThreadData
);
347 JITDylibState
*getJITDylibStateByHeader(void *DSOHandle
);
348 JITDylibState
*getJITDylibStateByName(std::string_view Path
);
350 Expected
<ExecutorAddr
> lookupSymbolInJITDylib(void *DSOHandle
,
351 std::string_view Symbol
);
353 bool lookupUnwindSections(void *Addr
, unw_dynamic_unwind_sections
&Info
);
355 static int findDynamicUnwindSections(uintptr_t addr
,
356 unw_dynamic_unwind_sections
*info
);
357 static Error
registerEHFrames(span
<const char> EHFrameSection
);
358 static Error
deregisterEHFrames(span
<const char> EHFrameSection
);
360 static Error
registerObjCSelectors(JITDylibState
&JDS
);
361 static Error
registerObjCClasses(JITDylibState
&JDS
);
362 static Error
registerSwift5Protocols(JITDylibState
&JDS
);
363 static Error
registerSwift5ProtocolConformances(JITDylibState
&JDS
);
364 static Error
registerSwift5Types(JITDylibState
&JDS
);
365 static Error
runModInits(std::unique_lock
<std::mutex
> &JDStatesLock
,
368 Expected
<void *> dlopenImpl(std::string_view Path
, int Mode
);
369 Error
dlopenFull(std::unique_lock
<std::mutex
> &JDStatesLock
,
371 Error
dlopenInitialize(std::unique_lock
<std::mutex
> &JDStatesLock
,
372 JITDylibState
&JDS
, MachOJITDylibDepInfoMap
&DepInfo
);
374 Error
dlcloseImpl(void *DSOHandle
);
375 Error
dlcloseDeinitialize(std::unique_lock
<std::mutex
> &JDStatesLock
,
378 static MachOPlatformRuntimeState
*MOPS
;
380 bool UseCallbackStyleUnwindInfo
= false;
382 // FIXME: Move to thread-state.
383 std::string DLFcnError
;
385 // APIMutex guards against concurrent entry into key "dyld" API functions
386 // (e.g. dlopen, dlclose).
387 std::recursive_mutex DyldAPIMutex
;
389 // JDStatesMutex guards the data structures that hold JITDylib state.
390 std::mutex JDStatesMutex
;
391 std::unordered_map
<void *, JITDylibState
> JDStates
;
392 std::unordered_map
<std::string_view
, void *> JDNameToHeader
;
394 // ThreadDataSectionsMutex guards thread local data section state.
395 std::mutex ThreadDataSectionsMutex
;
396 std::map
<const char *, size_t> ThreadDataSections
;
399 MachOPlatformRuntimeState
*MachOPlatformRuntimeState::MOPS
= nullptr;
401 Error
MachOPlatformRuntimeState::create() {
402 assert(!MOPS
&& "MachOPlatformRuntimeState should be null");
403 MOPS
= new MachOPlatformRuntimeState();
404 return MOPS
->initialize();
407 MachOPlatformRuntimeState
&MachOPlatformRuntimeState::get() {
408 assert(MOPS
&& "MachOPlatformRuntimeState not initialized");
412 Error
MachOPlatformRuntimeState::destroy() {
413 assert(MOPS
&& "MachOPlatformRuntimeState not initialized");
414 auto Err
= MOPS
->shutdown();
419 Error
MachOPlatformRuntimeState::initialize() {
420 UseCallbackStyleUnwindInfo
= __unw_add_find_dynamic_unwind_sections
&&
421 __unw_remove_find_dynamic_unwind_sections
;
422 if (UseCallbackStyleUnwindInfo
) {
424 printdbg("__unw_add/remove_find_dynamic_unwind_sections available."
425 " Using callback-based frame info lookup.\n");
427 if (__unw_add_find_dynamic_unwind_sections(&findDynamicUnwindSections
))
428 return make_error
<StringError
>(
429 "Could not register findDynamicUnwindSections");
432 printdbg("__unw_add/remove_find_dynamic_unwind_sections not available."
433 " Using classic frame info registration.\n");
436 return Error::success();
439 Error
MachOPlatformRuntimeState::shutdown() {
440 if (__unw_add_find_dynamic_unwind_sections
&&
441 __unw_remove_find_dynamic_unwind_sections
) {
442 if (__unw_remove_find_dynamic_unwind_sections(&findDynamicUnwindSections
)) {
444 { printdbg("__unw_remove_find_dynamic_unwind_sections failed.\n"); });
447 return Error::success();
450 Error
MachOPlatformRuntimeState::registerJITDylib(std::string Name
,
453 printdbg("Registering JITDylib %s: Header = %p\n", Name
.c_str(), Header
);
455 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
456 if (JDStates
.count(Header
)) {
457 std::ostringstream ErrStream
;
458 ErrStream
<< "Duplicate JITDylib registration for header " << Header
459 << " (name = " << Name
<< ")";
460 return make_error
<StringError
>(ErrStream
.str());
462 if (JDNameToHeader
.count(Name
)) {
463 std::ostringstream ErrStream
;
464 ErrStream
<< "Duplicate JITDylib registration for header " << Header
465 << " (header = " << Header
<< ")";
466 return make_error
<StringError
>(ErrStream
.str());
469 auto &JDS
= JDStates
[Header
];
470 JDS
.Name
= std::move(Name
);
472 JDNameToHeader
[JDS
.Name
] = Header
;
473 return Error::success();
476 Error
MachOPlatformRuntimeState::deregisterJITDylib(void *Header
) {
477 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
478 auto I
= JDStates
.find(Header
);
479 if (I
== JDStates
.end()) {
480 std::ostringstream ErrStream
;
481 ErrStream
<< "Attempted to deregister unrecognized header " << Header
;
482 return make_error
<StringError
>(ErrStream
.str());
485 // Remove std::string construction once we can use C++20.
486 auto J
= JDNameToHeader
.find(
487 std::string(I
->second
.Name
.data(), I
->second
.Name
.size()));
488 assert(J
!= JDNameToHeader
.end() &&
489 "Missing JDNameToHeader entry for JITDylib");
492 printdbg("Deregistering JITDylib %s: Header = %p\n", I
->second
.Name
.c_str(),
496 JDNameToHeader
.erase(J
);
498 return Error::success();
501 Error
MachOPlatformRuntimeState::registerThreadDataSection(
502 span
<const char> ThreadDataSection
) {
503 std::lock_guard
<std::mutex
> Lock(ThreadDataSectionsMutex
);
504 auto I
= ThreadDataSections
.upper_bound(ThreadDataSection
.data());
505 if (I
!= ThreadDataSections
.begin()) {
506 auto J
= std::prev(I
);
507 if (J
->first
+ J
->second
> ThreadDataSection
.data())
508 return make_error
<StringError
>("Overlapping __thread_data sections");
510 ThreadDataSections
.insert(
511 I
, std::make_pair(ThreadDataSection
.data(), ThreadDataSection
.size()));
512 return Error::success();
515 Error
MachOPlatformRuntimeState::deregisterThreadDataSection(
516 span
<const char> ThreadDataSection
) {
517 std::lock_guard
<std::mutex
> Lock(ThreadDataSectionsMutex
);
518 auto I
= ThreadDataSections
.find(ThreadDataSection
.data());
519 if (I
== ThreadDataSections
.end())
520 return make_error
<StringError
>("Attempt to deregister unknown thread data "
522 ThreadDataSections
.erase(I
);
523 return Error::success();
526 Error
MachOPlatformRuntimeState::registerObjectPlatformSections(
527 ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> UnwindInfo
,
528 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>> Secs
) {
530 // FIXME: Reject platform section registration after the JITDylib is
534 printdbg("MachOPlatform: Registering object sections for %p.\n",
535 HeaderAddr
.toPtr
<void *>());
538 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
539 auto *JDS
= getJITDylibStateByHeader(HeaderAddr
.toPtr
<void *>());
541 std::ostringstream ErrStream
;
542 ErrStream
<< "Could not register object platform sections for "
543 "unrecognized header "
544 << HeaderAddr
.toPtr
<void *>();
545 return make_error
<StringError
>(ErrStream
.str());
548 if (UnwindInfo
&& UseCallbackStyleUnwindInfo
) {
550 printdbg(" Registering new-style unwind info for:\n"
552 " Compact-unwind: %p -- %p\n"
554 UnwindInfo
->DwarfSection
.Start
.toPtr
<void *>(),
555 UnwindInfo
->DwarfSection
.End
.toPtr
<void *>(),
556 UnwindInfo
->CompactUnwindSection
.Start
.toPtr
<void *>(),
557 UnwindInfo
->CompactUnwindSection
.End
.toPtr
<void *>());
559 for (auto &CodeRange
: UnwindInfo
->CodeRanges
) {
560 JDS
->UnwindSections
.insert(CodeRange
.Start
.toPtr
<char *>(),
561 CodeRange
.End
.toPtr
<char *>(), *UnwindInfo
);
563 printdbg(" [ %p -- %p ]\n", CodeRange
.Start
.toPtr
<void *>(),
564 CodeRange
.End
.toPtr
<void *>());
569 for (auto &KV
: Secs
) {
570 // FIXME: Validate section ranges?
571 if (KV
.first
== "__TEXT,__eh_frame") {
572 if (!UseCallbackStyleUnwindInfo
) {
573 // Use classic libunwind registration.
574 if (auto Err
= registerEHFrames(KV
.second
.toSpan
<const char>()))
577 } else if (KV
.first
== "__DATA,__data") {
578 assert(!JDS
->DataSectionContent
.count(KV
.second
.Start
.toPtr
<char *>()) &&
579 "Address already registered.");
580 auto S
= KV
.second
.toSpan
<char>();
581 JDS
->DataSectionContent
[KV
.second
.Start
.toPtr
<char *>()] =
582 std::vector
<char>(S
.begin(), S
.end());
583 } else if (KV
.first
== "__DATA,__common") {
584 // fprintf(stderr, "Adding zero-init range %llx -- %llx\n",
585 // KV.second.Start.getValue(), KV.second.size());
586 JDS
->ZeroInitRanges
[KV
.second
.Start
.toPtr
<char *>()] = KV
.second
.size();
587 } else if (KV
.first
== "__DATA,__thread_data") {
588 if (auto Err
= registerThreadDataSection(KV
.second
.toSpan
<const char>()))
590 } else if (KV
.first
== "__DATA,__objc_selrefs")
591 JDS
->ObjCSelRefsSections
.add(KV
.second
.toSpan
<void *>());
592 else if (KV
.first
== "__DATA,__objc_classlist")
593 JDS
->ObjCClassListSections
.add(KV
.second
.toSpan
<void *>());
594 else if (KV
.first
== "__TEXT,__swift5_protos")
595 JDS
->Swift5ProtocolsSections
.add(KV
.second
.toSpan
<char>());
596 else if (KV
.first
== "__TEXT,__swift5_proto")
597 JDS
->Swift5ProtocolConformancesSections
.add(KV
.second
.toSpan
<char>());
598 else if (KV
.first
== "__TEXT,__swift5_types")
599 JDS
->Swift5TypesSections
.add(KV
.second
.toSpan
<char>());
600 else if (KV
.first
== "__DATA,__mod_init_func")
601 JDS
->ModInitsSections
.add(KV
.second
.toSpan
<void (*)()>());
603 // Should this be a warning instead?
604 return make_error
<StringError
>(
605 "Encountered unexpected section " +
606 std::string(KV
.first
.data(), KV
.first
.size()) +
607 " while registering object platform sections");
611 return Error::success();
614 Error
MachOPlatformRuntimeState::deregisterObjectPlatformSections(
615 ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> UnwindInfo
,
616 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>> Secs
) {
617 // TODO: Make this more efficient? (maybe unnecessary if removal is rare?)
618 // TODO: Add a JITDylib prepare-for-teardown operation that clears all
619 // registered sections, causing this function to take the fast-path.
621 printdbg("MachOPlatform: Registering object sections for %p.\n",
622 HeaderAddr
.toPtr
<void *>());
625 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
626 auto *JDS
= getJITDylibStateByHeader(HeaderAddr
.toPtr
<void *>());
628 std::ostringstream ErrStream
;
629 ErrStream
<< "Could not register object platform sections for unrecognized "
631 << HeaderAddr
.toPtr
<void *>();
632 return make_error
<StringError
>(ErrStream
.str());
635 // FIXME: Implement faster-path by returning immediately if JDS is being
636 // torn down entirely?
638 // TODO: Make library permanent (i.e. not able to be dlclosed) if it contains
639 // any Swift or ObjC. Once this happens we can clear (and no longer record)
640 // data section content, as the library could never be re-initialized.
642 if (UnwindInfo
&& UseCallbackStyleUnwindInfo
) {
644 printdbg(" Deregistering new-style unwind info for:\n"
646 " Compact-unwind: %p -- %p\n"
648 UnwindInfo
->DwarfSection
.Start
.toPtr
<void *>(),
649 UnwindInfo
->DwarfSection
.End
.toPtr
<void *>(),
650 UnwindInfo
->CompactUnwindSection
.Start
.toPtr
<void *>(),
651 UnwindInfo
->CompactUnwindSection
.End
.toPtr
<void *>());
653 for (auto &CodeRange
: UnwindInfo
->CodeRanges
) {
654 JDS
->UnwindSections
.erase(CodeRange
.Start
.toPtr
<char *>(),
655 CodeRange
.End
.toPtr
<char *>());
657 printdbg(" [ %p -- %p ]\n", CodeRange
.Start
.toPtr
<void *>(),
658 CodeRange
.End
.toPtr
<void *>());
663 for (auto &KV
: Secs
) {
664 // FIXME: Validate section ranges?
665 if (KV
.first
== "__TEXT,__eh_frame") {
666 if (!UseCallbackStyleUnwindInfo
) {
667 // Use classic libunwind registration.
668 if (auto Err
= deregisterEHFrames(KV
.second
.toSpan
<const char>()))
671 } else if (KV
.first
== "__DATA,__data") {
672 JDS
->DataSectionContent
.erase(KV
.second
.Start
.toPtr
<char *>());
673 } else if (KV
.first
== "__DATA,__common") {
674 JDS
->ZeroInitRanges
.erase(KV
.second
.Start
.toPtr
<char *>());
675 } else if (KV
.first
== "__DATA,__thread_data") {
677 deregisterThreadDataSection(KV
.second
.toSpan
<const char>()))
679 } else if (KV
.first
== "__DATA,__objc_selrefs")
680 JDS
->ObjCSelRefsSections
.removeIfPresent(KV
.second
);
681 else if (KV
.first
== "__DATA,__objc_classlist")
682 JDS
->ObjCClassListSections
.removeIfPresent(KV
.second
);
683 else if (KV
.first
== "__TEXT,__swift5_protos")
684 JDS
->Swift5ProtocolsSections
.removeIfPresent(KV
.second
);
685 else if (KV
.first
== "__TEXT,__swift5_proto")
686 JDS
->Swift5ProtocolConformancesSections
.removeIfPresent(KV
.second
);
687 else if (KV
.first
== "__TEXT,__swift5_types")
688 JDS
->Swift5TypesSections
.removeIfPresent(KV
.second
);
689 else if (KV
.first
== "__DATA,__mod_init_func")
690 JDS
->ModInitsSections
.removeIfPresent(KV
.second
);
692 // Should this be a warning instead?
693 return make_error
<StringError
>(
694 "Encountered unexpected section " +
695 std::string(KV
.first
.data(), KV
.first
.size()) +
696 " while deregistering object platform sections");
699 return Error::success();
702 const char *MachOPlatformRuntimeState::dlerror() { return DLFcnError
.c_str(); }
704 void *MachOPlatformRuntimeState::dlopen(std::string_view Path
, int Mode
) {
706 std::string
S(Path
.data(), Path
.size());
707 printdbg("MachOPlatform::dlopen(\"%s\")\n", S
.c_str());
709 std::lock_guard
<std::recursive_mutex
> Lock(DyldAPIMutex
);
710 if (auto H
= dlopenImpl(Path
, Mode
))
713 // FIXME: Make dlerror thread safe.
714 DLFcnError
= toString(H
.takeError());
719 int MachOPlatformRuntimeState::dlclose(void *DSOHandle
) {
721 auto *JDS
= getJITDylibStateByHeader(DSOHandle
);
722 std::string DylibName
;
725 printdbg("MachOPlatform::dlclose(%p) (%s)\n", DSOHandle
, S
.c_str());
727 printdbg("MachOPlatform::dlclose(%p) (%s)\n", DSOHandle
,
730 std::lock_guard
<std::recursive_mutex
> Lock(DyldAPIMutex
);
731 if (auto Err
= dlcloseImpl(DSOHandle
)) {
732 // FIXME: Make dlerror thread safe.
733 DLFcnError
= toString(std::move(Err
));
739 void *MachOPlatformRuntimeState::dlsym(void *DSOHandle
,
740 std::string_view Symbol
) {
741 auto Addr
= lookupSymbolInJITDylib(DSOHandle
, Symbol
);
743 DLFcnError
= toString(Addr
.takeError());
747 return Addr
->toPtr
<void *>();
750 int MachOPlatformRuntimeState::registerAtExit(void (*F
)(void *), void *Arg
,
752 // FIXME: Handle out-of-memory errors, returning -1 if OOM.
753 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
754 auto *JDS
= getJITDylibStateByHeader(DSOHandle
);
757 printdbg("MachOPlatformRuntimeState::registerAtExit called with "
758 "unrecognized dso handle %p\n",
763 JDS
->AtExits
.push_back({F
, Arg
});
767 void MachOPlatformRuntimeState::runAtExits(
768 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
) {
769 auto AtExits
= std::move(JDS
.AtExits
);
771 // Unlock while running atexits, as they may trigger operations that modify
773 JDStatesLock
.unlock();
774 while (!AtExits
.empty()) {
775 auto &AE
= AtExits
.back();
782 void MachOPlatformRuntimeState::runAtExits(void *DSOHandle
) {
783 std::unique_lock
<std::mutex
> Lock(JDStatesMutex
);
784 auto *JDS
= getJITDylibStateByHeader(DSOHandle
);
786 printdbg("MachOPlatformRuntimeState::runAtExits called on unrecognized "
791 runAtExits(Lock
, *JDS
);
794 Expected
<std::pair
<const char *, size_t>>
795 MachOPlatformRuntimeState::getThreadDataSectionFor(const char *ThreadData
) {
796 std::lock_guard
<std::mutex
> Lock(ThreadDataSectionsMutex
);
797 auto I
= ThreadDataSections
.upper_bound(ThreadData
);
798 // Check that we have a valid entry covering this address.
799 if (I
== ThreadDataSections
.begin())
800 return make_error
<StringError
>("No thread local data section for key");
802 if (ThreadData
>= I
->first
+ I
->second
)
803 return make_error
<StringError
>("No thread local data section for key");
807 MachOPlatformRuntimeState::JITDylibState
*
808 MachOPlatformRuntimeState::getJITDylibStateByHeader(void *DSOHandle
) {
809 auto I
= JDStates
.find(DSOHandle
);
810 if (I
== JDStates
.end()) {
811 I
= JDStates
.insert(std::make_pair(DSOHandle
, JITDylibState())).first
;
812 I
->second
.Header
= DSOHandle
;
817 MachOPlatformRuntimeState::JITDylibState
*
818 MachOPlatformRuntimeState::getJITDylibStateByName(std::string_view Name
) {
819 // FIXME: Avoid creating string once we have C++20.
820 auto I
= JDNameToHeader
.find(std::string(Name
.data(), Name
.size()));
821 if (I
!= JDNameToHeader
.end())
822 return getJITDylibStateByHeader(I
->second
);
826 Expected
<ExecutorAddr
>
827 MachOPlatformRuntimeState::lookupSymbolInJITDylib(void *DSOHandle
,
828 std::string_view Sym
) {
829 Expected
<ExecutorAddr
> Result((ExecutorAddr()));
830 if (auto Err
= WrapperFunction
<SPSExpected
<SPSExecutorAddr
>(
831 SPSExecutorAddr
, SPSString
)>::call(&__orc_rt_macho_symbol_lookup_tag
,
833 ExecutorAddr::fromPtr(DSOHandle
),
835 return std::move(Err
);
839 // eh-frame registration functions.
840 // We expect these to be available for all processes.
841 extern "C" void __register_frame(const void *);
842 extern "C" void __deregister_frame(const void *);
844 template <typename HandleFDEFn
>
845 void walkEHFrameSection(span
<const char> EHFrameSection
,
846 HandleFDEFn HandleFDE
) {
847 const char *CurCFIRecord
= EHFrameSection
.data();
848 uint64_t Size
= *reinterpret_cast<const uint32_t *>(CurCFIRecord
);
850 while (CurCFIRecord
!= EHFrameSection
.end() && Size
!= 0) {
851 const char *OffsetField
= CurCFIRecord
+ (Size
== 0xffffffff ? 12 : 4);
852 if (Size
== 0xffffffff)
853 Size
= *reinterpret_cast<const uint64_t *>(CurCFIRecord
+ 4) + 12;
856 uint32_t Offset
= *reinterpret_cast<const uint32_t *>(OffsetField
);
859 HandleFDE(CurCFIRecord
);
861 CurCFIRecord
+= Size
;
862 Size
= *reinterpret_cast<const uint32_t *>(CurCFIRecord
);
866 bool MachOPlatformRuntimeState::lookupUnwindSections(
867 void *Addr
, unw_dynamic_unwind_sections
&Info
) {
869 { printdbg("Tried to lookup unwind-info via new lookup call.\n"); });
870 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
871 for (auto &KV
: JDStates
) {
872 auto &JD
= KV
.second
;
873 auto I
= JD
.UnwindSections
.find(reinterpret_cast<char *>(Addr
));
874 if (I
!= JD
.UnwindSections
.end()) {
875 Info
.dso_base
= reinterpret_cast<uintptr_t>(JD
.Header
);
877 reinterpret_cast<uintptr_t>(I
->second
.DwarfSection
.data());
878 Info
.dwarf_section_length
= I
->second
.DwarfSection
.size();
879 Info
.compact_unwind_section
=
880 reinterpret_cast<uintptr_t>(I
->second
.CompactUnwindSection
.data());
881 Info
.compact_unwind_section_length
=
882 I
->second
.CompactUnwindSection
.size();
889 int MachOPlatformRuntimeState::findDynamicUnwindSections(
890 uintptr_t addr
, unw_dynamic_unwind_sections
*info
) {
893 return MachOPlatformRuntimeState::get().lookupUnwindSections((void *)addr
,
897 Error
MachOPlatformRuntimeState::registerEHFrames(
898 span
<const char> EHFrameSection
) {
899 walkEHFrameSection(EHFrameSection
, __register_frame
);
900 return Error::success();
903 Error
MachOPlatformRuntimeState::deregisterEHFrames(
904 span
<const char> EHFrameSection
) {
905 walkEHFrameSection(EHFrameSection
, __deregister_frame
);
906 return Error::success();
909 Error
MachOPlatformRuntimeState::registerObjCSelectors(JITDylibState
&JDS
) {
910 if (!JDS
.ObjCSelRefsSections
.hasNewSections())
911 return Error::success();
913 if (ORC_RT_UNLIKELY(!sel_registerName
))
914 return make_error
<StringError
>("sel_registerName is not available");
916 JDS
.ObjCSelRefsSections
.processNewSections([](span
<void *> SelRefs
) {
917 for (void *&SelEntry
: SelRefs
) {
918 const char *SelName
= reinterpret_cast<const char *>(SelEntry
);
919 auto Sel
= sel_registerName(SelName
);
920 *reinterpret_cast<SEL
*>(&SelEntry
) = Sel
;
924 return Error::success();
927 Error
MachOPlatformRuntimeState::registerObjCClasses(JITDylibState
&JDS
) {
928 if (!JDS
.ObjCClassListSections
.hasNewSections())
929 return Error::success();
931 if (ORC_RT_UNLIKELY(!objc_msgSend
))
932 return make_error
<StringError
>("objc_msgSend is not available");
933 if (ORC_RT_UNLIKELY(!objc_readClassPair
))
934 return make_error
<StringError
>("objc_readClassPair is not available");
936 struct ObjCClassCompiled
{
944 auto ClassSelector
= sel_registerName("class");
946 return JDS
.ObjCClassListSections
.processNewSections(
947 [&](span
<void *> ClassPtrs
) -> Error
{
948 for (void *ClassPtr
: ClassPtrs
) {
949 auto *Cls
= reinterpret_cast<Class
>(ClassPtr
);
950 auto *ClassCompiled
= reinterpret_cast<ObjCClassCompiled
*>(ClassPtr
);
951 objc_msgSend(reinterpret_cast<id
>(ClassCompiled
->Parent
),
953 auto Registered
= objc_readClassPair(Cls
, JDS
.ObjCImageInfo
);
954 // FIXME: Improve diagnostic by reporting the failed class's name.
955 if (Registered
!= Cls
)
956 return make_error
<StringError
>(
957 "Unable to register Objective-C class");
959 return Error::success();
963 Error
MachOPlatformRuntimeState::registerSwift5Protocols(JITDylibState
&JDS
) {
965 if (!JDS
.Swift5ProtocolsSections
.hasNewSections())
966 return Error::success();
968 if (ORC_RT_UNLIKELY(!swift_registerProtocols
))
969 return make_error
<StringError
>("swift_registerProtocols is not available");
971 JDS
.Swift5ProtocolsSections
.processNewSections([](span
<char> ProtoSec
) {
972 swift_registerProtocols(
973 reinterpret_cast<const ProtocolRecord
*>(ProtoSec
.data()),
974 reinterpret_cast<const ProtocolRecord
*>(ProtoSec
.data() +
978 return Error::success();
981 Error
MachOPlatformRuntimeState::registerSwift5ProtocolConformances(
982 JITDylibState
&JDS
) {
984 if (!JDS
.Swift5ProtocolConformancesSections
.hasNewSections())
985 return Error::success();
987 if (ORC_RT_UNLIKELY(!swift_registerProtocolConformances
))
988 return make_error
<StringError
>(
989 "swift_registerProtocolConformances is not available");
991 JDS
.Swift5ProtocolConformancesSections
.processNewSections(
992 [](span
<char> ProtoConfSec
) {
993 swift_registerProtocolConformances(
994 reinterpret_cast<const ProtocolConformanceRecord
*>(
995 ProtoConfSec
.data()),
996 reinterpret_cast<const ProtocolConformanceRecord
*>(
997 ProtoConfSec
.data() + ProtoConfSec
.size()));
1000 return Error::success();
1003 Error
MachOPlatformRuntimeState::registerSwift5Types(JITDylibState
&JDS
) {
1005 if (!JDS
.Swift5TypesSections
.hasNewSections())
1006 return Error::success();
1008 if (ORC_RT_UNLIKELY(!swift_registerTypeMetadataRecords
))
1009 return make_error
<StringError
>(
1010 "swift_registerTypeMetadataRecords is not available");
1012 JDS
.Swift5TypesSections
.processNewSections([&](span
<char> TypesSec
) {
1013 swift_registerTypeMetadataRecords(
1014 reinterpret_cast<const TypeMetadataRecord
*>(TypesSec
.data()),
1015 reinterpret_cast<const TypeMetadataRecord
*>(TypesSec
.data() +
1019 return Error::success();
1022 Error
MachOPlatformRuntimeState::runModInits(
1023 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
) {
1024 std::vector
<span
<void (*)()>> InitSections
;
1025 InitSections
.reserve(JDS
.ModInitsSections
.numNewSections());
1027 // Copy initializer sections: If the JITDylib is unsealed then the
1028 // initializers could reach back into the JIT and cause more initializers to
1030 // FIXME: Skip unlock and run in-place on sealed JITDylibs?
1031 JDS
.ModInitsSections
.processNewSections(
1032 [&](span
<void (*)()> Inits
) { InitSections
.push_back(Inits
); });
1034 JDStatesLock
.unlock();
1035 for (auto InitSec
: InitSections
)
1036 for (auto *Init
: InitSec
)
1038 JDStatesLock
.lock();
1040 return Error::success();
1043 Expected
<void *> MachOPlatformRuntimeState::dlopenImpl(std::string_view Path
,
1045 std::unique_lock
<std::mutex
> Lock(JDStatesMutex
);
1047 // Try to find JITDylib state by name.
1048 auto *JDS
= getJITDylibStateByName(Path
);
1051 return make_error
<StringError
>("No registered JTIDylib for path " +
1052 std::string(Path
.data(), Path
.size()));
1054 // If this JITDylib is unsealed, or this is the first dlopen then run
1055 // full dlopen path (update deps, push and run initializers, update ref
1056 // counts on all JITDylibs in the dep tree).
1057 if (!JDS
->referenced() || !JDS
->Sealed
) {
1058 if (auto Err
= dlopenFull(Lock
, *JDS
))
1059 return std::move(Err
);
1062 // Bump the ref-count on this dylib.
1065 // Return the header address.
1069 Error
MachOPlatformRuntimeState::dlopenFull(
1070 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
) {
1071 // Call back to the JIT to push the initializers.
1072 Expected
<MachOJITDylibDepInfoMap
> DepInfo((MachOJITDylibDepInfoMap()));
1073 // Unlock so that we can accept the initializer update.
1074 JDStatesLock
.unlock();
1075 if (auto Err
= WrapperFunction
<SPSExpected
<SPSMachOJITDylibDepInfoMap
>(
1076 SPSExecutorAddr
)>::call(&__orc_rt_macho_push_initializers_tag
,
1077 DepInfo
, ExecutorAddr::fromPtr(JDS
.Header
)))
1079 JDStatesLock
.lock();
1082 return DepInfo
.takeError();
1084 if (auto Err
= dlopenInitialize(JDStatesLock
, JDS
, *DepInfo
))
1087 if (!DepInfo
->empty()) {
1089 printdbg("Unrecognized dep-info key headers in dlopen of %s\n",
1092 std::ostringstream ErrStream
;
1093 ErrStream
<< "Encountered unrecognized dep-info key headers "
1094 "while processing dlopen of "
1096 return make_error
<StringError
>(ErrStream
.str());
1099 return Error::success();
1102 Error
MachOPlatformRuntimeState::dlopenInitialize(
1103 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
,
1104 MachOJITDylibDepInfoMap
&DepInfo
) {
1106 printdbg("MachOPlatformRuntimeState::dlopenInitialize(\"%s\")\n",
1110 // If the header is not present in the dep map then assume that we
1111 // already processed it earlier in the dlopenInitialize traversal and
1113 // TODO: Keep a visited set instead so that we can error out on missing
1115 auto I
= DepInfo
.find(ExecutorAddr::fromPtr(JDS
.Header
));
1116 if (I
== DepInfo
.end())
1117 return Error::success();
1119 auto DI
= std::move(I
->second
);
1122 // We don't need to re-initialize sealed JITDylibs that have already been
1123 // initialized. Just check that their dep-map entry is empty as expected.
1125 if (!DI
.DepHeaders
.empty()) {
1126 std::ostringstream ErrStream
;
1127 ErrStream
<< "Sealed JITDylib " << JDS
.Header
1128 << " already has registered dependencies";
1129 return make_error
<StringError
>(ErrStream
.str());
1131 if (JDS
.referenced())
1132 return Error::success();
1134 JDS
.Sealed
= DI
.Sealed
;
1136 // This is an unsealed or newly sealed JITDylib. Run initializers.
1137 std::vector
<JITDylibState
*> OldDeps
;
1138 std::swap(JDS
.Deps
, OldDeps
);
1139 JDS
.Deps
.reserve(DI
.DepHeaders
.size());
1140 for (auto DepHeaderAddr
: DI
.DepHeaders
) {
1141 auto *DepJDS
= getJITDylibStateByHeader(DepHeaderAddr
.toPtr
<void *>());
1143 std::ostringstream ErrStream
;
1144 ErrStream
<< "Encountered unrecognized dep header "
1145 << DepHeaderAddr
.toPtr
<void *>() << " while initializing "
1147 return make_error
<StringError
>(ErrStream
.str());
1149 ++DepJDS
->LinkedAgainstRefCount
;
1150 if (auto Err
= dlopenInitialize(JDStatesLock
, *DepJDS
, DepInfo
))
1154 // Initialize this JITDylib.
1155 if (auto Err
= registerObjCSelectors(JDS
))
1157 if (auto Err
= registerObjCClasses(JDS
))
1159 if (auto Err
= registerSwift5Protocols(JDS
))
1161 if (auto Err
= registerSwift5ProtocolConformances(JDS
))
1163 if (auto Err
= registerSwift5Types(JDS
))
1165 if (auto Err
= runModInits(JDStatesLock
, JDS
))
1168 // Decrement old deps.
1169 // FIXME: We should probably continue and just report deinitialize errors
1171 for (auto *DepJDS
: OldDeps
) {
1172 --DepJDS
->LinkedAgainstRefCount
;
1173 if (!DepJDS
->referenced())
1174 if (auto Err
= dlcloseDeinitialize(JDStatesLock
, *DepJDS
))
1178 return Error::success();
1181 Error
MachOPlatformRuntimeState::dlcloseImpl(void *DSOHandle
) {
1182 std::unique_lock
<std::mutex
> Lock(JDStatesMutex
);
1184 // Try to find JITDylib state by header.
1185 auto *JDS
= getJITDylibStateByHeader(DSOHandle
);
1188 std::ostringstream ErrStream
;
1189 ErrStream
<< "No registered JITDylib for " << DSOHandle
;
1190 return make_error
<StringError
>(ErrStream
.str());
1193 // Bump the ref-count.
1196 if (!JDS
->referenced())
1197 return dlcloseDeinitialize(Lock
, *JDS
);
1199 return Error::success();
1202 Error
MachOPlatformRuntimeState::dlcloseDeinitialize(
1203 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
) {
1206 printdbg("MachOPlatformRuntimeState::dlcloseDeinitialize(\"%s\")\n",
1210 runAtExits(JDStatesLock
, JDS
);
1213 JDS
.ModInitsSections
.reset();
1215 // Reset data section contents.
1216 for (auto &KV
: JDS
.DataSectionContent
)
1217 memcpy(KV
.first
, KV
.second
.data(), KV
.second
.size());
1218 for (auto &KV
: JDS
.ZeroInitRanges
)
1219 memset(KV
.first
, 0, KV
.second
);
1221 // Deinitialize any dependencies.
1222 for (auto *DepJDS
: JDS
.Deps
) {
1223 --DepJDS
->LinkedAgainstRefCount
;
1224 if (!DepJDS
->referenced())
1225 if (auto Err
= dlcloseDeinitialize(JDStatesLock
, *DepJDS
))
1229 return Error::success();
1232 class MachOPlatformRuntimeTLVManager
{
1234 void *getInstance(const char *ThreadData
);
1237 std::unordered_map
<const char *, char *> Instances
;
1238 std::unordered_map
<const char *, std::unique_ptr
<char[]>> AllocatedSections
;
1241 void *MachOPlatformRuntimeTLVManager::getInstance(const char *ThreadData
) {
1242 auto I
= Instances
.find(ThreadData
);
1243 if (I
!= Instances
.end())
1247 MachOPlatformRuntimeState::get().getThreadDataSectionFor(ThreadData
);
1249 __orc_rt_log_error(toString(TDS
.takeError()).c_str());
1253 auto &Allocated
= AllocatedSections
[TDS
->first
];
1255 Allocated
= std::make_unique
<char[]>(TDS
->second
);
1256 memcpy(Allocated
.get(), TDS
->first
, TDS
->second
);
1259 size_t ThreadDataDelta
= ThreadData
- TDS
->first
;
1260 assert(ThreadDataDelta
<= TDS
->second
&& "ThreadData outside section bounds");
1262 char *Instance
= Allocated
.get() + ThreadDataDelta
;
1263 Instances
[ThreadData
] = Instance
;
1267 void destroyMachOTLVMgr(void *MachOTLVMgr
) {
1268 delete static_cast<MachOPlatformRuntimeTLVManager
*>(MachOTLVMgr
);
1271 Error
runWrapperFunctionCalls(std::vector
<WrapperFunctionCall
> WFCs
) {
1272 for (auto &WFC
: WFCs
)
1273 if (auto Err
= WFC
.runWithSPSRet
<void>())
1275 return Error::success();
1278 } // end anonymous namespace
1280 //------------------------------------------------------------------------------
1282 //------------------------------------------------------------------------------
1284 ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
1285 __orc_rt_macho_platform_bootstrap(char *ArgData
, size_t ArgSize
) {
1286 return WrapperFunction
<SPSError()>::handle(
1288 []() { return MachOPlatformRuntimeState::create(); })
1292 ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
1293 __orc_rt_macho_platform_shutdown(char *ArgData
, size_t ArgSize
) {
1294 return WrapperFunction
<SPSError()>::handle(
1296 []() { return MachOPlatformRuntimeState::destroy(); })
1300 ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
1301 __orc_rt_macho_register_jitdylib(char *ArgData
, size_t ArgSize
) {
1302 return WrapperFunction
<SPSError(SPSString
, SPSExecutorAddr
)>::handle(
1304 [](std::string
&Name
, ExecutorAddr HeaderAddr
) {
1305 return MachOPlatformRuntimeState::get().registerJITDylib(
1306 std::move(Name
), HeaderAddr
.toPtr
<void *>());
1311 ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
1312 __orc_rt_macho_deregister_jitdylib(char *ArgData
, size_t ArgSize
) {
1313 return WrapperFunction
<SPSError(SPSExecutorAddr
)>::handle(
1315 [](ExecutorAddr HeaderAddr
) {
1316 return MachOPlatformRuntimeState::get().deregisterJITDylib(
1317 HeaderAddr
.toPtr
<void *>());
1322 ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
1323 __orc_rt_macho_register_object_platform_sections(char *ArgData
,
1325 return WrapperFunction
<SPSError(SPSExecutorAddr
,
1326 SPSOptional
<SPSUnwindSectionInfo
>,
1327 SPSMachOObjectPlatformSectionsMap
)>::
1328 handle(ArgData
, ArgSize
,
1329 [](ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> USI
,
1330 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>>
1332 return MachOPlatformRuntimeState::get()
1333 .registerObjectPlatformSections(HeaderAddr
, std::move(USI
),
1339 ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
1340 __orc_rt_macho_deregister_object_platform_sections(char *ArgData
,
1342 return WrapperFunction
<SPSError(SPSExecutorAddr
,
1343 SPSOptional
<SPSUnwindSectionInfo
>,
1344 SPSMachOObjectPlatformSectionsMap
)>::
1345 handle(ArgData
, ArgSize
,
1346 [](ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> USI
,
1347 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>>
1349 return MachOPlatformRuntimeState::get()
1350 .deregisterObjectPlatformSections(HeaderAddr
, std::move(USI
),
1356 ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
1357 __orc_rt_macho_run_wrapper_function_calls(char *ArgData
, size_t ArgSize
) {
1358 return WrapperFunction
<SPSError(SPSSequence
<SPSWrapperFunctionCall
>)>::handle(
1359 ArgData
, ArgSize
, runWrapperFunctionCalls
)
1363 //------------------------------------------------------------------------------
1365 //------------------------------------------------------------------------------
1367 ORC_RT_INTERFACE
void *__orc_rt_macho_tlv_get_addr_impl(TLVDescriptor
*D
) {
1368 auto *TLVMgr
= static_cast<MachOPlatformRuntimeTLVManager
*>(
1369 pthread_getspecific(D
->Key
));
1371 TLVMgr
= new MachOPlatformRuntimeTLVManager();
1372 if (pthread_setspecific(D
->Key
, TLVMgr
)) {
1373 __orc_rt_log_error("Call to pthread_setspecific failed");
1378 return TLVMgr
->getInstance(
1379 reinterpret_cast<char *>(static_cast<uintptr_t>(D
->DataAddress
)));
1382 ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
1383 __orc_rt_macho_create_pthread_key(char *ArgData
, size_t ArgSize
) {
1384 return WrapperFunction
<SPSExpected
<uint64_t>(void)>::handle(
1386 []() -> Expected
<uint64_t> {
1388 if (int Err
= pthread_key_create(&Key
, destroyMachOTLVMgr
)) {
1389 __orc_rt_log_error("Call to pthread_key_create failed");
1390 return make_error
<StringError
>(strerror(Err
));
1392 return static_cast<uint64_t>(Key
);
1397 //------------------------------------------------------------------------------
1398 // cxa_atexit support
1399 //------------------------------------------------------------------------------
1401 int __orc_rt_macho_cxa_atexit(void (*func
)(void *), void *arg
,
1403 return MachOPlatformRuntimeState::get().registerAtExit(func
, arg
, dso_handle
);
1406 void __orc_rt_macho_cxa_finalize(void *dso_handle
) {
1407 MachOPlatformRuntimeState::get().runAtExits(dso_handle
);
1410 //------------------------------------------------------------------------------
1411 // JIT'd dlfcn alternatives.
1412 //------------------------------------------------------------------------------
1414 const char *__orc_rt_macho_jit_dlerror() {
1415 return MachOPlatformRuntimeState::get().dlerror();
1418 void *__orc_rt_macho_jit_dlopen(const char *path
, int mode
) {
1419 return MachOPlatformRuntimeState::get().dlopen(path
, mode
);
1422 int __orc_rt_macho_jit_dlclose(void *dso_handle
) {
1423 return MachOPlatformRuntimeState::get().dlclose(dso_handle
);
1426 void *__orc_rt_macho_jit_dlsym(void *dso_handle
, const char *symbol
) {
1427 return MachOPlatformRuntimeState::get().dlsym(dso_handle
, symbol
);
1430 //------------------------------------------------------------------------------
1431 // MachO Run Program
1432 //------------------------------------------------------------------------------
1434 ORC_RT_INTERFACE
int64_t __orc_rt_macho_run_program(const char *JITDylibName
,
1435 const char *EntrySymbolName
,
1436 int argc
, char *argv
[]) {
1437 using MainTy
= int (*)(int, char *[]);
1439 void *H
= __orc_rt_macho_jit_dlopen(JITDylibName
,
1440 __orc_rt::macho::ORC_RT_RTLD_LAZY
);
1442 __orc_rt_log_error(__orc_rt_macho_jit_dlerror());
1447 reinterpret_cast<MainTy
>(__orc_rt_macho_jit_dlsym(H
, EntrySymbolName
));
1450 __orc_rt_log_error(__orc_rt_macho_jit_dlerror());
1454 int Result
= Main(argc
, argv
);
1456 if (__orc_rt_macho_jit_dlclose(H
) == -1)
1457 __orc_rt_log_error(__orc_rt_macho_jit_dlerror());