1 //===- macho_platform.cpp -------------------------------------------------===//
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 // This file contains code required to load the rest of the MachO runtime.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "macho_platform.h"
14 #include "bitmask_enum.h"
15 #include "common.h"
16 #include "debug.h"
17 #include "error.h"
18 #include "interval_map.h"
19 #include "wrapper_function_utils.h"
20 
21 #include <algorithm>
22 #include <ios>
23 #include <map>
24 #include <mutex>
25 #include <sstream>
26 #include <string_view>
27 #include <unordered_map>
28 #include <unordered_set>
29 #include <vector>
30 
31 #define DEBUG_TYPE "macho_platform"
32 
33 using namespace __orc_rt;
34 using namespace __orc_rt::macho;
35 
36 // Declare function tags for functions in the JIT process.
37 ORC_RT_JIT_DISPATCH_TAG(__orc_rt_macho_push_initializers_tag)
38 ORC_RT_JIT_DISPATCH_TAG(__orc_rt_macho_push_symbols_tag)
39 
40 struct objc_image_info;
41 struct mach_header;
42 
43 // Objective-C registration functions.
44 // These are weakly imported. If the Objective-C runtime has not been loaded
45 // then code containing Objective-C sections will generate an error.
46 extern "C" void
47 _objc_map_images(unsigned count, const char *const paths[],
48                  const mach_header *const mhdrs[]) ORC_RT_WEAK_IMPORT;
49 
50 extern "C" void _objc_load_image(const char *path,
51                                  const mach_header *mh) ORC_RT_WEAK_IMPORT;
52 
53 // Libunwind prototypes.
54 struct unw_dynamic_unwind_sections {
55   uintptr_t dso_base;
56   uintptr_t dwarf_section;
57   size_t dwarf_section_length;
58   uintptr_t compact_unwind_section;
59   size_t compact_unwind_section_length;
60 };
61 
62 typedef int (*unw_find_dynamic_unwind_sections)(
63     uintptr_t addr, struct unw_dynamic_unwind_sections *info);
64 
65 extern "C" int __unw_add_find_dynamic_unwind_sections(
66     unw_find_dynamic_unwind_sections find_dynamic_unwind_sections)
67     ORC_RT_WEAK_IMPORT;
68 
69 extern "C" int __unw_remove_find_dynamic_unwind_sections(
70     unw_find_dynamic_unwind_sections find_dynamic_unwind_sections)
71     ORC_RT_WEAK_IMPORT;
72 
73 namespace {
74 
75 struct MachOJITDylibDepInfo {
76   bool Sealed = false;
77   std::vector<ExecutorAddr> DepHeaders;
78 };
79 
80 using MachOJITDylibDepInfoMap =
81     std::unordered_map<ExecutorAddr, MachOJITDylibDepInfo>;
82 
83 } // anonymous namespace
84 
85 namespace __orc_rt {
86 
87 using SPSMachOObjectPlatformSectionsMap =
88     SPSSequence<SPSTuple<SPSString, SPSExecutorAddrRange>>;
89 
90 using SPSMachOJITDylibDepInfo = SPSTuple<bool, SPSSequence<SPSExecutorAddr>>;
91 
92 using SPSMachOJITDylibDepInfoMap =
93     SPSSequence<SPSTuple<SPSExecutorAddr, SPSMachOJITDylibDepInfo>>;
94 
95 template <>
96 class SPSSerializationTraits<SPSMachOJITDylibDepInfo, MachOJITDylibDepInfo> {
97 public:
98   static size_t size(const MachOJITDylibDepInfo &JDI) {
99     return SPSMachOJITDylibDepInfo::AsArgList::size(JDI.Sealed, JDI.DepHeaders);
100   }
101 
102   static bool serialize(SPSOutputBuffer &OB, const MachOJITDylibDepInfo &JDI) {
103     return SPSMachOJITDylibDepInfo::AsArgList::serialize(OB, JDI.Sealed,
104                                                          JDI.DepHeaders);
105   }
106 
107   static bool deserialize(SPSInputBuffer &IB, MachOJITDylibDepInfo &JDI) {
108     return SPSMachOJITDylibDepInfo::AsArgList::deserialize(IB, JDI.Sealed,
109                                                            JDI.DepHeaders);
110   }
111 };
112 
113 struct UnwindSectionInfo {
114   std::vector<ExecutorAddrRange> CodeRanges;
115   ExecutorAddrRange DwarfSection;
116   ExecutorAddrRange CompactUnwindSection;
117 };
118 
119 using SPSUnwindSectionInfo =
120     SPSTuple<SPSSequence<SPSExecutorAddrRange>, SPSExecutorAddrRange,
121              SPSExecutorAddrRange>;
122 
123 template <>
124 class SPSSerializationTraits<SPSUnwindSectionInfo, UnwindSectionInfo> {
125 public:
126   static size_t size(const UnwindSectionInfo &USI) {
127     return SPSUnwindSectionInfo::AsArgList::size(
128         USI.CodeRanges, USI.DwarfSection, USI.CompactUnwindSection);
129   }
130 
131   static bool serialize(SPSOutputBuffer &OB, const UnwindSectionInfo &USI) {
132     return SPSUnwindSectionInfo::AsArgList::serialize(
133         OB, USI.CodeRanges, USI.DwarfSection, USI.CompactUnwindSection);
134   }
135 
136   static bool deserialize(SPSInputBuffer &IB, UnwindSectionInfo &USI) {
137     return SPSUnwindSectionInfo::AsArgList::deserialize(
138         IB, USI.CodeRanges, USI.DwarfSection, USI.CompactUnwindSection);
139   }
140 };
141 
142 } // namespace __orc_rt
143 
144 namespace {
145 struct TLVDescriptor {
146   void *(*Thunk)(TLVDescriptor *) = nullptr;
147   unsigned long Key = 0;
148   unsigned long DataAddress = 0;
149 };
150 
151 class MachOPlatformRuntimeState {
152 public:
153   // Used internally by MachOPlatformRuntimeState, but made public to enable
154   // serialization.
155   enum class MachOExecutorSymbolFlags : uint8_t {
156     None = 0,
157     Weak = 1U << 0,
158     Callable = 1U << 1,
159     ORC_RT_MARK_AS_BITMASK_ENUM(/* LargestValue = */ Callable)
160   };
161 
162 private:
163   struct AtExitEntry {
164     void (*Func)(void *);
165     void *Arg;
166   };
167 
168   using AtExitsVector = std::vector<AtExitEntry>;
169 
170   /// Used to manage sections of fixed-sized metadata records (e.g. pointer
171   /// sections, selector refs, etc.)
172   template <typename RecordElement> class RecordSectionsTracker {
173   public:
174     /// Add a section to the "new" list.
175     void add(span<RecordElement> Sec) { New.push_back(std::move(Sec)); }
176 
177     /// Returns true if there are new sections to process.
178     bool hasNewSections() const { return !New.empty(); }
179 
180     /// Returns the number of new sections to process.
181     size_t numNewSections() const { return New.size(); }
182 
183     /// Process all new sections.
184     template <typename ProcessSectionFunc>
185     std::enable_if_t<std::is_void_v<
186         std::invoke_result_t<ProcessSectionFunc, span<RecordElement>>>>
187     processNewSections(ProcessSectionFunc &&ProcessSection) {
188       for (auto &Sec : New)
189         ProcessSection(Sec);
190       moveNewToProcessed();
191     }
192 
193     /// Proces all new sections with a fallible handler.
194     ///
195     /// Successfully handled sections will be moved to the Processed
196     /// list.
197     template <typename ProcessSectionFunc>
198     std::enable_if_t<
199         std::is_same_v<Error, std::invoke_result_t<ProcessSectionFunc,
200                                                    span<RecordElement>>>,
201         Error>
202     processNewSections(ProcessSectionFunc &&ProcessSection) {
203       for (size_t I = 0; I != New.size(); ++I) {
204         if (auto Err = ProcessSection(New[I])) {
205           for (size_t J = 0; J != I; ++J)
206             Processed.push_back(New[J]);
207           New.erase(New.begin(), New.begin() + I);
208           return Err;
209         }
210       }
211       moveNewToProcessed();
212       return Error::success();
213     }
214 
215     /// Move all sections back to New for reprocessing.
216     void reset() {
217       moveNewToProcessed();
218       New = std::move(Processed);
219     }
220 
221     /// Remove the section with the given range.
222     bool removeIfPresent(ExecutorAddrRange R) {
223       if (removeIfPresent(New, R))
224         return true;
225       return removeIfPresent(Processed, R);
226     }
227 
228   private:
229     void moveNewToProcessed() {
230       if (Processed.empty())
231         Processed = std::move(New);
232       else {
233         Processed.reserve(Processed.size() + New.size());
234         std::copy(New.begin(), New.end(), std::back_inserter(Processed));
235         New.clear();
236       }
237     }
238 
239     bool removeIfPresent(std::vector<span<RecordElement>> &V,
240                          ExecutorAddrRange R) {
241       auto RI = std::find_if(
242           V.rbegin(), V.rend(),
243           [RS = R.toSpan<RecordElement>()](const span<RecordElement> &E) {
244             return E.data() == RS.data();
245           });
246       if (RI != V.rend()) {
247         V.erase(std::next(RI).base());
248         return true;
249       }
250       return false;
251     }
252 
253     std::vector<span<RecordElement>> Processed;
254     std::vector<span<RecordElement>> New;
255   };
256 
257   struct UnwindSections {
258     UnwindSections(const UnwindSectionInfo &USI)
259         : DwarfSection(USI.DwarfSection.toSpan<char>()),
260           CompactUnwindSection(USI.CompactUnwindSection.toSpan<char>()) {}
261 
262     span<char> DwarfSection;
263     span<char> CompactUnwindSection;
264   };
265 
266   using UnwindSectionsMap =
267       IntervalMap<char *, UnwindSections, IntervalCoalescing::Disabled>;
268 
269   struct JITDylibState {
270 
271     using SymbolTableMap =
272         std::unordered_map<std::string_view,
273                            std::pair<ExecutorAddr, MachOExecutorSymbolFlags>>;
274 
275     std::string Name;
276     void *Header = nullptr;
277     bool Sealed = false;
278     size_t LinkedAgainstRefCount = 0;
279     size_t DlRefCount = 0;
280     SymbolTableMap SymbolTable;
281     std::vector<JITDylibState *> Deps;
282     AtExitsVector AtExits;
283     const objc_image_info *ObjCImageInfo = nullptr;
284     std::unordered_map<void *, std::vector<char>> DataSectionContent;
285     std::unordered_map<void *, size_t> ZeroInitRanges;
286     UnwindSectionsMap UnwindSections;
287     RecordSectionsTracker<void (*)()> ModInitsSections;
288     RecordSectionsTracker<char> ObjCRuntimeRegistrationObjects;
289 
290     bool referenced() const {
291       return LinkedAgainstRefCount != 0 || DlRefCount != 0;
292     }
293   };
294 
295 public:
296   static Error create();
297   static MachOPlatformRuntimeState &get();
298   static Error destroy();
299 
300   MachOPlatformRuntimeState() = default;
301 
302   // Delete copy and move constructors.
303   MachOPlatformRuntimeState(const MachOPlatformRuntimeState &) = delete;
304   MachOPlatformRuntimeState &
305   operator=(const MachOPlatformRuntimeState &) = delete;
306   MachOPlatformRuntimeState(MachOPlatformRuntimeState &&) = delete;
307   MachOPlatformRuntimeState &operator=(MachOPlatformRuntimeState &&) = delete;
308 
309   Error initialize();
310   Error shutdown();
311 
312   Error registerJITDylib(std::string Name, void *Header);
313   Error deregisterJITDylib(void *Header);
314   Error registerThreadDataSection(span<const char> ThreadDataSection);
315   Error deregisterThreadDataSection(span<const char> ThreadDataSection);
316   Error registerObjectSymbolTable(
317       ExecutorAddr HeaderAddr,
318       const std::vector<std::tuple<ExecutorAddr, ExecutorAddr,
319                                    MachOExecutorSymbolFlags>> &Entries);
320   Error deregisterObjectSymbolTable(
321       ExecutorAddr HeaderAddr,
322       const std::vector<std::tuple<ExecutorAddr, ExecutorAddr,
323                                    MachOExecutorSymbolFlags>> &Entries);
324   Error registerObjectPlatformSections(
325       ExecutorAddr HeaderAddr, std::optional<UnwindSectionInfo> UnwindSections,
326       std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs);
327   Error deregisterObjectPlatformSections(
328       ExecutorAddr HeaderAddr, std::optional<UnwindSectionInfo> UnwindSections,
329       std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs);
330 
331   const char *dlerror();
332   void *dlopen(std::string_view Name, int Mode);
333   int dlclose(void *DSOHandle);
334   void *dlsym(void *DSOHandle, const char *Symbol);
335 
336   int registerAtExit(void (*F)(void *), void *Arg, void *DSOHandle);
337   void runAtExits(std::unique_lock<std::mutex> &JDStatesLock,
338                   JITDylibState &JDS);
339   void runAtExits(void *DSOHandle);
340 
341   /// Returns the base address of the section containing ThreadData.
342   Expected<std::pair<const char *, size_t>>
343   getThreadDataSectionFor(const char *ThreadData);
344 
345 private:
346   JITDylibState *getJITDylibStateByHeader(void *DSOHandle);
347   JITDylibState *getJITDylibStateByName(std::string_view Path);
348 
349   /// Requests materialization of the given symbols. For each pair, the bool
350   /// element indicates whether the symbol is required (true) or weakly
351   /// referenced (false).
352   Error requestPushSymbols(JITDylibState &JDS,
353                            span<std::pair<std::string_view, bool>> Symbols);
354 
355   /// Attempts to look up the given symbols locally, requesting a push from the
356   /// remote if they're not found. Results are written to the Result span, which
357   /// must have the same size as the Symbols span.
358   Error
359   lookupSymbols(JITDylibState &JDS, std::unique_lock<std::mutex> &JDStatesLock,
360                 span<std::pair<ExecutorAddr, MachOExecutorSymbolFlags>> Result,
361                 span<std::pair<std::string_view, bool>> Symbols);
362 
363   bool lookupUnwindSections(void *Addr, unw_dynamic_unwind_sections &Info);
364 
365   static int findDynamicUnwindSections(uintptr_t addr,
366                                        unw_dynamic_unwind_sections *info);
367   static Error registerEHFrames(span<const char> EHFrameSection);
368   static Error deregisterEHFrames(span<const char> EHFrameSection);
369 
370   static Error registerObjCRegistrationObjects(JITDylibState &JDS);
371   static Error runModInits(std::unique_lock<std::mutex> &JDStatesLock,
372                            JITDylibState &JDS);
373 
374   Expected<void *> dlopenImpl(std::string_view Path, int Mode);
375   Error dlopenFull(std::unique_lock<std::mutex> &JDStatesLock,
376                    JITDylibState &JDS);
377   Error dlopenInitialize(std::unique_lock<std::mutex> &JDStatesLock,
378                          JITDylibState &JDS, MachOJITDylibDepInfoMap &DepInfo);
379 
380   Error dlcloseImpl(void *DSOHandle);
381   Error dlcloseDeinitialize(std::unique_lock<std::mutex> &JDStatesLock,
382                             JITDylibState &JDS);
383 
384   static MachOPlatformRuntimeState *MOPS;
385 
386   bool UseCallbackStyleUnwindInfo = false;
387 
388   // FIXME: Move to thread-state.
389   std::string DLFcnError;
390 
391   // APIMutex guards against concurrent entry into key "dyld" API functions
392   // (e.g. dlopen, dlclose).
393   std::recursive_mutex DyldAPIMutex;
394 
395   // JDStatesMutex guards the data structures that hold JITDylib state.
396   std::mutex JDStatesMutex;
397   std::unordered_map<void *, JITDylibState> JDStates;
398   std::unordered_map<std::string_view, void *> JDNameToHeader;
399 
400   // ThreadDataSectionsMutex guards thread local data section state.
401   std::mutex ThreadDataSectionsMutex;
402   std::map<const char *, size_t> ThreadDataSections;
403 };
404 
405 } // anonymous namespace
406 
407 namespace __orc_rt {
408 
409 class SPSMachOExecutorSymbolFlags;
410 
411 template <>
412 class SPSSerializationTraits<
413     SPSMachOExecutorSymbolFlags,
414     MachOPlatformRuntimeState::MachOExecutorSymbolFlags> {
415 private:
416   using UT = std::underlying_type_t<
417       MachOPlatformRuntimeState::MachOExecutorSymbolFlags>;
418 
419 public:
420   static size_t
421   size(const MachOPlatformRuntimeState::MachOExecutorSymbolFlags &SF) {
422     return sizeof(UT);
423   }
424 
425   static bool
426   serialize(SPSOutputBuffer &OB,
427             const MachOPlatformRuntimeState::MachOExecutorSymbolFlags &SF) {
428     return SPSArgList<UT>::serialize(OB, static_cast<UT>(SF));
429   }
430 
431   static bool
432   deserialize(SPSInputBuffer &IB,
433               MachOPlatformRuntimeState::MachOExecutorSymbolFlags &SF) {
434     UT Tmp;
435     if (!SPSArgList<UT>::deserialize(IB, Tmp))
436       return false;
437     SF = static_cast<MachOPlatformRuntimeState::MachOExecutorSymbolFlags>(Tmp);
438     return true;
439   }
440 };
441 
442 } // namespace __orc_rt
443 
444 namespace {
445 
446 MachOPlatformRuntimeState *MachOPlatformRuntimeState::MOPS = nullptr;
447 
448 Error MachOPlatformRuntimeState::create() {
449   assert(!MOPS && "MachOPlatformRuntimeState should be null");
450   MOPS = new MachOPlatformRuntimeState();
451   return MOPS->initialize();
452 }
453 
454 MachOPlatformRuntimeState &MachOPlatformRuntimeState::get() {
455   assert(MOPS && "MachOPlatformRuntimeState not initialized");
456   return *MOPS;
457 }
458 
459 Error MachOPlatformRuntimeState::destroy() {
460   assert(MOPS && "MachOPlatformRuntimeState not initialized");
461   auto Err = MOPS->shutdown();
462   delete MOPS;
463   return Err;
464 }
465 
466 Error MachOPlatformRuntimeState::initialize() {
467   UseCallbackStyleUnwindInfo = __unw_add_find_dynamic_unwind_sections &&
468                                __unw_remove_find_dynamic_unwind_sections;
469   if (UseCallbackStyleUnwindInfo) {
470     ORC_RT_DEBUG({
471       printdbg("__unw_add/remove_find_dynamic_unwind_sections available."
472                " Using callback-based frame info lookup.\n");
473     });
474     if (__unw_add_find_dynamic_unwind_sections(&findDynamicUnwindSections))
475       return make_error<StringError>(
476           "Could not register findDynamicUnwindSections");
477   } else {
478     ORC_RT_DEBUG({
479       printdbg("__unw_add/remove_find_dynamic_unwind_sections not available."
480                " Using classic frame info registration.\n");
481     });
482   }
483   return Error::success();
484 }
485 
486 Error MachOPlatformRuntimeState::shutdown() {
487   if (UseCallbackStyleUnwindInfo) {
488     if (__unw_remove_find_dynamic_unwind_sections(&findDynamicUnwindSections)) {
489       ORC_RT_DEBUG(
490           { printdbg("__unw_remove_find_dynamic_unwind_sections failed.\n"); });
491     }
492   }
493   return Error::success();
494 }
495 
496 Error MachOPlatformRuntimeState::registerJITDylib(std::string Name,
497                                                   void *Header) {
498   ORC_RT_DEBUG({
499     printdbg("Registering JITDylib %s: Header = %p\n", Name.c_str(), Header);
500   });
501   std::lock_guard<std::mutex> Lock(JDStatesMutex);
502   if (JDStates.count(Header)) {
503     std::ostringstream ErrStream;
504     ErrStream << "Duplicate JITDylib registration for header " << Header
505               << " (name = " << Name << ")";
506     return make_error<StringError>(ErrStream.str());
507   }
508   if (JDNameToHeader.count(Name)) {
509     std::ostringstream ErrStream;
510     ErrStream << "Duplicate JITDylib registration for header " << Header
511               << " (header = " << Header << ")";
512     return make_error<StringError>(ErrStream.str());
513   }
514 
515   auto &JDS = JDStates[Header];
516   JDS.Name = std::move(Name);
517   JDS.Header = Header;
518   JDNameToHeader[JDS.Name] = Header;
519   return Error::success();
520 }
521 
522 Error MachOPlatformRuntimeState::deregisterJITDylib(void *Header) {
523   std::lock_guard<std::mutex> Lock(JDStatesMutex);
524   auto I = JDStates.find(Header);
525   if (I == JDStates.end()) {
526     std::ostringstream ErrStream;
527     ErrStream << "Attempted to deregister unrecognized header " << Header;
528     return make_error<StringError>(ErrStream.str());
529   }
530 
531   // Remove std::string construction once we can use C++20.
532   auto J = JDNameToHeader.find(
533       std::string(I->second.Name.data(), I->second.Name.size()));
534   assert(J != JDNameToHeader.end() &&
535          "Missing JDNameToHeader entry for JITDylib");
536 
537   ORC_RT_DEBUG({
538     printdbg("Deregistering JITDylib %s: Header = %p\n", I->second.Name.c_str(),
539              Header);
540   });
541 
542   JDNameToHeader.erase(J);
543   JDStates.erase(I);
544   return Error::success();
545 }
546 
547 Error MachOPlatformRuntimeState::registerThreadDataSection(
548     span<const char> ThreadDataSection) {
549   std::lock_guard<std::mutex> Lock(ThreadDataSectionsMutex);
550   auto I = ThreadDataSections.upper_bound(ThreadDataSection.data());
551   if (I != ThreadDataSections.begin()) {
552     auto J = std::prev(I);
553     if (J->first + J->second > ThreadDataSection.data())
554       return make_error<StringError>("Overlapping __thread_data sections");
555   }
556   ThreadDataSections.insert(
557       I, std::make_pair(ThreadDataSection.data(), ThreadDataSection.size()));
558   return Error::success();
559 }
560 
561 Error MachOPlatformRuntimeState::deregisterThreadDataSection(
562     span<const char> ThreadDataSection) {
563   std::lock_guard<std::mutex> Lock(ThreadDataSectionsMutex);
564   auto I = ThreadDataSections.find(ThreadDataSection.data());
565   if (I == ThreadDataSections.end())
566     return make_error<StringError>("Attempt to deregister unknown thread data "
567                                    "section");
568   ThreadDataSections.erase(I);
569   return Error::success();
570 }
571 
572 Error MachOPlatformRuntimeState::registerObjectSymbolTable(
573     ExecutorAddr HeaderAddr,
574     const std::vector<std::tuple<ExecutorAddr, ExecutorAddr,
575                                  MachOExecutorSymbolFlags>> &Entries) {
576 
577   std::lock_guard<std::mutex> Lock(JDStatesMutex);
578   auto *JDS = getJITDylibStateByHeader(HeaderAddr.toPtr<void *>());
579   if (!JDS) {
580     std::ostringstream ErrStream;
581     ErrStream << "Could not register object platform sections for "
582                  "unrecognized header "
583               << HeaderAddr.toPtr<void *>();
584     return make_error<StringError>(ErrStream.str());
585   }
586 
587   for (auto &[NameAddr, SymAddr, Flags] : Entries)
588     JDS->SymbolTable[NameAddr.toPtr<const char *>()] = {SymAddr, Flags};
589 
590   return Error::success();
591 }
592 
593 Error MachOPlatformRuntimeState::deregisterObjectSymbolTable(
594     ExecutorAddr HeaderAddr,
595     const std::vector<std::tuple<ExecutorAddr, ExecutorAddr,
596                                  MachOExecutorSymbolFlags>> &Entries) {
597 
598   std::lock_guard<std::mutex> Lock(JDStatesMutex);
599   auto *JDS = getJITDylibStateByHeader(HeaderAddr.toPtr<void *>());
600   if (!JDS) {
601     std::ostringstream ErrStream;
602     ErrStream << "Could not register object platform sections for "
603                  "unrecognized header "
604               << HeaderAddr.toPtr<void *>();
605     return make_error<StringError>(ErrStream.str());
606   }
607 
608   for (auto &[NameAddr, SymAddr, Flags] : Entries)
609     JDS->SymbolTable.erase(NameAddr.toPtr<const char *>());
610 
611   return Error::success();
612 }
613 
614 Error MachOPlatformRuntimeState::registerObjectPlatformSections(
615     ExecutorAddr HeaderAddr, std::optional<UnwindSectionInfo> UnwindInfo,
616     std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs) {
617 
618   // FIXME: Reject platform section registration after the JITDylib is
619   // sealed?
620 
621   ORC_RT_DEBUG({
622     printdbg("MachOPlatform: Registering object sections for %p.\n",
623              HeaderAddr.toPtr<void *>());
624   });
625 
626   std::lock_guard<std::mutex> Lock(JDStatesMutex);
627   auto *JDS = getJITDylibStateByHeader(HeaderAddr.toPtr<void *>());
628   if (!JDS) {
629     std::ostringstream ErrStream;
630     ErrStream << "Could not register object platform sections for "
631                  "unrecognized header "
632               << HeaderAddr.toPtr<void *>();
633     return make_error<StringError>(ErrStream.str());
634   }
635 
636   if (UnwindInfo && UseCallbackStyleUnwindInfo) {
637     ORC_RT_DEBUG({
638       printdbg("  Registering new-style unwind info for:\n"
639                "    DWARF: %p -- %p\n"
640                "    Compact-unwind: %p -- %p\n"
641                "  for:\n",
642                UnwindInfo->DwarfSection.Start.toPtr<void *>(),
643                UnwindInfo->DwarfSection.End.toPtr<void *>(),
644                UnwindInfo->CompactUnwindSection.Start.toPtr<void *>(),
645                UnwindInfo->CompactUnwindSection.End.toPtr<void *>());
646     });
647     for (auto &CodeRange : UnwindInfo->CodeRanges) {
648       JDS->UnwindSections.insert(CodeRange.Start.toPtr<char *>(),
649                                  CodeRange.End.toPtr<char *>(), *UnwindInfo);
650       ORC_RT_DEBUG({
651         printdbg("    [ %p -- %p ]\n", CodeRange.Start.toPtr<void *>(),
652                  CodeRange.End.toPtr<void *>());
653       });
654     }
655   }
656 
657   for (auto &KV : Secs) {
658     // FIXME: Validate section ranges?
659     if (KV.first == "__TEXT,__eh_frame") {
660       if (!UseCallbackStyleUnwindInfo) {
661         // Use classic libunwind registration.
662         if (auto Err = registerEHFrames(KV.second.toSpan<const char>()))
663           return Err;
664       }
665     } else if (KV.first == "__DATA,__data") {
666       assert(!JDS->DataSectionContent.count(KV.second.Start.toPtr<char *>()) &&
667              "Address already registered.");
668       auto S = KV.second.toSpan<char>();
669       JDS->DataSectionContent[KV.second.Start.toPtr<char *>()] =
670           std::vector<char>(S.begin(), S.end());
671     } else if (KV.first == "__DATA,__common") {
672       JDS->ZeroInitRanges[KV.second.Start.toPtr<char *>()] = KV.second.size();
673     } else if (KV.first == "__DATA,__thread_data") {
674       if (auto Err = registerThreadDataSection(KV.second.toSpan<const char>()))
675         return Err;
676     } else if (KV.first == "__llvm_jitlink_ObjCRuntimeRegistrationObject")
677       JDS->ObjCRuntimeRegistrationObjects.add(KV.second.toSpan<char>());
678     else if (KV.first == "__DATA,__mod_init_func")
679       JDS->ModInitsSections.add(KV.second.toSpan<void (*)()>());
680     else {
681       // Should this be a warning instead?
682       return make_error<StringError>(
683           "Encountered unexpected section " +
684           std::string(KV.first.data(), KV.first.size()) +
685           " while registering object platform sections");
686     }
687   }
688 
689   return Error::success();
690 }
691 
692 Error MachOPlatformRuntimeState::deregisterObjectPlatformSections(
693     ExecutorAddr HeaderAddr, std::optional<UnwindSectionInfo> UnwindInfo,
694     std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs) {
695   // TODO: Make this more efficient? (maybe unnecessary if removal is rare?)
696   // TODO: Add a JITDylib prepare-for-teardown operation that clears all
697   //       registered sections, causing this function to take the fast-path.
698   ORC_RT_DEBUG({
699     printdbg("MachOPlatform: Deregistering object sections for %p.\n",
700              HeaderAddr.toPtr<void *>());
701   });
702 
703   std::lock_guard<std::mutex> Lock(JDStatesMutex);
704   auto *JDS = getJITDylibStateByHeader(HeaderAddr.toPtr<void *>());
705   if (!JDS) {
706     std::ostringstream ErrStream;
707     ErrStream << "Could not register object platform sections for unrecognized "
708                  "header "
709               << HeaderAddr.toPtr<void *>();
710     return make_error<StringError>(ErrStream.str());
711   }
712 
713   // FIXME: Implement faster-path by returning immediately if JDS is being
714   // torn down entirely?
715 
716   // TODO: Make library permanent (i.e. not able to be dlclosed) if it contains
717   // any Swift or ObjC. Once this happens we can clear (and no longer record)
718   // data section content, as the library could never be re-initialized.
719 
720   if (UnwindInfo && UseCallbackStyleUnwindInfo) {
721     ORC_RT_DEBUG({
722       printdbg("  Deregistering new-style unwind info for:\n"
723                "    DWARF: %p -- %p\n"
724                "    Compact-unwind: %p -- %p\n"
725                "  for:\n",
726                UnwindInfo->DwarfSection.Start.toPtr<void *>(),
727                UnwindInfo->DwarfSection.End.toPtr<void *>(),
728                UnwindInfo->CompactUnwindSection.Start.toPtr<void *>(),
729                UnwindInfo->CompactUnwindSection.End.toPtr<void *>());
730     });
731     for (auto &CodeRange : UnwindInfo->CodeRanges) {
732       JDS->UnwindSections.erase(CodeRange.Start.toPtr<char *>(),
733                                 CodeRange.End.toPtr<char *>());
734       ORC_RT_DEBUG({
735         printdbg("    [ %p -- %p ]\n", CodeRange.Start.toPtr<void *>(),
736                  CodeRange.End.toPtr<void *>());
737       });
738     }
739   }
740 
741   for (auto &KV : Secs) {
742     // FIXME: Validate section ranges?
743     if (KV.first == "__TEXT,__eh_frame") {
744       if (!UseCallbackStyleUnwindInfo) {
745         // Use classic libunwind registration.
746         if (auto Err = deregisterEHFrames(KV.second.toSpan<const char>()))
747           return Err;
748       }
749     } else if (KV.first == "__DATA,__data") {
750       JDS->DataSectionContent.erase(KV.second.Start.toPtr<char *>());
751     } else if (KV.first == "__DATA,__common") {
752       JDS->ZeroInitRanges.erase(KV.second.Start.toPtr<char *>());
753     } else if (KV.first == "__DATA,__thread_data") {
754       if (auto Err =
755               deregisterThreadDataSection(KV.second.toSpan<const char>()))
756         return Err;
757     } else if (KV.first == "__llvm_jitlink_ObjCRuntimeRegistrationObject")
758       JDS->ObjCRuntimeRegistrationObjects.removeIfPresent(KV.second);
759     else if (KV.first == "__DATA,__mod_init_func")
760       JDS->ModInitsSections.removeIfPresent(KV.second);
761     else {
762       // Should this be a warning instead?
763       return make_error<StringError>(
764           "Encountered unexpected section " +
765           std::string(KV.first.data(), KV.first.size()) +
766           " while deregistering object platform sections");
767     }
768   }
769   return Error::success();
770 }
771 
772 const char *MachOPlatformRuntimeState::dlerror() { return DLFcnError.c_str(); }
773 
774 void *MachOPlatformRuntimeState::dlopen(std::string_view Path, int Mode) {
775   ORC_RT_DEBUG({
776     std::string S(Path.data(), Path.size());
777     printdbg("MachOPlatform::dlopen(\"%s\")\n", S.c_str());
778   });
779   std::lock_guard<std::recursive_mutex> Lock(DyldAPIMutex);
780   if (auto H = dlopenImpl(Path, Mode))
781     return *H;
782   else {
783     // FIXME: Make dlerror thread safe.
784     DLFcnError = toString(H.takeError());
785     return nullptr;
786   }
787 }
788 
789 int MachOPlatformRuntimeState::dlclose(void *DSOHandle) {
790   ORC_RT_DEBUG({
791     auto *JDS = getJITDylibStateByHeader(DSOHandle);
792     std::string DylibName;
793     if (JDS) {
794       std::string S;
795       printdbg("MachOPlatform::dlclose(%p) (%s)\n", DSOHandle, S.c_str());
796     } else
797       printdbg("MachOPlatform::dlclose(%p) (%s)\n", DSOHandle,
798                "invalid handle");
799   });
800   std::lock_guard<std::recursive_mutex> Lock(DyldAPIMutex);
801   if (auto Err = dlcloseImpl(DSOHandle)) {
802     // FIXME: Make dlerror thread safe.
803     DLFcnError = toString(std::move(Err));
804     return -1;
805   }
806   return 0;
807 }
808 
809 void *MachOPlatformRuntimeState::dlsym(void *DSOHandle, const char *Symbol) {
810   std::unique_lock<std::mutex> Lock(JDStatesMutex);
811   auto *JDS = getJITDylibStateByHeader(DSOHandle);
812   if (!JDS) {
813     std::ostringstream ErrStream;
814     ErrStream << "In call to dlsym, unrecognized header address " << DSOHandle;
815     DLFcnError = ErrStream.str();
816     return nullptr;
817   }
818 
819   std::string MangledName = std::string("_") + Symbol;
820   std::pair<std::string_view, bool> Lookup(MangledName, false);
821   std::pair<ExecutorAddr, MachOExecutorSymbolFlags> Result;
822 
823   if (auto Err = lookupSymbols(*JDS, Lock, {&Result, 1}, {&Lookup, 1})) {
824     DLFcnError = toString(std::move(Err));
825     return nullptr;
826   }
827 
828   return Result.first.toPtr<void *>();
829 }
830 
831 int MachOPlatformRuntimeState::registerAtExit(void (*F)(void *), void *Arg,
832                                               void *DSOHandle) {
833   // FIXME: Handle out-of-memory errors, returning -1 if OOM.
834   std::lock_guard<std::mutex> Lock(JDStatesMutex);
835   auto *JDS = getJITDylibStateByHeader(DSOHandle);
836   if (!JDS) {
837     ORC_RT_DEBUG({
838       printdbg("MachOPlatformRuntimeState::registerAtExit called with "
839                "unrecognized dso handle %p\n",
840                DSOHandle);
841     });
842     return -1;
843   }
844   JDS->AtExits.push_back({F, Arg});
845   return 0;
846 }
847 
848 void MachOPlatformRuntimeState::runAtExits(
849     std::unique_lock<std::mutex> &JDStatesLock, JITDylibState &JDS) {
850   auto AtExits = std::move(JDS.AtExits);
851 
852   // Unlock while running atexits, as they may trigger operations that modify
853   // JDStates.
854   JDStatesLock.unlock();
855   while (!AtExits.empty()) {
856     auto &AE = AtExits.back();
857     AE.Func(AE.Arg);
858     AtExits.pop_back();
859   }
860   JDStatesLock.lock();
861 }
862 
863 void MachOPlatformRuntimeState::runAtExits(void *DSOHandle) {
864   std::unique_lock<std::mutex> Lock(JDStatesMutex);
865   auto *JDS = getJITDylibStateByHeader(DSOHandle);
866   ORC_RT_DEBUG({
867     printdbg("MachOPlatformRuntimeState::runAtExits called on unrecognized "
868              "dso_handle %p\n",
869              DSOHandle);
870   });
871   if (JDS)
872     runAtExits(Lock, *JDS);
873 }
874 
875 Expected<std::pair<const char *, size_t>>
876 MachOPlatformRuntimeState::getThreadDataSectionFor(const char *ThreadData) {
877   std::lock_guard<std::mutex> Lock(ThreadDataSectionsMutex);
878   auto I = ThreadDataSections.upper_bound(ThreadData);
879   // Check that we have a valid entry covering this address.
880   if (I == ThreadDataSections.begin())
881     return make_error<StringError>("No thread local data section for key");
882   I = std::prev(I);
883   if (ThreadData >= I->first + I->second)
884     return make_error<StringError>("No thread local data section for key");
885   return *I;
886 }
887 
888 MachOPlatformRuntimeState::JITDylibState *
889 MachOPlatformRuntimeState::getJITDylibStateByHeader(void *DSOHandle) {
890   auto I = JDStates.find(DSOHandle);
891   if (I == JDStates.end()) {
892     I = JDStates.insert(std::make_pair(DSOHandle, JITDylibState())).first;
893     I->second.Header = DSOHandle;
894   }
895   return &I->second;
896 }
897 
898 MachOPlatformRuntimeState::JITDylibState *
899 MachOPlatformRuntimeState::getJITDylibStateByName(std::string_view Name) {
900   // FIXME: Avoid creating string once we have C++20.
901   auto I = JDNameToHeader.find(std::string(Name.data(), Name.size()));
902   if (I != JDNameToHeader.end())
903     return getJITDylibStateByHeader(I->second);
904   return nullptr;
905 }
906 
907 Error MachOPlatformRuntimeState::requestPushSymbols(
908     JITDylibState &JDS, span<std::pair<std::string_view, bool>> Symbols) {
909   Error OpErr = Error::success();
910   if (auto Err = WrapperFunction<SPSError(
911           SPSExecutorAddr, SPSSequence<SPSTuple<SPSString, bool>>)>::
912           call(&__orc_rt_macho_push_symbols_tag, OpErr,
913                ExecutorAddr::fromPtr(JDS.Header), Symbols)) {
914     cantFail(std::move(OpErr));
915     return std::move(Err);
916   }
917   return OpErr;
918 }
919 
920 Error MachOPlatformRuntimeState::lookupSymbols(
921     JITDylibState &JDS, std::unique_lock<std::mutex> &JDStatesLock,
922     span<std::pair<ExecutorAddr, MachOExecutorSymbolFlags>> Result,
923     span<std::pair<std::string_view, bool>> Symbols) {
924   assert(JDStatesLock.owns_lock() &&
925          "JDStatesLock should be locked at call-site");
926   assert(Result.size() == Symbols.size() &&
927          "Results and Symbols span sizes should match");
928 
929   // Make an initial pass over the local symbol table.
930   std::vector<size_t> MissingSymbolIndexes;
931   for (size_t Idx = 0; Idx != Symbols.size(); ++Idx) {
932     auto I = JDS.SymbolTable.find(Symbols[Idx].first);
933     if (I != JDS.SymbolTable.end())
934       Result[Idx] = I->second;
935     else
936       MissingSymbolIndexes.push_back(Idx);
937   }
938 
939   // If everything has been resolved already then bail out early.
940   if (MissingSymbolIndexes.empty())
941     return Error::success();
942 
943   // Otherwise call back to the controller to try to request that the symbol
944   // be materialized.
945   std::vector<std::pair<std::string_view, bool>> MissingSymbols;
946   MissingSymbols.reserve(MissingSymbolIndexes.size());
947   ORC_RT_DEBUG({
948     printdbg("requesting push of %i missing symbols...\n",
949              MissingSymbolIndexes.size());
950   });
951   for (auto MissingIdx : MissingSymbolIndexes)
952     MissingSymbols.push_back(Symbols[MissingIdx]);
953 
954   JDStatesLock.unlock();
955   if (auto Err = requestPushSymbols(
956           JDS, {MissingSymbols.data(), MissingSymbols.size()}))
957     return Err;
958   JDStatesLock.lock();
959 
960   // Try to resolve the previously missing symbols locally.
961   std::vector<size_t> MissingRequiredSymbols;
962   for (auto MissingIdx : MissingSymbolIndexes) {
963     auto I = JDS.SymbolTable.find(Symbols[MissingIdx].first);
964     if (I != JDS.SymbolTable.end())
965       Result[MissingIdx] = I->second;
966     else {
967       if (Symbols[MissingIdx].second)
968         MissingRequiredSymbols.push_back(MissingIdx);
969       else
970         Result[MissingIdx] = {ExecutorAddr(), {}};
971     }
972   }
973 
974   // Error out if any missing symbols could not be resolved.
975   if (!MissingRequiredSymbols.empty()) {
976     std::ostringstream ErrStream;
977     ErrStream << "Lookup could not find required symbols: [ ";
978     for (auto MissingIdx : MissingRequiredSymbols)
979       ErrStream << "\"" << Symbols[MissingIdx].first << "\" ";
980     ErrStream << "]";
981     return make_error<StringError>(ErrStream.str());
982   }
983 
984   return Error::success();
985 }
986 
987 // eh-frame registration functions.
988 // We expect these to be available for all processes.
989 extern "C" void __register_frame(const void *);
990 extern "C" void __deregister_frame(const void *);
991 
992 template <typename HandleFDEFn>
993 void walkEHFrameSection(span<const char> EHFrameSection,
994                         HandleFDEFn HandleFDE) {
995   const char *CurCFIRecord = EHFrameSection.data();
996   uint64_t Size = *reinterpret_cast<const uint32_t *>(CurCFIRecord);
997 
998   while (CurCFIRecord != EHFrameSection.end() && Size != 0) {
999     const char *OffsetField = CurCFIRecord + (Size == 0xffffffff ? 12 : 4);
1000     if (Size == 0xffffffff)
1001       Size = *reinterpret_cast<const uint64_t *>(CurCFIRecord + 4) + 12;
1002     else
1003       Size += 4;
1004     uint32_t Offset = *reinterpret_cast<const uint32_t *>(OffsetField);
1005 
1006     if (Offset != 0)
1007       HandleFDE(CurCFIRecord);
1008 
1009     CurCFIRecord += Size;
1010     Size = *reinterpret_cast<const uint32_t *>(CurCFIRecord);
1011   }
1012 }
1013 
1014 bool MachOPlatformRuntimeState::lookupUnwindSections(
1015     void *Addr, unw_dynamic_unwind_sections &Info) {
1016   ORC_RT_DEBUG(
1017       { printdbg("Tried to lookup unwind-info via new lookup call.\n"); });
1018   std::lock_guard<std::mutex> Lock(JDStatesMutex);
1019   for (auto &KV : JDStates) {
1020     auto &JD = KV.second;
1021     auto I = JD.UnwindSections.find(reinterpret_cast<char *>(Addr));
1022     if (I != JD.UnwindSections.end()) {
1023       Info.dso_base = reinterpret_cast<uintptr_t>(JD.Header);
1024       Info.dwarf_section =
1025           reinterpret_cast<uintptr_t>(I->second.DwarfSection.data());
1026       Info.dwarf_section_length = I->second.DwarfSection.size();
1027       Info.compact_unwind_section =
1028           reinterpret_cast<uintptr_t>(I->second.CompactUnwindSection.data());
1029       Info.compact_unwind_section_length =
1030           I->second.CompactUnwindSection.size();
1031       return true;
1032     }
1033   }
1034   return false;
1035 }
1036 
1037 int MachOPlatformRuntimeState::findDynamicUnwindSections(
1038     uintptr_t addr, unw_dynamic_unwind_sections *info) {
1039   if (!info)
1040     return 0;
1041   return MachOPlatformRuntimeState::get().lookupUnwindSections((void *)addr,
1042                                                                *info);
1043 }
1044 
1045 Error MachOPlatformRuntimeState::registerEHFrames(
1046     span<const char> EHFrameSection) {
1047   walkEHFrameSection(EHFrameSection, __register_frame);
1048   return Error::success();
1049 }
1050 
1051 Error MachOPlatformRuntimeState::deregisterEHFrames(
1052     span<const char> EHFrameSection) {
1053   walkEHFrameSection(EHFrameSection, __deregister_frame);
1054   return Error::success();
1055 }
1056 
1057 Error MachOPlatformRuntimeState::registerObjCRegistrationObjects(
1058     JITDylibState &JDS) {
1059   ORC_RT_DEBUG(printdbg("Registering Objective-C / Swift metadata.\n"));
1060 
1061   std::vector<char *> RegObjBases;
1062   JDS.ObjCRuntimeRegistrationObjects.processNewSections(
1063       [&](span<char> RegObj) { RegObjBases.push_back(RegObj.data()); });
1064 
1065   if (RegObjBases.empty())
1066     return Error::success();
1067 
1068   if (!_objc_map_images || !_objc_load_image)
1069     return make_error<StringError>(
1070         "Could not register Objective-C / Swift metadata: _objc_map_images / "
1071         "_objc_load_image not found");
1072 
1073   std::vector<char *> Paths;
1074   Paths.resize(RegObjBases.size());
1075   _objc_map_images(RegObjBases.size(), Paths.data(),
1076                    reinterpret_cast<mach_header **>(RegObjBases.data()));
1077 
1078   for (void *RegObjBase : RegObjBases)
1079     _objc_load_image(nullptr, reinterpret_cast<mach_header *>(RegObjBase));
1080 
1081   return Error::success();
1082 }
1083 
1084 Error MachOPlatformRuntimeState::runModInits(
1085     std::unique_lock<std::mutex> &JDStatesLock, JITDylibState &JDS) {
1086   std::vector<span<void (*)()>> InitSections;
1087   InitSections.reserve(JDS.ModInitsSections.numNewSections());
1088 
1089   // Copy initializer sections: If the JITDylib is unsealed then the
1090   // initializers could reach back into the JIT and cause more initializers to
1091   // be added.
1092   // FIXME: Skip unlock and run in-place on sealed JITDylibs?
1093   JDS.ModInitsSections.processNewSections(
1094       [&](span<void (*)()> Inits) { InitSections.push_back(Inits); });
1095 
1096   JDStatesLock.unlock();
1097   for (auto InitSec : InitSections)
1098     for (auto *Init : InitSec)
1099       Init();
1100   JDStatesLock.lock();
1101 
1102   return Error::success();
1103 }
1104 
1105 Expected<void *> MachOPlatformRuntimeState::dlopenImpl(std::string_view Path,
1106                                                        int Mode) {
1107   std::unique_lock<std::mutex> Lock(JDStatesMutex);
1108 
1109   // Try to find JITDylib state by name.
1110   auto *JDS = getJITDylibStateByName(Path);
1111 
1112   if (!JDS)
1113     return make_error<StringError>("No registered JTIDylib for path " +
1114                                    std::string(Path.data(), Path.size()));
1115 
1116   // If this JITDylib is unsealed, or this is the first dlopen then run
1117   // full dlopen path (update deps, push and run initializers, update ref
1118   // counts on all JITDylibs in the dep tree).
1119   if (!JDS->referenced() || !JDS->Sealed) {
1120     if (auto Err = dlopenFull(Lock, *JDS))
1121       return std::move(Err);
1122   }
1123 
1124   // Bump the ref-count on this dylib.
1125   ++JDS->DlRefCount;
1126 
1127   // Return the header address.
1128   return JDS->Header;
1129 }
1130 
1131 Error MachOPlatformRuntimeState::dlopenFull(
1132     std::unique_lock<std::mutex> &JDStatesLock, JITDylibState &JDS) {
1133   // Call back to the JIT to push the initializers.
1134   Expected<MachOJITDylibDepInfoMap> DepInfo((MachOJITDylibDepInfoMap()));
1135   // Unlock so that we can accept the initializer update.
1136   JDStatesLock.unlock();
1137   if (auto Err = WrapperFunction<SPSExpected<SPSMachOJITDylibDepInfoMap>(
1138           SPSExecutorAddr)>::call(&__orc_rt_macho_push_initializers_tag,
1139                                   DepInfo, ExecutorAddr::fromPtr(JDS.Header)))
1140     return Err;
1141   JDStatesLock.lock();
1142 
1143   if (!DepInfo)
1144     return DepInfo.takeError();
1145 
1146   if (auto Err = dlopenInitialize(JDStatesLock, JDS, *DepInfo))
1147     return Err;
1148 
1149   if (!DepInfo->empty()) {
1150     ORC_RT_DEBUG({
1151       printdbg("Unrecognized dep-info key headers in dlopen of %s\n",
1152                JDS.Name.c_str());
1153     });
1154     std::ostringstream ErrStream;
1155     ErrStream << "Encountered unrecognized dep-info key headers "
1156                  "while processing dlopen of "
1157               << JDS.Name;
1158     return make_error<StringError>(ErrStream.str());
1159   }
1160 
1161   return Error::success();
1162 }
1163 
1164 Error MachOPlatformRuntimeState::dlopenInitialize(
1165     std::unique_lock<std::mutex> &JDStatesLock, JITDylibState &JDS,
1166     MachOJITDylibDepInfoMap &DepInfo) {
1167   ORC_RT_DEBUG({
1168     printdbg("MachOPlatformRuntimeState::dlopenInitialize(\"%s\")\n",
1169              JDS.Name.c_str());
1170   });
1171 
1172   // If the header is not present in the dep map then assume that we
1173   // already processed it earlier in the dlopenInitialize traversal and
1174   // return.
1175   // TODO: Keep a visited set instead so that we can error out on missing
1176   //       entries?
1177   auto I = DepInfo.find(ExecutorAddr::fromPtr(JDS.Header));
1178   if (I == DepInfo.end())
1179     return Error::success();
1180 
1181   auto DI = std::move(I->second);
1182   DepInfo.erase(I);
1183 
1184   // We don't need to re-initialize sealed JITDylibs that have already been
1185   // initialized. Just check that their dep-map entry is empty as expected.
1186   if (JDS.Sealed) {
1187     if (!DI.DepHeaders.empty()) {
1188       std::ostringstream ErrStream;
1189       ErrStream << "Sealed JITDylib " << JDS.Header
1190                 << " already has registered dependencies";
1191       return make_error<StringError>(ErrStream.str());
1192     }
1193     if (JDS.referenced())
1194       return Error::success();
1195   } else
1196     JDS.Sealed = DI.Sealed;
1197 
1198   // This is an unsealed or newly sealed JITDylib. Run initializers.
1199   std::vector<JITDylibState *> OldDeps;
1200   std::swap(JDS.Deps, OldDeps);
1201   JDS.Deps.reserve(DI.DepHeaders.size());
1202   for (auto DepHeaderAddr : DI.DepHeaders) {
1203     auto *DepJDS = getJITDylibStateByHeader(DepHeaderAddr.toPtr<void *>());
1204     if (!DepJDS) {
1205       std::ostringstream ErrStream;
1206       ErrStream << "Encountered unrecognized dep header "
1207                 << DepHeaderAddr.toPtr<void *>() << " while initializing "
1208                 << JDS.Name;
1209       return make_error<StringError>(ErrStream.str());
1210     }
1211     ++DepJDS->LinkedAgainstRefCount;
1212     if (auto Err = dlopenInitialize(JDStatesLock, *DepJDS, DepInfo))
1213       return Err;
1214   }
1215 
1216   // Initialize this JITDylib.
1217   if (auto Err = registerObjCRegistrationObjects(JDS))
1218     return Err;
1219   if (auto Err = runModInits(JDStatesLock, JDS))
1220     return Err;
1221 
1222   // Decrement old deps.
1223   // FIXME: We should probably continue and just report deinitialize errors
1224   // here.
1225   for (auto *DepJDS : OldDeps) {
1226     --DepJDS->LinkedAgainstRefCount;
1227     if (!DepJDS->referenced())
1228       if (auto Err = dlcloseDeinitialize(JDStatesLock, *DepJDS))
1229         return Err;
1230   }
1231 
1232   return Error::success();
1233 }
1234 
1235 Error MachOPlatformRuntimeState::dlcloseImpl(void *DSOHandle) {
1236   std::unique_lock<std::mutex> Lock(JDStatesMutex);
1237 
1238   // Try to find JITDylib state by header.
1239   auto *JDS = getJITDylibStateByHeader(DSOHandle);
1240 
1241   if (!JDS) {
1242     std::ostringstream ErrStream;
1243     ErrStream << "No registered JITDylib for " << DSOHandle;
1244     return make_error<StringError>(ErrStream.str());
1245   }
1246 
1247   // Bump the ref-count.
1248   --JDS->DlRefCount;
1249 
1250   if (!JDS->referenced())
1251     return dlcloseDeinitialize(Lock, *JDS);
1252 
1253   return Error::success();
1254 }
1255 
1256 Error MachOPlatformRuntimeState::dlcloseDeinitialize(
1257     std::unique_lock<std::mutex> &JDStatesLock, JITDylibState &JDS) {
1258 
1259   ORC_RT_DEBUG({
1260     printdbg("MachOPlatformRuntimeState::dlcloseDeinitialize(\"%s\")\n",
1261              JDS.Name.c_str());
1262   });
1263 
1264   runAtExits(JDStatesLock, JDS);
1265 
1266   // Reset mod-inits
1267   JDS.ModInitsSections.reset();
1268 
1269   // Reset data section contents.
1270   for (auto &KV : JDS.DataSectionContent)
1271     memcpy(KV.first, KV.second.data(), KV.second.size());
1272   for (auto &KV : JDS.ZeroInitRanges)
1273     memset(KV.first, 0, KV.second);
1274 
1275   // Deinitialize any dependencies.
1276   for (auto *DepJDS : JDS.Deps) {
1277     --DepJDS->LinkedAgainstRefCount;
1278     if (!DepJDS->referenced())
1279       if (auto Err = dlcloseDeinitialize(JDStatesLock, *DepJDS))
1280         return Err;
1281   }
1282 
1283   return Error::success();
1284 }
1285 
1286 class MachOPlatformRuntimeTLVManager {
1287 public:
1288   void *getInstance(const char *ThreadData);
1289 
1290 private:
1291   std::unordered_map<const char *, char *> Instances;
1292   std::unordered_map<const char *, std::unique_ptr<char[]>> AllocatedSections;
1293 };
1294 
1295 void *MachOPlatformRuntimeTLVManager::getInstance(const char *ThreadData) {
1296   auto I = Instances.find(ThreadData);
1297   if (I != Instances.end())
1298     return I->second;
1299 
1300   auto TDS =
1301       MachOPlatformRuntimeState::get().getThreadDataSectionFor(ThreadData);
1302   if (!TDS) {
1303     __orc_rt_log_error(toString(TDS.takeError()).c_str());
1304     return nullptr;
1305   }
1306 
1307   auto &Allocated = AllocatedSections[TDS->first];
1308   if (!Allocated) {
1309     Allocated = std::make_unique<char[]>(TDS->second);
1310     memcpy(Allocated.get(), TDS->first, TDS->second);
1311   }
1312 
1313   size_t ThreadDataDelta = ThreadData - TDS->first;
1314   assert(ThreadDataDelta <= TDS->second && "ThreadData outside section bounds");
1315 
1316   char *Instance = Allocated.get() + ThreadDataDelta;
1317   Instances[ThreadData] = Instance;
1318   return Instance;
1319 }
1320 
1321 void destroyMachOTLVMgr(void *MachOTLVMgr) {
1322   delete static_cast<MachOPlatformRuntimeTLVManager *>(MachOTLVMgr);
1323 }
1324 
1325 Error runWrapperFunctionCalls(std::vector<WrapperFunctionCall> WFCs) {
1326   for (auto &WFC : WFCs)
1327     if (auto Err = WFC.runWithSPSRet<void>())
1328       return Err;
1329   return Error::success();
1330 }
1331 
1332 } // end anonymous namespace
1333 
1334 //------------------------------------------------------------------------------
1335 //                             JIT entry points
1336 //------------------------------------------------------------------------------
1337 
1338 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1339 __orc_rt_macho_platform_bootstrap(char *ArgData, size_t ArgSize) {
1340   return WrapperFunction<SPSError()>::handle(
1341              ArgData, ArgSize,
1342              []() { return MachOPlatformRuntimeState::create(); })
1343       .release();
1344 }
1345 
1346 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1347 __orc_rt_macho_platform_shutdown(char *ArgData, size_t ArgSize) {
1348   return WrapperFunction<SPSError()>::handle(
1349              ArgData, ArgSize,
1350              []() { return MachOPlatformRuntimeState::destroy(); })
1351       .release();
1352 }
1353 
1354 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1355 __orc_rt_macho_register_jitdylib(char *ArgData, size_t ArgSize) {
1356   return WrapperFunction<SPSError(SPSString, SPSExecutorAddr)>::handle(
1357              ArgData, ArgSize,
1358              [](std::string &Name, ExecutorAddr HeaderAddr) {
1359                return MachOPlatformRuntimeState::get().registerJITDylib(
1360                    std::move(Name), HeaderAddr.toPtr<void *>());
1361              })
1362       .release();
1363 }
1364 
1365 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1366 __orc_rt_macho_deregister_jitdylib(char *ArgData, size_t ArgSize) {
1367   return WrapperFunction<SPSError(SPSExecutorAddr)>::handle(
1368              ArgData, ArgSize,
1369              [](ExecutorAddr HeaderAddr) {
1370                return MachOPlatformRuntimeState::get().deregisterJITDylib(
1371                    HeaderAddr.toPtr<void *>());
1372              })
1373       .release();
1374 }
1375 
1376 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1377 __orc_rt_macho_register_object_platform_sections(char *ArgData,
1378                                                  size_t ArgSize) {
1379   return WrapperFunction<SPSError(SPSExecutorAddr,
1380                                   SPSOptional<SPSUnwindSectionInfo>,
1381                                   SPSMachOObjectPlatformSectionsMap)>::
1382       handle(ArgData, ArgSize,
1383              [](ExecutorAddr HeaderAddr, std::optional<UnwindSectionInfo> USI,
1384                 std::vector<std::pair<std::string_view, ExecutorAddrRange>>
1385                     &Secs) {
1386                return MachOPlatformRuntimeState::get()
1387                    .registerObjectPlatformSections(HeaderAddr, std::move(USI),
1388                                                    std::move(Secs));
1389              })
1390           .release();
1391 }
1392 
1393 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1394 __orc_rt_macho_register_object_symbol_table(char *ArgData, size_t ArgSize) {
1395   using SymtabContainer = std::vector<
1396       std::tuple<ExecutorAddr, ExecutorAddr,
1397                  MachOPlatformRuntimeState::MachOExecutorSymbolFlags>>;
1398   return WrapperFunction<SPSError(
1399       SPSExecutorAddr, SPSSequence<SPSTuple<SPSExecutorAddr, SPSExecutorAddr,
1400                                             SPSMachOExecutorSymbolFlags>>)>::
1401       handle(ArgData, ArgSize,
1402              [](ExecutorAddr HeaderAddr, SymtabContainer &Symbols) {
1403                return MachOPlatformRuntimeState::get()
1404                    .registerObjectSymbolTable(HeaderAddr, Symbols);
1405              })
1406           .release();
1407 }
1408 
1409 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1410 __orc_rt_macho_deregister_object_symbol_table(char *ArgData, size_t ArgSize) {
1411   using SymtabContainer = std::vector<
1412       std::tuple<ExecutorAddr, ExecutorAddr,
1413                  MachOPlatformRuntimeState::MachOExecutorSymbolFlags>>;
1414   return WrapperFunction<SPSError(
1415       SPSExecutorAddr, SPSSequence<SPSTuple<SPSExecutorAddr, SPSExecutorAddr,
1416                                             SPSMachOExecutorSymbolFlags>>)>::
1417       handle(ArgData, ArgSize,
1418              [](ExecutorAddr HeaderAddr, SymtabContainer &Symbols) {
1419                return MachOPlatformRuntimeState::get()
1420                    .deregisterObjectSymbolTable(HeaderAddr, Symbols);
1421              })
1422           .release();
1423 }
1424 
1425 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1426 __orc_rt_macho_deregister_object_platform_sections(char *ArgData,
1427                                                    size_t ArgSize) {
1428   return WrapperFunction<SPSError(SPSExecutorAddr,
1429                                   SPSOptional<SPSUnwindSectionInfo>,
1430                                   SPSMachOObjectPlatformSectionsMap)>::
1431       handle(ArgData, ArgSize,
1432              [](ExecutorAddr HeaderAddr, std::optional<UnwindSectionInfo> USI,
1433                 std::vector<std::pair<std::string_view, ExecutorAddrRange>>
1434                     &Secs) {
1435                return MachOPlatformRuntimeState::get()
1436                    .deregisterObjectPlatformSections(HeaderAddr, std::move(USI),
1437                                                      std::move(Secs));
1438              })
1439           .release();
1440 }
1441 
1442 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1443 __orc_rt_macho_run_wrapper_function_calls(char *ArgData, size_t ArgSize) {
1444   return WrapperFunction<SPSError(SPSSequence<SPSWrapperFunctionCall>)>::handle(
1445              ArgData, ArgSize, runWrapperFunctionCalls)
1446       .release();
1447 }
1448 
1449 //------------------------------------------------------------------------------
1450 //                            TLV support
1451 //------------------------------------------------------------------------------
1452 
1453 ORC_RT_INTERFACE void *__orc_rt_macho_tlv_get_addr_impl(TLVDescriptor *D) {
1454   auto *TLVMgr = static_cast<MachOPlatformRuntimeTLVManager *>(
1455       pthread_getspecific(D->Key));
1456   if (!TLVMgr) {
1457     TLVMgr = new MachOPlatformRuntimeTLVManager();
1458     if (pthread_setspecific(D->Key, TLVMgr)) {
1459       __orc_rt_log_error("Call to pthread_setspecific failed");
1460       return nullptr;
1461     }
1462   }
1463 
1464   return TLVMgr->getInstance(
1465       reinterpret_cast<char *>(static_cast<uintptr_t>(D->DataAddress)));
1466 }
1467 
1468 ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
1469 __orc_rt_macho_create_pthread_key(char *ArgData, size_t ArgSize) {
1470   return WrapperFunction<SPSExpected<uint64_t>(void)>::handle(
1471              ArgData, ArgSize,
1472              []() -> Expected<uint64_t> {
1473                pthread_key_t Key;
1474                if (int Err = pthread_key_create(&Key, destroyMachOTLVMgr)) {
1475                  __orc_rt_log_error("Call to pthread_key_create failed");
1476                  return make_error<StringError>(strerror(Err));
1477                }
1478                return static_cast<uint64_t>(Key);
1479              })
1480       .release();
1481 }
1482 
1483 //------------------------------------------------------------------------------
1484 //                           cxa_atexit support
1485 //------------------------------------------------------------------------------
1486 
1487 int __orc_rt_macho_cxa_atexit(void (*func)(void *), void *arg,
1488                               void *dso_handle) {
1489   return MachOPlatformRuntimeState::get().registerAtExit(func, arg, dso_handle);
1490 }
1491 
1492 void __orc_rt_macho_cxa_finalize(void *dso_handle) {
1493   MachOPlatformRuntimeState::get().runAtExits(dso_handle);
1494 }
1495 
1496 //------------------------------------------------------------------------------
1497 //                        JIT'd dlfcn alternatives.
1498 //------------------------------------------------------------------------------
1499 
1500 const char *__orc_rt_macho_jit_dlerror() {
1501   return MachOPlatformRuntimeState::get().dlerror();
1502 }
1503 
1504 void *__orc_rt_macho_jit_dlopen(const char *path, int mode) {
1505   return MachOPlatformRuntimeState::get().dlopen(path, mode);
1506 }
1507 
1508 int __orc_rt_macho_jit_dlclose(void *dso_handle) {
1509   return MachOPlatformRuntimeState::get().dlclose(dso_handle);
1510 }
1511 
1512 void *__orc_rt_macho_jit_dlsym(void *dso_handle, const char *symbol) {
1513   return MachOPlatformRuntimeState::get().dlsym(dso_handle, symbol);
1514 }
1515 
1516 //------------------------------------------------------------------------------
1517 //                             MachO Run Program
1518 //------------------------------------------------------------------------------
1519 
1520 ORC_RT_INTERFACE int64_t __orc_rt_macho_run_program(const char *JITDylibName,
1521                                                     const char *EntrySymbolName,
1522                                                     int argc, char *argv[]) {
1523   using MainTy = int (*)(int, char *[]);
1524 
1525   void *H = __orc_rt_macho_jit_dlopen(JITDylibName,
1526                                       __orc_rt::macho::ORC_RT_RTLD_LAZY);
1527   if (!H) {
1528     __orc_rt_log_error(__orc_rt_macho_jit_dlerror());
1529     return -1;
1530   }
1531 
1532   auto *Main =
1533       reinterpret_cast<MainTy>(__orc_rt_macho_jit_dlsym(H, EntrySymbolName));
1534 
1535   if (!Main) {
1536     __orc_rt_log_error(__orc_rt_macho_jit_dlerror());
1537     return -1;
1538   }
1539 
1540   int Result = Main(argc, argv);
1541 
1542   if (__orc_rt_macho_jit_dlclose(H) == -1)
1543     __orc_rt_log_error(__orc_rt_macho_jit_dlerror());
1544 
1545   return Result;
1546 }
1547