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
)
39 struct objc_image_info
;
42 // Objective-C registration functions.
43 // These are weakly imported. If the Objective-C runtime has not been loaded
44 // then code containing Objective-C sections will generate an error.
46 _objc_map_images(unsigned count
, const char *const paths
[],
47 const mach_header
*const mhdrs
[]) ORC_RT_WEAK_IMPORT
;
49 extern "C" void _objc_load_image(const char *path
,
50 const mach_header
*mh
) ORC_RT_WEAK_IMPORT
;
52 // Libunwind prototypes.
53 struct unw_dynamic_unwind_sections
{
55 uintptr_t dwarf_section
;
56 size_t dwarf_section_length
;
57 uintptr_t compact_unwind_section
;
58 size_t compact_unwind_section_length
;
61 typedef int (*unw_find_dynamic_unwind_sections
)(
62 uintptr_t addr
, struct unw_dynamic_unwind_sections
*info
);
64 extern "C" int __unw_add_find_dynamic_unwind_sections(
65 unw_find_dynamic_unwind_sections find_dynamic_unwind_sections
)
68 extern "C" int __unw_remove_find_dynamic_unwind_sections(
69 unw_find_dynamic_unwind_sections find_dynamic_unwind_sections
)
74 struct MachOJITDylibDepInfo
{
76 std::vector
<ExecutorAddr
> DepHeaders
;
79 using MachOJITDylibDepInfoMap
=
80 std::unordered_map
<ExecutorAddr
, MachOJITDylibDepInfo
>;
82 } // anonymous namespace
86 using SPSMachOObjectPlatformSectionsMap
=
87 SPSSequence
<SPSTuple
<SPSString
, SPSExecutorAddrRange
>>;
89 using SPSMachOJITDylibDepInfo
= SPSTuple
<bool, SPSSequence
<SPSExecutorAddr
>>;
91 using SPSMachOJITDylibDepInfoMap
=
92 SPSSequence
<SPSTuple
<SPSExecutorAddr
, SPSMachOJITDylibDepInfo
>>;
95 class SPSSerializationTraits
<SPSMachOJITDylibDepInfo
, MachOJITDylibDepInfo
> {
97 static size_t size(const MachOJITDylibDepInfo
&JDI
) {
98 return SPSMachOJITDylibDepInfo::AsArgList::size(JDI
.Sealed
, JDI
.DepHeaders
);
101 static bool serialize(SPSOutputBuffer
&OB
, const MachOJITDylibDepInfo
&JDI
) {
102 return SPSMachOJITDylibDepInfo::AsArgList::serialize(OB
, JDI
.Sealed
,
106 static bool deserialize(SPSInputBuffer
&IB
, MachOJITDylibDepInfo
&JDI
) {
107 return SPSMachOJITDylibDepInfo::AsArgList::deserialize(IB
, JDI
.Sealed
,
112 struct UnwindSectionInfo
{
113 std::vector
<ExecutorAddrRange
> CodeRanges
;
114 ExecutorAddrRange DwarfSection
;
115 ExecutorAddrRange CompactUnwindSection
;
118 using SPSUnwindSectionInfo
=
119 SPSTuple
<SPSSequence
<SPSExecutorAddrRange
>, SPSExecutorAddrRange
,
120 SPSExecutorAddrRange
>;
123 class SPSSerializationTraits
<SPSUnwindSectionInfo
, UnwindSectionInfo
> {
125 static size_t size(const UnwindSectionInfo
&USI
) {
126 return SPSUnwindSectionInfo::AsArgList::size(
127 USI
.CodeRanges
, USI
.DwarfSection
, USI
.CompactUnwindSection
);
130 static bool serialize(SPSOutputBuffer
&OB
, const UnwindSectionInfo
&USI
) {
131 return SPSUnwindSectionInfo::AsArgList::serialize(
132 OB
, USI
.CodeRanges
, USI
.DwarfSection
, USI
.CompactUnwindSection
);
135 static bool deserialize(SPSInputBuffer
&IB
, UnwindSectionInfo
&USI
) {
136 return SPSUnwindSectionInfo::AsArgList::deserialize(
137 IB
, USI
.CodeRanges
, USI
.DwarfSection
, USI
.CompactUnwindSection
);
141 } // namespace __orc_rt
144 struct TLVDescriptor
{
145 void *(*Thunk
)(TLVDescriptor
*) = nullptr;
146 unsigned long Key
= 0;
147 unsigned long DataAddress
= 0;
150 class MachOPlatformRuntimeState
{
153 void (*Func
)(void *);
157 using AtExitsVector
= std::vector
<AtExitEntry
>;
159 /// Used to manage sections of fixed-sized metadata records (e.g. pointer
160 /// sections, selector refs, etc.)
161 template <typename RecordElement
> class RecordSectionsTracker
{
163 /// Add a section to the "new" list.
164 void add(span
<RecordElement
> Sec
) { New
.push_back(std::move(Sec
)); }
166 /// Returns true if there are new sections to process.
167 bool hasNewSections() const { return !New
.empty(); }
169 /// Returns the number of new sections to process.
170 size_t numNewSections() const { return New
.size(); }
172 /// Process all new sections.
173 template <typename ProcessSectionFunc
>
174 std::enable_if_t
<std::is_void_v
<
175 std::invoke_result_t
<ProcessSectionFunc
, span
<RecordElement
>>>>
176 processNewSections(ProcessSectionFunc
&&ProcessSection
) {
177 for (auto &Sec
: New
)
179 moveNewToProcessed();
182 /// Proces all new sections with a fallible handler.
184 /// Successfully handled sections will be moved to the Processed
186 template <typename ProcessSectionFunc
>
188 std::is_same_v
<Error
, std::invoke_result_t
<ProcessSectionFunc
,
189 span
<RecordElement
>>>,
191 processNewSections(ProcessSectionFunc
&&ProcessSection
) {
192 for (size_t I
= 0; I
!= New
.size(); ++I
) {
193 if (auto Err
= ProcessSection(New
[I
])) {
194 for (size_t J
= 0; J
!= I
; ++J
)
195 Processed
.push_back(New
[J
]);
196 New
.erase(New
.begin(), New
.begin() + I
);
200 moveNewToProcessed();
201 return Error::success();
204 /// Move all sections back to New for reprocessing.
206 moveNewToProcessed();
207 New
= std::move(Processed
);
210 /// Remove the section with the given range.
211 bool removeIfPresent(ExecutorAddrRange R
) {
212 if (removeIfPresent(New
, R
))
214 return removeIfPresent(Processed
, R
);
218 void moveNewToProcessed() {
219 if (Processed
.empty())
220 Processed
= std::move(New
);
222 Processed
.reserve(Processed
.size() + New
.size());
223 std::copy(New
.begin(), New
.end(), std::back_inserter(Processed
));
228 bool removeIfPresent(std::vector
<span
<RecordElement
>> &V
,
229 ExecutorAddrRange R
) {
230 auto RI
= std::find_if(
231 V
.rbegin(), V
.rend(),
232 [RS
= R
.toSpan
<RecordElement
>()](const span
<RecordElement
> &E
) {
233 return E
.data() == RS
.data();
235 if (RI
!= V
.rend()) {
236 V
.erase(std::next(RI
).base());
242 std::vector
<span
<RecordElement
>> Processed
;
243 std::vector
<span
<RecordElement
>> New
;
246 struct UnwindSections
{
247 UnwindSections(const UnwindSectionInfo
&USI
)
248 : DwarfSection(USI
.DwarfSection
.toSpan
<char>()),
249 CompactUnwindSection(USI
.CompactUnwindSection
.toSpan
<char>()) {}
251 span
<char> DwarfSection
;
252 span
<char> CompactUnwindSection
;
255 using UnwindSectionsMap
=
256 IntervalMap
<char *, UnwindSections
, IntervalCoalescing::Disabled
>;
258 struct JITDylibState
{
260 void *Header
= nullptr;
262 size_t LinkedAgainstRefCount
= 0;
263 size_t DlRefCount
= 0;
264 std::vector
<JITDylibState
*> Deps
;
265 AtExitsVector AtExits
;
266 const objc_image_info
*ObjCImageInfo
= nullptr;
267 std::unordered_map
<void *, std::vector
<char>> DataSectionContent
;
268 std::unordered_map
<void *, size_t> ZeroInitRanges
;
269 UnwindSectionsMap UnwindSections
;
270 RecordSectionsTracker
<void (*)()> ModInitsSections
;
271 RecordSectionsTracker
<char> ObjCRuntimeRegistrationObjects
;
273 bool referenced() const {
274 return LinkedAgainstRefCount
!= 0 || DlRefCount
!= 0;
279 static Error
create();
280 static MachOPlatformRuntimeState
&get();
281 static Error
destroy();
283 MachOPlatformRuntimeState() = default;
285 // Delete copy and move constructors.
286 MachOPlatformRuntimeState(const MachOPlatformRuntimeState
&) = delete;
287 MachOPlatformRuntimeState
&
288 operator=(const MachOPlatformRuntimeState
&) = delete;
289 MachOPlatformRuntimeState(MachOPlatformRuntimeState
&&) = delete;
290 MachOPlatformRuntimeState
&operator=(MachOPlatformRuntimeState
&&) = delete;
295 Error
registerJITDylib(std::string Name
, void *Header
);
296 Error
deregisterJITDylib(void *Header
);
297 Error
registerThreadDataSection(span
<const char> ThreadDataSection
);
298 Error
deregisterThreadDataSection(span
<const char> ThreadDataSection
);
299 Error
registerObjectPlatformSections(
300 ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> UnwindSections
,
301 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>> Secs
);
302 Error
deregisterObjectPlatformSections(
303 ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> UnwindSections
,
304 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>> Secs
);
306 const char *dlerror();
307 void *dlopen(std::string_view Name
, int Mode
);
308 int dlclose(void *DSOHandle
);
309 void *dlsym(void *DSOHandle
, std::string_view Symbol
);
311 int registerAtExit(void (*F
)(void *), void *Arg
, void *DSOHandle
);
312 void runAtExits(std::unique_lock
<std::mutex
> &JDStatesLock
,
314 void runAtExits(void *DSOHandle
);
316 /// Returns the base address of the section containing ThreadData.
317 Expected
<std::pair
<const char *, size_t>>
318 getThreadDataSectionFor(const char *ThreadData
);
321 JITDylibState
*getJITDylibStateByHeader(void *DSOHandle
);
322 JITDylibState
*getJITDylibStateByName(std::string_view Path
);
324 Expected
<ExecutorAddr
> lookupSymbolInJITDylib(void *DSOHandle
,
325 std::string_view Symbol
);
327 bool lookupUnwindSections(void *Addr
, unw_dynamic_unwind_sections
&Info
);
329 static int findDynamicUnwindSections(uintptr_t addr
,
330 unw_dynamic_unwind_sections
*info
);
331 static Error
registerEHFrames(span
<const char> EHFrameSection
);
332 static Error
deregisterEHFrames(span
<const char> EHFrameSection
);
334 static Error
registerObjCRegistrationObjects(JITDylibState
&JDS
);
335 static Error
runModInits(std::unique_lock
<std::mutex
> &JDStatesLock
,
338 Expected
<void *> dlopenImpl(std::string_view Path
, int Mode
);
339 Error
dlopenFull(std::unique_lock
<std::mutex
> &JDStatesLock
,
341 Error
dlopenInitialize(std::unique_lock
<std::mutex
> &JDStatesLock
,
342 JITDylibState
&JDS
, MachOJITDylibDepInfoMap
&DepInfo
);
344 Error
dlcloseImpl(void *DSOHandle
);
345 Error
dlcloseDeinitialize(std::unique_lock
<std::mutex
> &JDStatesLock
,
348 static MachOPlatformRuntimeState
*MOPS
;
350 bool UseCallbackStyleUnwindInfo
= false;
352 // FIXME: Move to thread-state.
353 std::string DLFcnError
;
355 // APIMutex guards against concurrent entry into key "dyld" API functions
356 // (e.g. dlopen, dlclose).
357 std::recursive_mutex DyldAPIMutex
;
359 // JDStatesMutex guards the data structures that hold JITDylib state.
360 std::mutex JDStatesMutex
;
361 std::unordered_map
<void *, JITDylibState
> JDStates
;
362 std::unordered_map
<std::string_view
, void *> JDNameToHeader
;
364 // ThreadDataSectionsMutex guards thread local data section state.
365 std::mutex ThreadDataSectionsMutex
;
366 std::map
<const char *, size_t> ThreadDataSections
;
369 MachOPlatformRuntimeState
*MachOPlatformRuntimeState::MOPS
= nullptr;
371 Error
MachOPlatformRuntimeState::create() {
372 assert(!MOPS
&& "MachOPlatformRuntimeState should be null");
373 MOPS
= new MachOPlatformRuntimeState();
374 return MOPS
->initialize();
377 MachOPlatformRuntimeState
&MachOPlatformRuntimeState::get() {
378 assert(MOPS
&& "MachOPlatformRuntimeState not initialized");
382 Error
MachOPlatformRuntimeState::destroy() {
383 assert(MOPS
&& "MachOPlatformRuntimeState not initialized");
384 auto Err
= MOPS
->shutdown();
389 Error
MachOPlatformRuntimeState::initialize() {
390 UseCallbackStyleUnwindInfo
= __unw_add_find_dynamic_unwind_sections
&&
391 __unw_remove_find_dynamic_unwind_sections
;
392 if (UseCallbackStyleUnwindInfo
) {
394 printdbg("__unw_add/remove_find_dynamic_unwind_sections available."
395 " Using callback-based frame info lookup.\n");
397 if (__unw_add_find_dynamic_unwind_sections(&findDynamicUnwindSections
))
398 return make_error
<StringError
>(
399 "Could not register findDynamicUnwindSections");
402 printdbg("__unw_add/remove_find_dynamic_unwind_sections not available."
403 " Using classic frame info registration.\n");
406 return Error::success();
409 Error
MachOPlatformRuntimeState::shutdown() {
410 if (UseCallbackStyleUnwindInfo
) {
411 if (__unw_remove_find_dynamic_unwind_sections(&findDynamicUnwindSections
)) {
413 { printdbg("__unw_remove_find_dynamic_unwind_sections failed.\n"); });
416 return Error::success();
419 Error
MachOPlatformRuntimeState::registerJITDylib(std::string Name
,
422 printdbg("Registering JITDylib %s: Header = %p\n", Name
.c_str(), Header
);
424 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
425 if (JDStates
.count(Header
)) {
426 std::ostringstream ErrStream
;
427 ErrStream
<< "Duplicate JITDylib registration for header " << Header
428 << " (name = " << Name
<< ")";
429 return make_error
<StringError
>(ErrStream
.str());
431 if (JDNameToHeader
.count(Name
)) {
432 std::ostringstream ErrStream
;
433 ErrStream
<< "Duplicate JITDylib registration for header " << Header
434 << " (header = " << Header
<< ")";
435 return make_error
<StringError
>(ErrStream
.str());
438 auto &JDS
= JDStates
[Header
];
439 JDS
.Name
= std::move(Name
);
441 JDNameToHeader
[JDS
.Name
] = Header
;
442 return Error::success();
445 Error
MachOPlatformRuntimeState::deregisterJITDylib(void *Header
) {
446 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
447 auto I
= JDStates
.find(Header
);
448 if (I
== JDStates
.end()) {
449 std::ostringstream ErrStream
;
450 ErrStream
<< "Attempted to deregister unrecognized header " << Header
;
451 return make_error
<StringError
>(ErrStream
.str());
454 // Remove std::string construction once we can use C++20.
455 auto J
= JDNameToHeader
.find(
456 std::string(I
->second
.Name
.data(), I
->second
.Name
.size()));
457 assert(J
!= JDNameToHeader
.end() &&
458 "Missing JDNameToHeader entry for JITDylib");
461 printdbg("Deregistering JITDylib %s: Header = %p\n", I
->second
.Name
.c_str(),
465 JDNameToHeader
.erase(J
);
467 return Error::success();
470 Error
MachOPlatformRuntimeState::registerThreadDataSection(
471 span
<const char> ThreadDataSection
) {
472 std::lock_guard
<std::mutex
> Lock(ThreadDataSectionsMutex
);
473 auto I
= ThreadDataSections
.upper_bound(ThreadDataSection
.data());
474 if (I
!= ThreadDataSections
.begin()) {
475 auto J
= std::prev(I
);
476 if (J
->first
+ J
->second
> ThreadDataSection
.data())
477 return make_error
<StringError
>("Overlapping __thread_data sections");
479 ThreadDataSections
.insert(
480 I
, std::make_pair(ThreadDataSection
.data(), ThreadDataSection
.size()));
481 return Error::success();
484 Error
MachOPlatformRuntimeState::deregisterThreadDataSection(
485 span
<const char> ThreadDataSection
) {
486 std::lock_guard
<std::mutex
> Lock(ThreadDataSectionsMutex
);
487 auto I
= ThreadDataSections
.find(ThreadDataSection
.data());
488 if (I
== ThreadDataSections
.end())
489 return make_error
<StringError
>("Attempt to deregister unknown thread data "
491 ThreadDataSections
.erase(I
);
492 return Error::success();
495 Error
MachOPlatformRuntimeState::registerObjectPlatformSections(
496 ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> UnwindInfo
,
497 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>> Secs
) {
499 // FIXME: Reject platform section registration after the JITDylib is
503 printdbg("MachOPlatform: Registering object sections for %p.\n",
504 HeaderAddr
.toPtr
<void *>());
507 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
508 auto *JDS
= getJITDylibStateByHeader(HeaderAddr
.toPtr
<void *>());
510 std::ostringstream ErrStream
;
511 ErrStream
<< "Could not register object platform sections for "
512 "unrecognized header "
513 << HeaderAddr
.toPtr
<void *>();
514 return make_error
<StringError
>(ErrStream
.str());
517 if (UnwindInfo
&& UseCallbackStyleUnwindInfo
) {
519 printdbg(" Registering new-style unwind info for:\n"
521 " Compact-unwind: %p -- %p\n"
523 UnwindInfo
->DwarfSection
.Start
.toPtr
<void *>(),
524 UnwindInfo
->DwarfSection
.End
.toPtr
<void *>(),
525 UnwindInfo
->CompactUnwindSection
.Start
.toPtr
<void *>(),
526 UnwindInfo
->CompactUnwindSection
.End
.toPtr
<void *>());
528 for (auto &CodeRange
: UnwindInfo
->CodeRanges
) {
529 JDS
->UnwindSections
.insert(CodeRange
.Start
.toPtr
<char *>(),
530 CodeRange
.End
.toPtr
<char *>(), *UnwindInfo
);
532 printdbg(" [ %p -- %p ]\n", CodeRange
.Start
.toPtr
<void *>(),
533 CodeRange
.End
.toPtr
<void *>());
538 for (auto &KV
: Secs
) {
539 // FIXME: Validate section ranges?
540 if (KV
.first
== "__TEXT,__eh_frame") {
541 if (!UseCallbackStyleUnwindInfo
) {
542 // Use classic libunwind registration.
543 if (auto Err
= registerEHFrames(KV
.second
.toSpan
<const char>()))
546 } else if (KV
.first
== "__DATA,__data") {
547 assert(!JDS
->DataSectionContent
.count(KV
.second
.Start
.toPtr
<char *>()) &&
548 "Address already registered.");
549 auto S
= KV
.second
.toSpan
<char>();
550 JDS
->DataSectionContent
[KV
.second
.Start
.toPtr
<char *>()] =
551 std::vector
<char>(S
.begin(), S
.end());
552 } else if (KV
.first
== "__DATA,__common") {
553 JDS
->ZeroInitRanges
[KV
.second
.Start
.toPtr
<char *>()] = KV
.second
.size();
554 } else if (KV
.first
== "__DATA,__thread_data") {
555 if (auto Err
= registerThreadDataSection(KV
.second
.toSpan
<const char>()))
557 } else if (KV
.first
== "__llvm_jitlink_ObjCRuntimeRegistrationObject")
558 JDS
->ObjCRuntimeRegistrationObjects
.add(KV
.second
.toSpan
<char>());
559 else if (KV
.first
== "__DATA,__mod_init_func")
560 JDS
->ModInitsSections
.add(KV
.second
.toSpan
<void (*)()>());
562 // Should this be a warning instead?
563 return make_error
<StringError
>(
564 "Encountered unexpected section " +
565 std::string(KV
.first
.data(), KV
.first
.size()) +
566 " while registering object platform sections");
570 return Error::success();
573 Error
MachOPlatformRuntimeState::deregisterObjectPlatformSections(
574 ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> UnwindInfo
,
575 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>> Secs
) {
576 // TODO: Make this more efficient? (maybe unnecessary if removal is rare?)
577 // TODO: Add a JITDylib prepare-for-teardown operation that clears all
578 // registered sections, causing this function to take the fast-path.
580 printdbg("MachOPlatform: Deregistering object sections for %p.\n",
581 HeaderAddr
.toPtr
<void *>());
584 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
585 auto *JDS
= getJITDylibStateByHeader(HeaderAddr
.toPtr
<void *>());
587 std::ostringstream ErrStream
;
588 ErrStream
<< "Could not register object platform sections for unrecognized "
590 << HeaderAddr
.toPtr
<void *>();
591 return make_error
<StringError
>(ErrStream
.str());
594 // FIXME: Implement faster-path by returning immediately if JDS is being
595 // torn down entirely?
597 // TODO: Make library permanent (i.e. not able to be dlclosed) if it contains
598 // any Swift or ObjC. Once this happens we can clear (and no longer record)
599 // data section content, as the library could never be re-initialized.
601 if (UnwindInfo
&& UseCallbackStyleUnwindInfo
) {
603 printdbg(" Deregistering new-style unwind info for:\n"
605 " Compact-unwind: %p -- %p\n"
607 UnwindInfo
->DwarfSection
.Start
.toPtr
<void *>(),
608 UnwindInfo
->DwarfSection
.End
.toPtr
<void *>(),
609 UnwindInfo
->CompactUnwindSection
.Start
.toPtr
<void *>(),
610 UnwindInfo
->CompactUnwindSection
.End
.toPtr
<void *>());
612 for (auto &CodeRange
: UnwindInfo
->CodeRanges
) {
613 JDS
->UnwindSections
.erase(CodeRange
.Start
.toPtr
<char *>(),
614 CodeRange
.End
.toPtr
<char *>());
616 printdbg(" [ %p -- %p ]\n", CodeRange
.Start
.toPtr
<void *>(),
617 CodeRange
.End
.toPtr
<void *>());
622 for (auto &KV
: Secs
) {
623 // FIXME: Validate section ranges?
624 if (KV
.first
== "__TEXT,__eh_frame") {
625 if (!UseCallbackStyleUnwindInfo
) {
626 // Use classic libunwind registration.
627 if (auto Err
= deregisterEHFrames(KV
.second
.toSpan
<const char>()))
630 } else if (KV
.first
== "__DATA,__data") {
631 JDS
->DataSectionContent
.erase(KV
.second
.Start
.toPtr
<char *>());
632 } else if (KV
.first
== "__DATA,__common") {
633 JDS
->ZeroInitRanges
.erase(KV
.second
.Start
.toPtr
<char *>());
634 } else if (KV
.first
== "__DATA,__thread_data") {
636 deregisterThreadDataSection(KV
.second
.toSpan
<const char>()))
638 } else if (KV
.first
== "__llvm_jitlink_ObjCRuntimeRegistrationObject")
639 JDS
->ObjCRuntimeRegistrationObjects
.removeIfPresent(KV
.second
);
640 else if (KV
.first
== "__DATA,__mod_init_func")
641 JDS
->ModInitsSections
.removeIfPresent(KV
.second
);
643 // Should this be a warning instead?
644 return make_error
<StringError
>(
645 "Encountered unexpected section " +
646 std::string(KV
.first
.data(), KV
.first
.size()) +
647 " while deregistering object platform sections");
650 return Error::success();
653 const char *MachOPlatformRuntimeState::dlerror() { return DLFcnError
.c_str(); }
655 void *MachOPlatformRuntimeState::dlopen(std::string_view Path
, int Mode
) {
657 std::string
S(Path
.data(), Path
.size());
658 printdbg("MachOPlatform::dlopen(\"%s\")\n", S
.c_str());
660 std::lock_guard
<std::recursive_mutex
> Lock(DyldAPIMutex
);
661 if (auto H
= dlopenImpl(Path
, Mode
))
664 // FIXME: Make dlerror thread safe.
665 DLFcnError
= toString(H
.takeError());
670 int MachOPlatformRuntimeState::dlclose(void *DSOHandle
) {
672 auto *JDS
= getJITDylibStateByHeader(DSOHandle
);
673 std::string DylibName
;
676 printdbg("MachOPlatform::dlclose(%p) (%s)\n", DSOHandle
, S
.c_str());
678 printdbg("MachOPlatform::dlclose(%p) (%s)\n", DSOHandle
,
681 std::lock_guard
<std::recursive_mutex
> Lock(DyldAPIMutex
);
682 if (auto Err
= dlcloseImpl(DSOHandle
)) {
683 // FIXME: Make dlerror thread safe.
684 DLFcnError
= toString(std::move(Err
));
690 void *MachOPlatformRuntimeState::dlsym(void *DSOHandle
,
691 std::string_view Symbol
) {
692 auto Addr
= lookupSymbolInJITDylib(DSOHandle
, Symbol
);
694 DLFcnError
= toString(Addr
.takeError());
698 return Addr
->toPtr
<void *>();
701 int MachOPlatformRuntimeState::registerAtExit(void (*F
)(void *), void *Arg
,
703 // FIXME: Handle out-of-memory errors, returning -1 if OOM.
704 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
705 auto *JDS
= getJITDylibStateByHeader(DSOHandle
);
708 printdbg("MachOPlatformRuntimeState::registerAtExit called with "
709 "unrecognized dso handle %p\n",
714 JDS
->AtExits
.push_back({F
, Arg
});
718 void MachOPlatformRuntimeState::runAtExits(
719 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
) {
720 auto AtExits
= std::move(JDS
.AtExits
);
722 // Unlock while running atexits, as they may trigger operations that modify
724 JDStatesLock
.unlock();
725 while (!AtExits
.empty()) {
726 auto &AE
= AtExits
.back();
733 void MachOPlatformRuntimeState::runAtExits(void *DSOHandle
) {
734 std::unique_lock
<std::mutex
> Lock(JDStatesMutex
);
735 auto *JDS
= getJITDylibStateByHeader(DSOHandle
);
737 printdbg("MachOPlatformRuntimeState::runAtExits called on unrecognized "
742 runAtExits(Lock
, *JDS
);
745 Expected
<std::pair
<const char *, size_t>>
746 MachOPlatformRuntimeState::getThreadDataSectionFor(const char *ThreadData
) {
747 std::lock_guard
<std::mutex
> Lock(ThreadDataSectionsMutex
);
748 auto I
= ThreadDataSections
.upper_bound(ThreadData
);
749 // Check that we have a valid entry covering this address.
750 if (I
== ThreadDataSections
.begin())
751 return make_error
<StringError
>("No thread local data section for key");
753 if (ThreadData
>= I
->first
+ I
->second
)
754 return make_error
<StringError
>("No thread local data section for key");
758 MachOPlatformRuntimeState::JITDylibState
*
759 MachOPlatformRuntimeState::getJITDylibStateByHeader(void *DSOHandle
) {
760 auto I
= JDStates
.find(DSOHandle
);
761 if (I
== JDStates
.end()) {
762 I
= JDStates
.insert(std::make_pair(DSOHandle
, JITDylibState())).first
;
763 I
->second
.Header
= DSOHandle
;
768 MachOPlatformRuntimeState::JITDylibState
*
769 MachOPlatformRuntimeState::getJITDylibStateByName(std::string_view Name
) {
770 // FIXME: Avoid creating string once we have C++20.
771 auto I
= JDNameToHeader
.find(std::string(Name
.data(), Name
.size()));
772 if (I
!= JDNameToHeader
.end())
773 return getJITDylibStateByHeader(I
->second
);
777 Expected
<ExecutorAddr
>
778 MachOPlatformRuntimeState::lookupSymbolInJITDylib(void *DSOHandle
,
779 std::string_view Sym
) {
780 Expected
<ExecutorAddr
> Result((ExecutorAddr()));
781 if (auto Err
= WrapperFunction
<SPSExpected
<SPSExecutorAddr
>(
782 SPSExecutorAddr
, SPSString
)>::call(&__orc_rt_macho_symbol_lookup_tag
,
784 ExecutorAddr::fromPtr(DSOHandle
),
786 return std::move(Err
);
790 // eh-frame registration functions.
791 // We expect these to be available for all processes.
792 extern "C" void __register_frame(const void *);
793 extern "C" void __deregister_frame(const void *);
795 template <typename HandleFDEFn
>
796 void walkEHFrameSection(span
<const char> EHFrameSection
,
797 HandleFDEFn HandleFDE
) {
798 const char *CurCFIRecord
= EHFrameSection
.data();
799 uint64_t Size
= *reinterpret_cast<const uint32_t *>(CurCFIRecord
);
801 while (CurCFIRecord
!= EHFrameSection
.end() && Size
!= 0) {
802 const char *OffsetField
= CurCFIRecord
+ (Size
== 0xffffffff ? 12 : 4);
803 if (Size
== 0xffffffff)
804 Size
= *reinterpret_cast<const uint64_t *>(CurCFIRecord
+ 4) + 12;
807 uint32_t Offset
= *reinterpret_cast<const uint32_t *>(OffsetField
);
810 HandleFDE(CurCFIRecord
);
812 CurCFIRecord
+= Size
;
813 Size
= *reinterpret_cast<const uint32_t *>(CurCFIRecord
);
817 bool MachOPlatformRuntimeState::lookupUnwindSections(
818 void *Addr
, unw_dynamic_unwind_sections
&Info
) {
820 { printdbg("Tried to lookup unwind-info via new lookup call.\n"); });
821 std::lock_guard
<std::mutex
> Lock(JDStatesMutex
);
822 for (auto &KV
: JDStates
) {
823 auto &JD
= KV
.second
;
824 auto I
= JD
.UnwindSections
.find(reinterpret_cast<char *>(Addr
));
825 if (I
!= JD
.UnwindSections
.end()) {
826 Info
.dso_base
= reinterpret_cast<uintptr_t>(JD
.Header
);
828 reinterpret_cast<uintptr_t>(I
->second
.DwarfSection
.data());
829 Info
.dwarf_section_length
= I
->second
.DwarfSection
.size();
830 Info
.compact_unwind_section
=
831 reinterpret_cast<uintptr_t>(I
->second
.CompactUnwindSection
.data());
832 Info
.compact_unwind_section_length
=
833 I
->second
.CompactUnwindSection
.size();
840 int MachOPlatformRuntimeState::findDynamicUnwindSections(
841 uintptr_t addr
, unw_dynamic_unwind_sections
*info
) {
844 return MachOPlatformRuntimeState::get().lookupUnwindSections((void *)addr
,
848 Error
MachOPlatformRuntimeState::registerEHFrames(
849 span
<const char> EHFrameSection
) {
850 walkEHFrameSection(EHFrameSection
, __register_frame
);
851 return Error::success();
854 Error
MachOPlatformRuntimeState::deregisterEHFrames(
855 span
<const char> EHFrameSection
) {
856 walkEHFrameSection(EHFrameSection
, __deregister_frame
);
857 return Error::success();
860 Error
MachOPlatformRuntimeState::registerObjCRegistrationObjects(
861 JITDylibState
&JDS
) {
862 ORC_RT_DEBUG(printdbg("Registering Objective-C / Swift metadata.\n"));
864 std::vector
<char *> RegObjBases
;
865 JDS
.ObjCRuntimeRegistrationObjects
.processNewSections(
866 [&](span
<char> RegObj
) { RegObjBases
.push_back(RegObj
.data()); });
868 if (RegObjBases
.empty())
869 return Error::success();
871 if (!_objc_map_images
|| !_objc_load_image
)
872 return make_error
<StringError
>(
873 "Could not register Objective-C / Swift metadata: _objc_map_images / "
874 "_objc_load_image not found");
876 std::vector
<char *> Paths
;
877 Paths
.resize(RegObjBases
.size());
878 _objc_map_images(RegObjBases
.size(), Paths
.data(),
879 reinterpret_cast<mach_header
**>(RegObjBases
.data()));
881 for (void *RegObjBase
: RegObjBases
)
882 _objc_load_image(nullptr, reinterpret_cast<mach_header
*>(RegObjBase
));
884 return Error::success();
887 Error
MachOPlatformRuntimeState::runModInits(
888 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
) {
889 std::vector
<span
<void (*)()>> InitSections
;
890 InitSections
.reserve(JDS
.ModInitsSections
.numNewSections());
892 // Copy initializer sections: If the JITDylib is unsealed then the
893 // initializers could reach back into the JIT and cause more initializers to
895 // FIXME: Skip unlock and run in-place on sealed JITDylibs?
896 JDS
.ModInitsSections
.processNewSections(
897 [&](span
<void (*)()> Inits
) { InitSections
.push_back(Inits
); });
899 JDStatesLock
.unlock();
900 for (auto InitSec
: InitSections
)
901 for (auto *Init
: InitSec
)
905 return Error::success();
908 Expected
<void *> MachOPlatformRuntimeState::dlopenImpl(std::string_view Path
,
910 std::unique_lock
<std::mutex
> Lock(JDStatesMutex
);
912 // Try to find JITDylib state by name.
913 auto *JDS
= getJITDylibStateByName(Path
);
916 return make_error
<StringError
>("No registered JTIDylib for path " +
917 std::string(Path
.data(), Path
.size()));
919 // If this JITDylib is unsealed, or this is the first dlopen then run
920 // full dlopen path (update deps, push and run initializers, update ref
921 // counts on all JITDylibs in the dep tree).
922 if (!JDS
->referenced() || !JDS
->Sealed
) {
923 if (auto Err
= dlopenFull(Lock
, *JDS
))
924 return std::move(Err
);
927 // Bump the ref-count on this dylib.
930 // Return the header address.
934 Error
MachOPlatformRuntimeState::dlopenFull(
935 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
) {
936 // Call back to the JIT to push the initializers.
937 Expected
<MachOJITDylibDepInfoMap
> DepInfo((MachOJITDylibDepInfoMap()));
938 // Unlock so that we can accept the initializer update.
939 JDStatesLock
.unlock();
940 if (auto Err
= WrapperFunction
<SPSExpected
<SPSMachOJITDylibDepInfoMap
>(
941 SPSExecutorAddr
)>::call(&__orc_rt_macho_push_initializers_tag
,
942 DepInfo
, ExecutorAddr::fromPtr(JDS
.Header
)))
947 return DepInfo
.takeError();
949 if (auto Err
= dlopenInitialize(JDStatesLock
, JDS
, *DepInfo
))
952 if (!DepInfo
->empty()) {
954 printdbg("Unrecognized dep-info key headers in dlopen of %s\n",
957 std::ostringstream ErrStream
;
958 ErrStream
<< "Encountered unrecognized dep-info key headers "
959 "while processing dlopen of "
961 return make_error
<StringError
>(ErrStream
.str());
964 return Error::success();
967 Error
MachOPlatformRuntimeState::dlopenInitialize(
968 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
,
969 MachOJITDylibDepInfoMap
&DepInfo
) {
971 printdbg("MachOPlatformRuntimeState::dlopenInitialize(\"%s\")\n",
975 // If the header is not present in the dep map then assume that we
976 // already processed it earlier in the dlopenInitialize traversal and
978 // TODO: Keep a visited set instead so that we can error out on missing
980 auto I
= DepInfo
.find(ExecutorAddr::fromPtr(JDS
.Header
));
981 if (I
== DepInfo
.end())
982 return Error::success();
984 auto DI
= std::move(I
->second
);
987 // We don't need to re-initialize sealed JITDylibs that have already been
988 // initialized. Just check that their dep-map entry is empty as expected.
990 if (!DI
.DepHeaders
.empty()) {
991 std::ostringstream ErrStream
;
992 ErrStream
<< "Sealed JITDylib " << JDS
.Header
993 << " already has registered dependencies";
994 return make_error
<StringError
>(ErrStream
.str());
996 if (JDS
.referenced())
997 return Error::success();
999 JDS
.Sealed
= DI
.Sealed
;
1001 // This is an unsealed or newly sealed JITDylib. Run initializers.
1002 std::vector
<JITDylibState
*> OldDeps
;
1003 std::swap(JDS
.Deps
, OldDeps
);
1004 JDS
.Deps
.reserve(DI
.DepHeaders
.size());
1005 for (auto DepHeaderAddr
: DI
.DepHeaders
) {
1006 auto *DepJDS
= getJITDylibStateByHeader(DepHeaderAddr
.toPtr
<void *>());
1008 std::ostringstream ErrStream
;
1009 ErrStream
<< "Encountered unrecognized dep header "
1010 << DepHeaderAddr
.toPtr
<void *>() << " while initializing "
1012 return make_error
<StringError
>(ErrStream
.str());
1014 ++DepJDS
->LinkedAgainstRefCount
;
1015 if (auto Err
= dlopenInitialize(JDStatesLock
, *DepJDS
, DepInfo
))
1019 // Initialize this JITDylib.
1020 if (auto Err
= registerObjCRegistrationObjects(JDS
))
1022 if (auto Err
= runModInits(JDStatesLock
, JDS
))
1025 // Decrement old deps.
1026 // FIXME: We should probably continue and just report deinitialize errors
1028 for (auto *DepJDS
: OldDeps
) {
1029 --DepJDS
->LinkedAgainstRefCount
;
1030 if (!DepJDS
->referenced())
1031 if (auto Err
= dlcloseDeinitialize(JDStatesLock
, *DepJDS
))
1035 return Error::success();
1038 Error
MachOPlatformRuntimeState::dlcloseImpl(void *DSOHandle
) {
1039 std::unique_lock
<std::mutex
> Lock(JDStatesMutex
);
1041 // Try to find JITDylib state by header.
1042 auto *JDS
= getJITDylibStateByHeader(DSOHandle
);
1045 std::ostringstream ErrStream
;
1046 ErrStream
<< "No registered JITDylib for " << DSOHandle
;
1047 return make_error
<StringError
>(ErrStream
.str());
1050 // Bump the ref-count.
1053 if (!JDS
->referenced())
1054 return dlcloseDeinitialize(Lock
, *JDS
);
1056 return Error::success();
1059 Error
MachOPlatformRuntimeState::dlcloseDeinitialize(
1060 std::unique_lock
<std::mutex
> &JDStatesLock
, JITDylibState
&JDS
) {
1063 printdbg("MachOPlatformRuntimeState::dlcloseDeinitialize(\"%s\")\n",
1067 runAtExits(JDStatesLock
, JDS
);
1070 JDS
.ModInitsSections
.reset();
1072 // Reset data section contents.
1073 for (auto &KV
: JDS
.DataSectionContent
)
1074 memcpy(KV
.first
, KV
.second
.data(), KV
.second
.size());
1075 for (auto &KV
: JDS
.ZeroInitRanges
)
1076 memset(KV
.first
, 0, KV
.second
);
1078 // Deinitialize any dependencies.
1079 for (auto *DepJDS
: JDS
.Deps
) {
1080 --DepJDS
->LinkedAgainstRefCount
;
1081 if (!DepJDS
->referenced())
1082 if (auto Err
= dlcloseDeinitialize(JDStatesLock
, *DepJDS
))
1086 return Error::success();
1089 class MachOPlatformRuntimeTLVManager
{
1091 void *getInstance(const char *ThreadData
);
1094 std::unordered_map
<const char *, char *> Instances
;
1095 std::unordered_map
<const char *, std::unique_ptr
<char[]>> AllocatedSections
;
1098 void *MachOPlatformRuntimeTLVManager::getInstance(const char *ThreadData
) {
1099 auto I
= Instances
.find(ThreadData
);
1100 if (I
!= Instances
.end())
1104 MachOPlatformRuntimeState::get().getThreadDataSectionFor(ThreadData
);
1106 __orc_rt_log_error(toString(TDS
.takeError()).c_str());
1110 auto &Allocated
= AllocatedSections
[TDS
->first
];
1112 Allocated
= std::make_unique
<char[]>(TDS
->second
);
1113 memcpy(Allocated
.get(), TDS
->first
, TDS
->second
);
1116 size_t ThreadDataDelta
= ThreadData
- TDS
->first
;
1117 assert(ThreadDataDelta
<= TDS
->second
&& "ThreadData outside section bounds");
1119 char *Instance
= Allocated
.get() + ThreadDataDelta
;
1120 Instances
[ThreadData
] = Instance
;
1124 void destroyMachOTLVMgr(void *MachOTLVMgr
) {
1125 delete static_cast<MachOPlatformRuntimeTLVManager
*>(MachOTLVMgr
);
1128 Error
runWrapperFunctionCalls(std::vector
<WrapperFunctionCall
> WFCs
) {
1129 for (auto &WFC
: WFCs
)
1130 if (auto Err
= WFC
.runWithSPSRet
<void>())
1132 return Error::success();
1135 } // end anonymous namespace
1137 //------------------------------------------------------------------------------
1139 //------------------------------------------------------------------------------
1141 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1142 __orc_rt_macho_platform_bootstrap(char *ArgData
, size_t ArgSize
) {
1143 return WrapperFunction
<SPSError()>::handle(
1145 []() { return MachOPlatformRuntimeState::create(); })
1149 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1150 __orc_rt_macho_platform_shutdown(char *ArgData
, size_t ArgSize
) {
1151 return WrapperFunction
<SPSError()>::handle(
1153 []() { return MachOPlatformRuntimeState::destroy(); })
1157 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1158 __orc_rt_macho_register_jitdylib(char *ArgData
, size_t ArgSize
) {
1159 return WrapperFunction
<SPSError(SPSString
, SPSExecutorAddr
)>::handle(
1161 [](std::string
&Name
, ExecutorAddr HeaderAddr
) {
1162 return MachOPlatformRuntimeState::get().registerJITDylib(
1163 std::move(Name
), HeaderAddr
.toPtr
<void *>());
1168 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1169 __orc_rt_macho_deregister_jitdylib(char *ArgData
, size_t ArgSize
) {
1170 return WrapperFunction
<SPSError(SPSExecutorAddr
)>::handle(
1172 [](ExecutorAddr HeaderAddr
) {
1173 return MachOPlatformRuntimeState::get().deregisterJITDylib(
1174 HeaderAddr
.toPtr
<void *>());
1179 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1180 __orc_rt_macho_register_object_platform_sections(char *ArgData
,
1182 return WrapperFunction
<SPSError(SPSExecutorAddr
,
1183 SPSOptional
<SPSUnwindSectionInfo
>,
1184 SPSMachOObjectPlatformSectionsMap
)>::
1185 handle(ArgData
, ArgSize
,
1186 [](ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> USI
,
1187 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>>
1189 return MachOPlatformRuntimeState::get()
1190 .registerObjectPlatformSections(HeaderAddr
, std::move(USI
),
1196 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1197 __orc_rt_macho_deregister_object_platform_sections(char *ArgData
,
1199 return WrapperFunction
<SPSError(SPSExecutorAddr
,
1200 SPSOptional
<SPSUnwindSectionInfo
>,
1201 SPSMachOObjectPlatformSectionsMap
)>::
1202 handle(ArgData
, ArgSize
,
1203 [](ExecutorAddr HeaderAddr
, std::optional
<UnwindSectionInfo
> USI
,
1204 std::vector
<std::pair
<std::string_view
, ExecutorAddrRange
>>
1206 return MachOPlatformRuntimeState::get()
1207 .deregisterObjectPlatformSections(HeaderAddr
, std::move(USI
),
1213 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1214 __orc_rt_macho_run_wrapper_function_calls(char *ArgData
, size_t ArgSize
) {
1215 return WrapperFunction
<SPSError(SPSSequence
<SPSWrapperFunctionCall
>)>::handle(
1216 ArgData
, ArgSize
, runWrapperFunctionCalls
)
1220 //------------------------------------------------------------------------------
1222 //------------------------------------------------------------------------------
1224 ORC_RT_INTERFACE
void *__orc_rt_macho_tlv_get_addr_impl(TLVDescriptor
*D
) {
1225 auto *TLVMgr
= static_cast<MachOPlatformRuntimeTLVManager
*>(
1226 pthread_getspecific(D
->Key
));
1228 TLVMgr
= new MachOPlatformRuntimeTLVManager();
1229 if (pthread_setspecific(D
->Key
, TLVMgr
)) {
1230 __orc_rt_log_error("Call to pthread_setspecific failed");
1235 return TLVMgr
->getInstance(
1236 reinterpret_cast<char *>(static_cast<uintptr_t>(D
->DataAddress
)));
1239 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1240 __orc_rt_macho_create_pthread_key(char *ArgData
, size_t ArgSize
) {
1241 return WrapperFunction
<SPSExpected
<uint64_t>(void)>::handle(
1243 []() -> Expected
<uint64_t> {
1245 if (int Err
= pthread_key_create(&Key
, destroyMachOTLVMgr
)) {
1246 __orc_rt_log_error("Call to pthread_key_create failed");
1247 return make_error
<StringError
>(strerror(Err
));
1249 return static_cast<uint64_t>(Key
);
1254 //------------------------------------------------------------------------------
1255 // cxa_atexit support
1256 //------------------------------------------------------------------------------
1258 int __orc_rt_macho_cxa_atexit(void (*func
)(void *), void *arg
,
1260 return MachOPlatformRuntimeState::get().registerAtExit(func
, arg
, dso_handle
);
1263 void __orc_rt_macho_cxa_finalize(void *dso_handle
) {
1264 MachOPlatformRuntimeState::get().runAtExits(dso_handle
);
1267 //------------------------------------------------------------------------------
1268 // JIT'd dlfcn alternatives.
1269 //------------------------------------------------------------------------------
1271 const char *__orc_rt_macho_jit_dlerror() {
1272 return MachOPlatformRuntimeState::get().dlerror();
1275 void *__orc_rt_macho_jit_dlopen(const char *path
, int mode
) {
1276 return MachOPlatformRuntimeState::get().dlopen(path
, mode
);
1279 int __orc_rt_macho_jit_dlclose(void *dso_handle
) {
1280 return MachOPlatformRuntimeState::get().dlclose(dso_handle
);
1283 void *__orc_rt_macho_jit_dlsym(void *dso_handle
, const char *symbol
) {
1284 return MachOPlatformRuntimeState::get().dlsym(dso_handle
, symbol
);
1287 //------------------------------------------------------------------------------
1288 // MachO Run Program
1289 //------------------------------------------------------------------------------
1291 ORC_RT_INTERFACE
int64_t __orc_rt_macho_run_program(const char *JITDylibName
,
1292 const char *EntrySymbolName
,
1293 int argc
, char *argv
[]) {
1294 using MainTy
= int (*)(int, char *[]);
1296 void *H
= __orc_rt_macho_jit_dlopen(JITDylibName
,
1297 __orc_rt::macho::ORC_RT_RTLD_LAZY
);
1299 __orc_rt_log_error(__orc_rt_macho_jit_dlerror());
1304 reinterpret_cast<MainTy
>(__orc_rt_macho_jit_dlsym(H
, EntrySymbolName
));
1307 __orc_rt_log_error(__orc_rt_macho_jit_dlerror());
1311 int Result
= Main(argc
, argv
);
1313 if (__orc_rt_macho_jit_dlclose(H
) == -1)
1314 __orc_rt_log_error(__orc_rt_macho_jit_dlerror());