LLVM 24.0.0git
MachOPlatform.cpp
Go to the documentation of this file.
1//===------ MachOPlatform.cpp - Utilities for executing MachO in Orc ------===//
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
10
20#include "llvm/Support/Debug.h"
21#include <optional>
22
23#define DEBUG_TYPE "orc"
24
25using namespace llvm;
26using namespace llvm::orc;
27using namespace llvm::orc::shared;
28
29namespace llvm {
30namespace orc {
31namespace shared {
32
36
37class SPSMachOExecutorSymbolFlags;
38
39template <>
41 MachOPlatform::MachOJITDylibDepInfo> {
42public:
43 static size_t size(const MachOPlatform::MachOJITDylibDepInfo &DDI) {
44 return SPSMachOJITDylibDepInfo::AsArgList::size(DDI.Sealed, DDI.DepHeaders);
45 }
46
47 static bool serialize(SPSOutputBuffer &OB,
49 return SPSMachOJITDylibDepInfo::AsArgList::serialize(OB, DDI.Sealed,
50 DDI.DepHeaders);
51 }
52
53 static bool deserialize(SPSInputBuffer &IB,
55 return SPSMachOJITDylibDepInfo::AsArgList::deserialize(IB, DDI.Sealed,
56 DDI.DepHeaders);
57 }
58};
59
60template <>
61class SPSSerializationTraits<SPSMachOExecutorSymbolFlags,
62 MachOPlatform::MachOExecutorSymbolFlags> {
63private:
64 using UT = std::underlying_type_t<MachOPlatform::MachOExecutorSymbolFlags>;
65
66public:
68 return sizeof(UT);
69 }
70
71 static bool serialize(SPSOutputBuffer &OB,
73 return SPSArgList<UT>::serialize(OB, static_cast<UT>(SF));
74 }
75
76 static bool deserialize(SPSInputBuffer &IB,
78 UT Tmp;
79 if (!SPSArgList<UT>::deserialize(IB, Tmp))
80 return false;
81 SF = static_cast<MachOPlatform::MachOExecutorSymbolFlags>(Tmp);
82 return true;
83 }
84};
85
86} // namespace shared
87} // namespace orc
88} // namespace llvm
89
90namespace {
91
92using SPSRegisterSymbolsArgs =
95 SPSMachOExecutorSymbolFlags>>>;
96
97std::unique_ptr<jitlink::LinkGraph> createPlatformGraph(MachOPlatform &MOP,
98 std::string Name) {
99 auto &ES = MOP.getExecutionSession();
100 return std::make_unique<jitlink::LinkGraph>(
101 std::move(Name), ES.getSymbolStringPool(), ES.getTargetTriple(),
103}
104
105// Creates a Bootstrap-Complete LinkGraph to run deferred actions.
106class MachOPlatformCompleteBootstrapMaterializationUnit
107 : public MaterializationUnit {
108public:
109 using SymbolTableVector =
110 SmallVector<std::tuple<ExecutorAddr, ExecutorAddr,
112
113 MachOPlatformCompleteBootstrapMaterializationUnit(
114 MachOPlatform &MOP, StringRef PlatformJDName,
115 SymbolStringPtr CompleteBootstrapSymbol, SymbolTableVector SymTab,
116 shared::AllocActions DeferredAAs, ExecutorAddr MachOHeaderAddr,
117 ExecutorAddr PlatformBootstrap, ExecutorAddr PlatformShutdown,
118 ExecutorAddr RegisterJITDylib, ExecutorAddr DeregisterJITDylib,
119 ExecutorAddr RegisterObjectSymbolTable,
120 ExecutorAddr DeregisterObjectSymbolTable)
121 : MaterializationUnit(
122 {{{CompleteBootstrapSymbol, JITSymbolFlags::None}}, nullptr}),
123 MOP(MOP), PlatformJDName(PlatformJDName),
124 CompleteBootstrapSymbol(std::move(CompleteBootstrapSymbol)),
125 SymTab(std::move(SymTab)), DeferredAAs(std::move(DeferredAAs)),
126 MachOHeaderAddr(MachOHeaderAddr), PlatformBootstrap(PlatformBootstrap),
127 PlatformShutdown(PlatformShutdown), RegisterJITDylib(RegisterJITDylib),
128 DeregisterJITDylib(DeregisterJITDylib),
129 RegisterObjectSymbolTable(RegisterObjectSymbolTable),
130 DeregisterObjectSymbolTable(DeregisterObjectSymbolTable) {}
131
132 StringRef getName() const override {
133 return "MachOPlatformCompleteBootstrap";
134 }
135
136 void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
137 using namespace jitlink;
138 auto G = createPlatformGraph(MOP, "<OrcRTCompleteBootstrap>");
139 auto &PlaceholderSection =
140 G->createSection("__orc_rt_cplt_bs", MemProt::Read);
141 auto &PlaceholderBlock =
142 G->createZeroFillBlock(PlaceholderSection, 1, ExecutorAddr(), 1, 0);
143 G->addDefinedSymbol(PlaceholderBlock, 0, *CompleteBootstrapSymbol, 1,
144 Linkage::Strong, Scope::Hidden, false, true);
145
146 // Reserve space for the stolen actions, plus two extras.
147 G->allocActions().reserve(DeferredAAs.size() + 3);
148
149 // 1. Bootstrap the platform support code.
150 G->allocActions().push_back(
151 {cantFail(WrapperFunctionCall::Create<SPSArgList<>>(PlatformBootstrap)),
152 cantFail(
153 WrapperFunctionCall::Create<SPSArgList<>>(PlatformShutdown))});
154
155 // 2. Register the platform JITDylib.
156 G->allocActions().push_back(
158 SPSArgList<SPSString, SPSExecutorAddr>>(
159 RegisterJITDylib, PlatformJDName, MachOHeaderAddr)),
160 cantFail(WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>(
161 DeregisterJITDylib, MachOHeaderAddr))});
162
163 // 3. Register deferred symbols.
164 G->allocActions().push_back(
166 RegisterObjectSymbolTable, MachOHeaderAddr, SymTab)),
168 DeregisterObjectSymbolTable, MachOHeaderAddr, SymTab))});
169
170 // 4. Add the deferred actions to the graph.
171 std::move(DeferredAAs.begin(), DeferredAAs.end(),
172 std::back_inserter(G->allocActions()));
173
174 MOP.getObjectLinkingLayer().emit(std::move(R), std::move(G));
175 }
176
177 void discard(const JITDylib &JD, const SymbolStringPtr &Sym) override {}
178
179private:
180 MachOPlatform &MOP;
181 StringRef PlatformJDName;
182 SymbolStringPtr CompleteBootstrapSymbol;
183 SymbolTableVector SymTab;
184 shared::AllocActions DeferredAAs;
185 ExecutorAddr MachOHeaderAddr;
186 ExecutorAddr PlatformBootstrap;
187 ExecutorAddr PlatformShutdown;
188 ExecutorAddr RegisterJITDylib;
189 ExecutorAddr DeregisterJITDylib;
190 ExecutorAddr RegisterObjectSymbolTable;
191 ExecutorAddr DeregisterObjectSymbolTable;
192};
193
194static StringRef ObjCRuntimeObjectSectionsData[] = {
201
202static StringRef ObjCRuntimeObjectSectionsText[] = {
208
209static StringRef ObjCRuntimeObjectSectionName =
210 "__llvm_jitlink_ObjCRuntimeRegistrationObject";
211
212static StringRef ObjCImageInfoSymbolName =
213 "__llvm_jitlink_macho_objc_imageinfo";
214
215struct ObjCImageInfoFlags {
216 uint16_t SwiftABIVersion;
217 uint16_t SwiftVersion;
218 bool HasCategoryClassProperties;
219 bool HasSignedObjCClassROs;
220
221 static constexpr uint32_t SIGNED_CLASS_RO = (1 << 4);
222 static constexpr uint32_t HAS_CATEGORY_CLASS_PROPERTIES = (1 << 6);
223
224 explicit ObjCImageInfoFlags(uint32_t RawFlags) {
225 HasSignedObjCClassROs = RawFlags & SIGNED_CLASS_RO;
226 HasCategoryClassProperties = RawFlags & HAS_CATEGORY_CLASS_PROPERTIES;
227 SwiftABIVersion = (RawFlags >> 8) & 0xFF;
228 SwiftVersion = (RawFlags >> 16) & 0xFFFF;
229 }
230
231 uint32_t rawFlags() const {
232 uint32_t Result = 0;
233 if (HasCategoryClassProperties)
234 Result |= HAS_CATEGORY_CLASS_PROPERTIES;
235 if (HasSignedObjCClassROs)
236 Result |= SIGNED_CLASS_RO;
237 Result |= (SwiftABIVersion << 8);
238 Result |= (SwiftVersion << 16);
239 return Result;
240 }
241};
242} // end anonymous namespace
243
244namespace llvm {
245namespace orc {
246
247std::optional<MachOPlatform::HeaderOptions::BuildVersionOpts>
250 uint32_t SDK) {
251
253 switch (TT.getOS()) {
254 case Triple::IOS:
255 Platform = TT.isSimulatorEnvironment() ? MachO::PLATFORM_IOSSIMULATOR
256 : MachO::PLATFORM_IOS;
257 break;
258 case Triple::MacOSX:
259 Platform = MachO::PLATFORM_MACOS;
260 break;
261 case Triple::TvOS:
262 Platform = TT.isSimulatorEnvironment() ? MachO::PLATFORM_TVOSSIMULATOR
263 : MachO::PLATFORM_TVOS;
264 break;
265 case Triple::WatchOS:
266 Platform = TT.isSimulatorEnvironment() ? MachO::PLATFORM_WATCHOSSIMULATOR
267 : MachO::PLATFORM_WATCHOS;
268 break;
269 case Triple::XROS:
270 Platform = TT.isSimulatorEnvironment() ? MachO::PLATFORM_XROS_SIMULATOR
271 : MachO::PLATFORM_XROS;
272 break;
273 default:
274 return std::nullopt;
275 }
276
278}
279
282 std::unique_ptr<DefinitionGenerator> OrcRuntime,
283 HeaderOptionsBuilder BuildHeaderOpts,
284 HeaderOptions PlatformJDOpts,
285 MachOHeaderMUBuilder BuildMachOHeaderMU,
286 std::optional<SymbolAliasMap> RuntimeAliases) {
287
288 auto &ES = ObjLinkingLayer.getExecutionSession();
289
290 // If the target is not supported then bail out immediately.
291 if (!supportedTarget(ES.getTargetTriple()))
292 return make_error<StringError>("Unsupported MachOPlatform triple: " +
293 ES.getTargetTriple().str(),
295
296 // Create default aliases if the caller didn't supply any.
297 if (!RuntimeAliases)
298 RuntimeAliases = standardPlatformAliases(ES);
299
300 // Define the aliases.
301 if (auto Err = PlatformJD.define(symbolAliases(std::move(*RuntimeAliases))))
302 return std::move(Err);
303
304 {
305 // Add JIT dispatch reexports from bootstrap JITDylib.
306 if (auto Err = PlatformJD.define(reexports(
307 ES.getBootstrapJITDylib(),
308 {{ES.intern("___orc_rt_jit_dispatch"),
309 {ES.intern(rt::DispatchName),
310 JITSymbolFlags::Exported | JITSymbolFlags::Callable}},
311 {ES.intern("___orc_rt_jit_dispatch_ctx"),
312 {ES.intern(rt::DispatchCtxName), JITSymbolFlags::Exported}}})))
313 return Err;
314 }
315
316 // Create the instance.
317 Error Err = Error::success();
318 auto P = std::unique_ptr<MachOPlatform>(
319 new MachOPlatform(ObjLinkingLayer, PlatformJD, std::move(OrcRuntime),
320 std::move(BuildHeaderOpts), std::move(PlatformJDOpts),
321 std::move(BuildMachOHeaderMU), Err));
322 if (Err)
323 return std::move(Err);
324 return std::move(P);
325}
326
328 ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD,
329 const char *OrcRuntimePath, HeaderOptionsBuilder BuildHeaderOpts,
330 HeaderOptions PlatformJDOpts, MachOHeaderMUBuilder BuildMachOHeaderMU,
331 std::optional<SymbolAliasMap> RuntimeAliases) {
332
333 // Create a generator for the ORC runtime archive.
334 auto OrcRuntimeArchiveGenerator =
335 StaticLibraryDefinitionGenerator::Load(ObjLinkingLayer, OrcRuntimePath);
336 if (!OrcRuntimeArchiveGenerator)
337 return OrcRuntimeArchiveGenerator.takeError();
338
339 return Create(ObjLinkingLayer, PlatformJD,
340 std::move(*OrcRuntimeArchiveGenerator),
341 std::move(BuildHeaderOpts), std::move(PlatformJDOpts),
342 std::move(BuildMachOHeaderMU), std::move(RuntimeAliases));
343}
344
346 return setupJITDylib(JD, BuildHeaderOpts(JD));
347}
348
350 if (auto Err = JD.define(BuildMachOHeaderMU(*this, std::move(Opts))))
351 return Err;
352
353 return ES.lookup({&JD}, MachOHeaderStartSymbol).takeError();
354}
355
357 std::lock_guard<std::mutex> Lock(PlatformMutex);
358 auto I = JITDylibToHeaderAddr.find(&JD);
359 if (I != JITDylibToHeaderAddr.end()) {
360 assert(HeaderAddrToJITDylib.count(I->second) &&
361 "HeaderAddrToJITDylib missing entry");
362 HeaderAddrToJITDylib.erase(I->second);
363 JITDylibToHeaderAddr.erase(I);
364 }
365 JITDylibToPThreadKey.erase(&JD);
366 return Error::success();
367}
368
370 const MaterializationUnit &MU) {
371 auto &JD = RT.getJITDylib();
372 const auto &InitSym = MU.getInitializerSymbol();
373 if (!InitSym)
374 return Error::success();
375
376 RegisteredInitSymbols[&JD].add(InitSym,
378 LLVM_DEBUG({
379 dbgs() << "MachOPlatform: Registered init symbol " << *InitSym << " for MU "
380 << MU.getName() << "\n";
381 });
382 return Error::success();
383}
384
388
390 ArrayRef<std::pair<const char *, const char *>> AL) {
391 for (auto &KV : AL) {
392 auto AliasName = ES.intern(KV.first);
393 assert(!Aliases.count(AliasName) && "Duplicate symbol name in alias map");
394 Aliases[std::move(AliasName)] = {ES.intern(KV.second),
396 }
397}
398
406
409 static const std::pair<const char *, const char *> RequiredCXXAliases[] = {
410 {"___cxa_atexit", "___orc_rt_macho_cxa_atexit"}};
411
412 return ArrayRef<std::pair<const char *, const char *>>(RequiredCXXAliases);
413}
414
417 static const std::pair<const char *, const char *>
418 StandardRuntimeUtilityAliases[] = {
419 {"___orc_rt_run_program", "___orc_rt_macho_run_program"},
420 {"___orc_rt_jit_dlerror", "___orc_rt_macho_jit_dlerror"},
421 {"___orc_rt_jit_dlopen", "___orc_rt_macho_jit_dlopen"},
422 {"___orc_rt_jit_dlupdate", "___orc_rt_macho_jit_dlupdate"},
423 {"___orc_rt_jit_dlclose", "___orc_rt_macho_jit_dlclose"},
424 {"___orc_rt_jit_dlsym", "___orc_rt_macho_jit_dlsym"},
425 {"___orc_rt_log_error", "___orc_rt_log_error_to_stderr"}};
426
428 StandardRuntimeUtilityAliases);
429}
430
433 static const std::pair<const char *, const char *>
434 StandardLazyCompilationAliases[] = {
435 {"__orc_rt_reenter", "__orc_rt_sysv_reenter"},
436 {"__orc_rt_resolve_tag", "___orc_rt_resolve_tag"}};
437
439 StandardLazyCompilationAliases);
440}
441
445
446bool MachOPlatform::supportedTarget(const Triple &TT) {
447 switch (TT.getArch()) {
448 case Triple::aarch64:
449 case Triple::x86_64:
450 return true;
451 default:
452 return false;
453 }
454}
455
456jitlink::Edge::Kind MachOPlatform::getPointerEdgeKind(jitlink::LinkGraph &G) {
457 switch (G.getTargetTriple().getArch()) {
458 case Triple::aarch64:
460 case Triple::x86_64:
462 default:
463 llvm_unreachable("Unsupported architecture");
464 }
465}
466
468MachOPlatform::flagsForSymbol(jitlink::Symbol &Sym) {
472
473 if (Sym.isCallable())
475
476 return Flags;
477}
478
479MachOPlatform::MachOPlatform(
480 ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD,
481 std::unique_ptr<DefinitionGenerator> OrcRuntimeGenerator,
482 HeaderOptionsBuilder BuildHeaderOpts, HeaderOptions PlatformJDOpts,
483 MachOHeaderMUBuilder BuildMachOHeaderMU, Error &Err)
484 : ES(ObjLinkingLayer.getExecutionSession()), PlatformJD(PlatformJD),
485 ObjLinkingLayer(ObjLinkingLayer),
486 BuildHeaderOpts(std::move(BuildHeaderOpts)),
487 BuildMachOHeaderMU(std::move(BuildMachOHeaderMU)) {
488 ErrorAsOutParameter _(Err);
489 ObjLinkingLayer.addPlugin(std::make_unique<MachOPlatformPlugin>(*this));
490 PlatformJD.addGenerator(std::move(OrcRuntimeGenerator));
491
492 {
493 // Check for force-eh-frame
494 std::optional<bool> ForceEHFrames;
495 if ((Err = ES.getBootstrapMapValue<bool, bool>("darwin-use-ehframes-only",
496 ForceEHFrames)))
497 return;
498 this->ForceEHFrames = ForceEHFrames.value_or(false);
499 }
500
501 BootstrapInfo BI;
502 Bootstrap = &BI;
503
504 // Bootstrap process -- here be phase-ordering dragons.
505 //
506 // The MachOPlatform class uses allocation actions to register metadata
507 // sections with the ORC runtime, however the runtime contains metadata
508 // registration functions that have their own metadata that they need to
509 // register (e.g. the frame-info registration functions have frame-info).
510 // We can't use an ordinary lookup to find these registration functions
511 // because their address is needed during the link of the containing graph
512 // itself (to build the allocation actions that will call the registration
513 // functions). Further complicating the situation (a) the graph containing
514 // the registration functions is allowed to depend on other graphs (e.g. the
515 // graph containing the ORC runtime RTTI support) so we need to handle an
516 // unknown set of dependencies during bootstrap, and (b) these graphs may
517 // be linked concurrently if the user has installed a concurrent dispatcher.
518 //
519 // We satisfy these constraints by implementing a bootstrap phase during which
520 // allocation actions generated by MachOPlatform are appended to a list of
521 // deferred allocation actions, rather than to the graphs themselves. At the
522 // end of the bootstrap process the deferred actions are attached to a final
523 // "complete-bootstrap" graph that causes them to be run.
524 //
525 // The bootstrap steps are as follows:
526 //
527 // 1. Request the graph containing the mach header. This graph is guaranteed
528 // not to have any metadata so the fact that the registration functions
529 // are not available yet is not a problem.
530 //
531 // 2. Look up the registration functions and discard the results. This will
532 // trigger linking of the graph containing these functions, and
533 // consequently any graphs that it depends on. We do not use the lookup
534 // result to find the addresses of the functions requested (as described
535 // above the lookup will return too late for that), instead we capture the
536 // addresses in a post-allocation pass injected by the platform runtime
537 // during bootstrap only.
538 //
539 // 3. During bootstrap the MachOPlatformPlugin keeps a count of the number of
540 // graphs being linked (potentially concurrently), and we block until all
541 // of these graphs have completed linking. This is to avoid a race on the
542 // deferred-actions vector: the lookup for the runtime registration
543 // functions may return while some functions (those that are being
544 // incidentally linked in, but aren't reachable via the runtime functions)
545 // are still being linked, and we need to capture any allocation actions
546 // for this incidental code before we proceed.
547 //
548 // 4. Once all active links are complete we transfer the deferred actions to
549 // a newly added CompleteBootstrap graph and then request a symbol from
550 // the CompleteBootstrap graph to trigger materialization. This will cause
551 // all deferred actions to be run, and once this lookup returns we can
552 // proceed.
553 //
554 // 5. Finally, we associate runtime support methods in MachOPlatform with
555 // the corresponding jit-dispatch tag variables in the ORC runtime to make
556 // the support methods callable. The bootstrap is now complete.
557
558 // Step (1) Add header materialization unit and request.
559 if ((Err = PlatformJD.define(
560 this->BuildMachOHeaderMU(*this, std::move(PlatformJDOpts)))))
561 return;
562 if ((Err = ES.lookup(&PlatformJD, MachOHeaderStartSymbol).takeError()))
563 return;
564
565 // Step (2) Request runtime registration functions to trigger
566 // materialization..
567 if ((Err = ES.lookup(makeJITDylibSearchOrder(&PlatformJD),
568 SymbolLookupSet(
569 {PlatformBootstrap.Name, PlatformShutdown.Name,
570 RegisterJITDylib.Name, DeregisterJITDylib.Name,
571 RegisterObjectSymbolTable.Name,
572 DeregisterObjectSymbolTable.Name,
573 RegisterObjectPlatformSections.Name,
574 DeregisterObjectPlatformSections.Name,
575 CreatePThreadKey.Name}))
576 .takeError()))
577 return;
578
579 // Step (3) Wait for any incidental linker work to complete.
580 {
581 std::unique_lock<std::mutex> Lock(PlatformMutex);
582 BI.CV.wait(Lock, [&]() { return BI.ActiveGraphs == 0; });
583 Bootstrap = nullptr;
584 }
585
586 // Step (4) Add complete-bootstrap materialization unit and request.
587 auto BootstrapCompleteSymbol = ES.intern("__orc_rt_macho_complete_bootstrap");
588 if ((Err = PlatformJD.define(
589 std::make_unique<MachOPlatformCompleteBootstrapMaterializationUnit>(
590 *this, PlatformJD.getName(), BootstrapCompleteSymbol,
591 std::move(BI.SymTab), std::move(BI.DeferredAAs),
592 BI.MachOHeaderAddr, PlatformBootstrap.Addr,
593 PlatformShutdown.Addr, RegisterJITDylib.Addr,
594 DeregisterJITDylib.Addr, RegisterObjectSymbolTable.Addr,
595 DeregisterObjectSymbolTable.Addr))))
596 return;
597 if ((Err = ES.lookup(makeJITDylibSearchOrder(
599 std::move(BootstrapCompleteSymbol))
600 .takeError()))
601 return;
602
603 // (5) Associate runtime support functions.
604 // TODO: Consider moving this above (4) to make runtime support functions
605 // available to the bootstrap completion graph. We'd just need to be
606 // sure that the runtime support functions are fully usable before any
607 // bootstrap completion actions use them (e.g. the ORC runtime
608 // macho_platform object would have to have been created and
609 // initialized).
610 if ((Err = associateRuntimeSupportFunctions()))
611 return;
612}
613
614Error MachOPlatform::associateRuntimeSupportFunctions() {
616
617 using PushInitializersSPSSig =
618 SPSExpected<SPSMachOJITDylibDepInfoMap>(SPSExecutorAddr);
619 WFs[ES.intern("___orc_rt_macho_push_initializers_tag")] =
620 ES.wrapAsyncWithSPS<PushInitializersSPSSig>(
621 this, &MachOPlatform::rt_pushInitializers);
622
623 using PushSymbolsSPSSig =
624 SPSError(SPSExecutorAddr, SPSSequence<SPSTuple<SPSString, bool>>);
625 WFs[ES.intern("___orc_rt_macho_push_symbols_tag")] =
626 ES.wrapAsyncWithSPS<PushSymbolsSPSSig>(this,
627 &MachOPlatform::rt_pushSymbols);
628
629 return ES.registerJITDispatchHandlers(PlatformJD, std::move(WFs));
630}
631
632void MachOPlatform::pushInitializersLoop(
633 PushInitializersSendResultFn SendResult, JITDylibSP JD) {
634 DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols;
635 DenseMap<JITDylib *, SmallVector<JITDylib *>> JDDepMap;
636 SmallVector<JITDylib *, 16> Worklist({JD.get()});
637
638 ES.runSessionLocked([&]() {
639 while (!Worklist.empty()) {
640 // FIXME: Check for defunct dylibs.
641
642 auto DepJD = Worklist.back();
643 Worklist.pop_back();
644
645 // If we've already visited this JITDylib on this iteration then continue.
646 auto [It, Inserted] = JDDepMap.try_emplace(DepJD);
647 if (!Inserted)
648 continue;
649
650 // Add dep info.
651 auto &DM = It->second;
652 DepJD->withLinkOrderDo([&](const JITDylibSearchOrder &O) {
653 for (auto &KV : O) {
654 if (KV.first == DepJD)
655 continue;
656 DM.push_back(KV.first);
657 Worklist.push_back(KV.first);
658 }
659 });
660
661 // Add any registered init symbols.
662 auto RISItr = RegisteredInitSymbols.find(DepJD);
663 if (RISItr != RegisteredInitSymbols.end()) {
664 NewInitSymbols[DepJD] = std::move(RISItr->second);
665 RegisteredInitSymbols.erase(RISItr);
666 }
667 }
668 });
669
670 // If there are no further init symbols to look up then send the link order
671 // (as a list of header addresses) to the caller.
672 if (NewInitSymbols.empty()) {
673
674 // To make the list intelligible to the runtime we need to convert all
675 // JITDylib pointers to their header addresses. Only include JITDylibs
676 // that appear in the JITDylibToHeaderAddr map (i.e. those that have been
677 // through setupJITDylib) -- bare JITDylibs aren't managed by the platform.
678 DenseMap<JITDylib *, ExecutorAddr> HeaderAddrs;
679 HeaderAddrs.reserve(JDDepMap.size());
680 {
681 std::lock_guard<std::mutex> Lock(PlatformMutex);
682 for (auto &KV : JDDepMap) {
683 auto I = JITDylibToHeaderAddr.find(KV.first);
684 if (I != JITDylibToHeaderAddr.end())
685 HeaderAddrs[KV.first] = I->second;
686 }
687 }
688
689 // Build the dep info map to return.
691 DIM.reserve(JDDepMap.size());
692 for (auto &KV : JDDepMap) {
693 auto HI = HeaderAddrs.find(KV.first);
694 // Skip unmanaged JITDylibs.
695 if (HI == HeaderAddrs.end())
696 continue;
697 auto H = HI->second;
698 MachOJITDylibDepInfo DepInfo;
699 for (auto &Dep : KV.second) {
700 auto HJ = HeaderAddrs.find(Dep);
701 if (HJ != HeaderAddrs.end())
702 DepInfo.DepHeaders.push_back(HJ->second);
703 }
704 DIM.push_back(std::make_pair(H, std::move(DepInfo)));
705 }
706 SendResult(DIM);
707 return;
708 }
709
710 // Otherwise issue a lookup and re-run this phase when it completes.
712 [this, SendResult = std::move(SendResult), JD](Error Err) mutable {
713 if (Err)
714 SendResult(std::move(Err));
715 else
716 pushInitializersLoop(std::move(SendResult), JD);
717 },
718 ES, std::move(NewInitSymbols));
719}
720
721void MachOPlatform::rt_pushInitializers(PushInitializersSendResultFn SendResult,
722 ExecutorAddr JDHeaderAddr) {
723 JITDylibSP JD;
724 {
725 std::lock_guard<std::mutex> Lock(PlatformMutex);
726 auto I = HeaderAddrToJITDylib.find(JDHeaderAddr);
727 if (I != HeaderAddrToJITDylib.end())
728 JD = I->second;
729 }
730
731 LLVM_DEBUG({
732 dbgs() << "MachOPlatform::rt_pushInitializers(" << JDHeaderAddr << ") ";
733 if (JD)
734 dbgs() << "pushing initializers for " << JD->getName() << "\n";
735 else
736 dbgs() << "No JITDylib for header address.\n";
737 });
738
739 if (!JD) {
740 SendResult(make_error<StringError>("No JITDylib with header addr " +
741 formatv("{0:x}", JDHeaderAddr),
743 return;
744 }
745
746 pushInitializersLoop(std::move(SendResult), JD);
747}
748
749void MachOPlatform::rt_pushSymbols(
750 PushSymbolsInSendResultFn SendResult, ExecutorAddr Handle,
751 const std::vector<std::pair<StringRef, bool>> &SymbolNames) {
752
753 JITDylib *JD = nullptr;
754
755 {
756 std::lock_guard<std::mutex> Lock(PlatformMutex);
757 auto I = HeaderAddrToJITDylib.find(Handle);
758 if (I != HeaderAddrToJITDylib.end())
759 JD = I->second;
760 }
761 LLVM_DEBUG({
762 dbgs() << "MachOPlatform::rt_pushSymbols(";
763 if (JD)
764 dbgs() << "\"" << JD->getName() << "\", [ ";
765 else
766 dbgs() << "<invalid handle " << Handle << ">, [ ";
767 for (auto &Name : SymbolNames)
768 dbgs() << "\"" << Name.first << "\" ";
769 dbgs() << "])\n";
770 });
771
772 if (!JD) {
773 SendResult(make_error<StringError>("No JITDylib associated with handle " +
774 formatv("{0:x}", Handle),
776 return;
777 }
778
779 SymbolLookupSet LS;
780 for (auto &[Name, Required] : SymbolNames)
781 LS.add(ES.intern(Name), Required
784
785 ES.lookup(
787 std::move(LS), SymbolState::Ready,
788 [SendResult = std::move(SendResult)](Expected<SymbolMap> Result) mutable {
789 SendResult(Result.takeError());
790 },
792}
793
794Expected<uint64_t> MachOPlatform::createPThreadKey() {
795 if (!CreatePThreadKey.Addr)
797 "Attempting to create pthread key in target, but runtime support has "
798 "not been loaded yet",
800
801 Expected<uint64_t> Result(0);
802 if (auto Err = ES.callSPSWrapper<SPSExpected<uint64_t>(void)>(
803 CreatePThreadKey.Addr, Result))
804 return std::move(Err);
805 return Result;
806}
807
808void MachOPlatform::MachOPlatformPlugin::modifyPassConfig(
809 MaterializationResponsibility &MR, jitlink::LinkGraph &LG,
810 jitlink::PassConfiguration &Config) {
811
812 using namespace jitlink;
813
814 bool InBootstrapPhase = false;
815
816 ExecutorAddr HeaderAddr;
817 {
818 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
819 if (LLVM_UNLIKELY(&MR.getTargetJITDylib() == &MP.PlatformJD)) {
820 if (MP.Bootstrap) {
821 InBootstrapPhase = true;
822 ++MP.Bootstrap->ActiveGraphs;
823 }
824 }
825
826 // Get the dso-base address if available.
827 auto I = MP.JITDylibToHeaderAddr.find(&MR.getTargetJITDylib());
828 if (I != MP.JITDylibToHeaderAddr.end())
829 HeaderAddr = I->second;
830 }
831
832 // If we're forcing eh-frame use then discard the compact-unwind section
833 // immediately to prevent FDEs from being stripped.
834 if (MP.ForceEHFrames)
836 LG.removeSection(*CUSec);
837
838 // Point the libunwind dso-base absolute symbol at the header for the
839 // JITDylib. This will prevent us from synthesizing a new header for
840 // every object.
841 if (HeaderAddr)
842 LG.addAbsoluteSymbol("__jitlink$libunwind_dso_base", HeaderAddr, 0,
843 Linkage::Strong, Scope::Local, true);
844
845 // If we're in the bootstrap phase then increment the active graphs.
846 if (LLVM_UNLIKELY(InBootstrapPhase))
847 Config.PostAllocationPasses.push_back([this](LinkGraph &G) {
848 return bootstrapPipelineRecordRuntimeFunctions(G);
849 });
850
851 // --- Handle Initializers ---
852 if (auto InitSymbol = MR.getInitializerSymbol()) {
853
854 // If the initializer symbol is the MachOHeader start symbol then just
855 // register it and then bail out -- the header materialization unit
856 // definitely doesn't need any other passes.
857 if (InitSymbol == MP.MachOHeaderStartSymbol && !InBootstrapPhase) {
858 Config.PostAllocationPasses.push_back([this, &MR](LinkGraph &G) {
859 return associateJITDylibHeaderSymbol(G, MR);
860 });
861 return;
862 }
863
864 // If the object contains an init symbol other than the header start symbol
865 // then add passes to preserve, process and register the init
866 // sections/symbols.
867 Config.PrePrunePasses.push_back([this, &MR](LinkGraph &G) {
868 if (auto Err = preserveImportantSections(G, MR))
869 return Err;
870 return processObjCImageInfo(G, MR);
871 });
872 Config.PostPrunePasses.push_back(
873 [this](LinkGraph &G) { return createObjCRuntimeObject(G); });
874 Config.PostAllocationPasses.push_back(
875 [this, &MR](LinkGraph &G) { return populateObjCRuntimeObject(G, MR); });
876 }
877
878 // Insert TLV lowering at the start of the PostPrunePasses, since we want
879 // it to run before GOT/PLT lowering.
880 Config.PostPrunePasses.insert(
881 Config.PostPrunePasses.begin(),
882 [this, &JD = MR.getTargetJITDylib()](LinkGraph &G) {
883 return fixTLVSectionsAndEdges(G, JD);
884 });
885
886 // Add symbol table prepare and register passes: These will add strings for
887 // all symbols to the c-strings section, and build a symbol table registration
888 // call.
889 auto JITSymTabInfo = std::make_shared<JITSymTabVector>();
890 Config.PostPrunePasses.push_back([this, JITSymTabInfo](LinkGraph &G) {
891 return prepareSymbolTableRegistration(G, *JITSymTabInfo);
892 });
893 Config.PostFixupPasses.push_back([this, &MR, JITSymTabInfo,
894 InBootstrapPhase](LinkGraph &G) {
895 return addSymbolTableRegistration(G, MR, *JITSymTabInfo, InBootstrapPhase);
896 });
897
898 // Add a pass to register the final addresses of any special sections in the
899 // object with the runtime.
900 Config.PostAllocationPasses.push_back([this, &JD = MR.getTargetJITDylib(),
901 HeaderAddr,
902 InBootstrapPhase](LinkGraph &G) {
903 return registerObjectPlatformSections(G, JD, HeaderAddr, InBootstrapPhase);
904 });
905
906 // If we're in the bootstrap phase then steal allocation actions and then
907 // decrement the active graphs.
908 if (InBootstrapPhase)
909 Config.PostFixupPasses.push_back(
910 [this](LinkGraph &G) { return bootstrapPipelineEnd(G); });
911}
912
913Error MachOPlatform::MachOPlatformPlugin::
914 bootstrapPipelineRecordRuntimeFunctions(jitlink::LinkGraph &G) {
915 // Record bootstrap function names.
916 std::pair<StringRef, ExecutorAddr *> RuntimeSymbols[] = {
917 {*MP.MachOHeaderStartSymbol, &MP.Bootstrap->MachOHeaderAddr},
918 {*MP.PlatformBootstrap.Name, &MP.PlatformBootstrap.Addr},
919 {*MP.PlatformShutdown.Name, &MP.PlatformShutdown.Addr},
920 {*MP.RegisterJITDylib.Name, &MP.RegisterJITDylib.Addr},
921 {*MP.DeregisterJITDylib.Name, &MP.DeregisterJITDylib.Addr},
922 {*MP.RegisterObjectSymbolTable.Name, &MP.RegisterObjectSymbolTable.Addr},
923 {*MP.DeregisterObjectSymbolTable.Name,
924 &MP.DeregisterObjectSymbolTable.Addr},
925 {*MP.RegisterObjectPlatformSections.Name,
926 &MP.RegisterObjectPlatformSections.Addr},
927 {*MP.DeregisterObjectPlatformSections.Name,
928 &MP.DeregisterObjectPlatformSections.Addr},
929 {*MP.CreatePThreadKey.Name, &MP.CreatePThreadKey.Addr},
930 {*MP.RegisterObjCRuntimeObject.Name, &MP.RegisterObjCRuntimeObject.Addr},
931 {*MP.DeregisterObjCRuntimeObject.Name,
932 &MP.DeregisterObjCRuntimeObject.Addr}};
933
934 bool RegisterMachOHeader = false;
935
936 for (auto *Sym : G.defined_symbols()) {
937 for (auto &RTSym : RuntimeSymbols) {
938 if (Sym->hasName() && *Sym->getName() == RTSym.first) {
939 if (*RTSym.second)
941 "Duplicate " + RTSym.first +
942 " detected during MachOPlatform bootstrap",
944
945 if (Sym->getName() == MP.MachOHeaderStartSymbol)
946 RegisterMachOHeader = true;
947
948 *RTSym.second = Sym->getAddress();
949 }
950 }
951 }
952
953 if (RegisterMachOHeader) {
954 // If this graph defines the macho header symbol then create the internal
955 // mapping between it and PlatformJD.
956 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
957 MP.JITDylibToHeaderAddr[&MP.PlatformJD] = MP.Bootstrap->MachOHeaderAddr;
958 MP.HeaderAddrToJITDylib[MP.Bootstrap->MachOHeaderAddr] = &MP.PlatformJD;
959 }
960
961 return Error::success();
962}
963
964Error MachOPlatform::MachOPlatformPlugin::bootstrapPipelineEnd(
965 jitlink::LinkGraph &G) {
966 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
967
968 --MP.Bootstrap->ActiveGraphs;
969 // Notify Bootstrap->CV while holding the mutex because the mutex is
970 // also keeping Bootstrap->CV alive.
971 if (MP.Bootstrap->ActiveGraphs == 0)
972 MP.Bootstrap->CV.notify_all();
973 return Error::success();
974}
975
976Error MachOPlatform::MachOPlatformPlugin::associateJITDylibHeaderSymbol(
977 jitlink::LinkGraph &G, MaterializationResponsibility &MR) {
978 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
979 return Sym->getName() == MP.MachOHeaderStartSymbol;
980 });
981 assert(I != G.defined_symbols().end() && "Missing MachO header start symbol");
982
983 auto &JD = MR.getTargetJITDylib();
984 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
985 auto HeaderAddr = (*I)->getAddress();
986 MP.JITDylibToHeaderAddr[&JD] = HeaderAddr;
987 MP.HeaderAddrToJITDylib[HeaderAddr] = &JD;
988 // We can unconditionally add these actions to the Graph because this pass
989 // isn't used during bootstrap.
990 G.allocActions().push_back(
991 {cantFail(
992 WrapperFunctionCall::Create<SPSArgList<SPSString, SPSExecutorAddr>>(
993 MP.RegisterJITDylib.Addr, JD.getName(), HeaderAddr)),
994 cantFail(WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>(
995 MP.DeregisterJITDylib.Addr, HeaderAddr))});
996 return Error::success();
997}
998
999Error MachOPlatform::MachOPlatformPlugin::preserveImportantSections(
1000 jitlink::LinkGraph &G, MaterializationResponsibility &MR) {
1001 // __objc_imageinfo is "important": we want to preserve it and record its
1002 // address in the first graph that it appears in, then verify and discard it
1003 // in all subsequent graphs. In this pass we preserve unconditionally -- we'll
1004 // manually throw it away in the processObjCImageInfo pass.
1005 if (auto *ObjCImageInfoSec =
1006 G.findSectionByName(MachOObjCImageInfoSectionName)) {
1007 if (ObjCImageInfoSec->blocks_size() != 1)
1009 "In " + G.getName() +
1010 "__DATA,__objc_imageinfo contains multiple blocks",
1012 G.addAnonymousSymbol(**ObjCImageInfoSec->blocks().begin(), 0, 0, false,
1013 true);
1014
1015 for (auto *B : ObjCImageInfoSec->blocks())
1016 if (!B->edges_empty())
1017 return make_error<StringError>("In " + G.getName() + ", " +
1019 " contains references to symbols",
1021 }
1022
1023 // Init sections are important: We need to preserve them and so that their
1024 // addresses can be captured and reported to the ORC runtime in
1025 // registerObjectPlatformSections.
1026 if (const auto &InitSymName = MR.getInitializerSymbol()) {
1027
1028 jitlink::Symbol *InitSym = nullptr;
1029 for (auto &InitSectionName : MachOInitSectionNames) {
1030 // Skip ObjCImageInfo -- this shouldn't have any dependencies, and we may
1031 // remove it later.
1032 if (InitSectionName == MachOObjCImageInfoSectionName)
1033 continue;
1034
1035 // Skip non-init sections.
1036 auto *InitSection = G.findSectionByName(InitSectionName);
1037 if (!InitSection || InitSection->empty())
1038 continue;
1039
1040 // Create the init symbol if it has not been created already and attach it
1041 // to the first block.
1042 if (!InitSym) {
1043 auto &B = **InitSection->blocks().begin();
1044 InitSym = &G.addDefinedSymbol(
1045 B, 0, *InitSymName, B.getSize(), jitlink::Linkage::Strong,
1046 jitlink::Scope::SideEffectsOnly, false, true);
1047 }
1048
1049 // Add keep-alive edges to anonymous symbols in all other init blocks.
1050 for (auto *B : InitSection->blocks()) {
1051 if (B == &InitSym->getBlock())
1052 continue;
1053
1054 auto &S = G.addAnonymousSymbol(*B, 0, B->getSize(), false, true);
1055 InitSym->getBlock().addEdge(jitlink::Edge::KeepAlive, 0, S, 0);
1056 }
1057 }
1058 }
1059
1060 return Error::success();
1061}
1062
1063Error MachOPlatform::MachOPlatformPlugin::processObjCImageInfo(
1064 jitlink::LinkGraph &G, MaterializationResponsibility &MR) {
1065
1066 // If there's an ObjC imagine info then either
1067 // (1) It's the first __objc_imageinfo we've seen in this JITDylib. In
1068 // this case we name and record it.
1069 // OR
1070 // (2) We already have a recorded __objc_imageinfo for this JITDylib,
1071 // in which case we just verify it.
1072 auto *ObjCImageInfo = G.findSectionByName(MachOObjCImageInfoSectionName);
1073 if (!ObjCImageInfo)
1074 return Error::success();
1075
1076 auto ObjCImageInfoBlocks = ObjCImageInfo->blocks();
1077
1078 // Check that the section is not empty if present.
1079 if (ObjCImageInfoBlocks.empty())
1081 " section in " + G.getName(),
1083
1084 // Check that there's only one block in the section.
1085 if (std::next(ObjCImageInfoBlocks.begin()) != ObjCImageInfoBlocks.end())
1086 return make_error<StringError>("Multiple blocks in " +
1088 " section in " + G.getName(),
1090
1091 // Check that the __objc_imageinfo section is unreferenced.
1092 // FIXME: We could optimize this check if Symbols had a ref-count.
1093 for (auto &Sec : G.sections()) {
1094 if (&Sec != ObjCImageInfo)
1095 for (auto *B : Sec.blocks())
1096 for (auto &E : B->edges())
1097 if (E.getTarget().isDefined() &&
1098 &E.getTarget().getSection() == ObjCImageInfo)
1100 " is referenced within file " +
1101 G.getName(),
1103 }
1104
1105 auto &ObjCImageInfoBlock = **ObjCImageInfoBlocks.begin();
1106 auto *ObjCImageInfoData = ObjCImageInfoBlock.getContent().data();
1107 auto Version = support::endian::read32(ObjCImageInfoData, G.getEndianness());
1108 auto Flags =
1109 support::endian::read32(ObjCImageInfoData + 4, G.getEndianness());
1110
1111 // Lock the mutex while we verify / update the ObjCImageInfos map.
1112 std::lock_guard<std::mutex> Lock(PluginMutex);
1113
1114 auto ObjCImageInfoItr = ObjCImageInfos.find(&MR.getTargetJITDylib());
1115 if (ObjCImageInfoItr != ObjCImageInfos.end()) {
1116 // We've already registered an __objc_imageinfo section. Verify the
1117 // content of this new section matches, then delete it.
1118 if (ObjCImageInfoItr->second.Version != Version)
1120 "ObjC version in " + G.getName() +
1121 " does not match first registered version",
1123 if (ObjCImageInfoItr->second.Flags != Flags)
1124 if (Error E = mergeImageInfoFlags(G, MR, ObjCImageInfoItr->second, Flags))
1125 return E;
1126
1127 // __objc_imageinfo is valid. Delete the block.
1128 while (ObjCImageInfo->symbols_size() != 0)
1129 G.removeDefinedSymbol(**ObjCImageInfo->symbols().begin());
1130 G.removeBlock(ObjCImageInfoBlock);
1131 } else {
1132 LLVM_DEBUG({
1133 dbgs() << "MachOPlatform: Registered __objc_imageinfo for "
1134 << MR.getTargetJITDylib().getName() << " in " << G.getName()
1135 << "; flags = " << formatv("{0:x4}", Flags) << "\n";
1136 });
1137 // We haven't registered an __objc_imageinfo section yet. Register and
1138 // move on. The section should already be marked no-dead-strip.
1139 G.addDefinedSymbol(ObjCImageInfoBlock, 0, ObjCImageInfoSymbolName,
1140 ObjCImageInfoBlock.getSize(), jitlink::Linkage::Strong,
1141 jitlink::Scope::Hidden, false, true);
1142 if (auto Err = MR.defineMaterializing(
1143 {{MR.getExecutionSession().intern(ObjCImageInfoSymbolName),
1144 JITSymbolFlags()}}))
1145 return Err;
1146 ObjCImageInfos[&MR.getTargetJITDylib()] = {Version, Flags, false};
1147 }
1148
1149 return Error::success();
1150}
1151
1152Error MachOPlatform::MachOPlatformPlugin::mergeImageInfoFlags(
1153 jitlink::LinkGraph &G, MaterializationResponsibility &MR,
1154 ObjCImageInfo &Info, uint32_t NewFlags) {
1155 if (Info.Flags == NewFlags)
1156 return Error::success();
1157
1158 ObjCImageInfoFlags Old(Info.Flags);
1159 ObjCImageInfoFlags New(NewFlags);
1160
1161 // Check for incompatible flags.
1162 if (Old.SwiftABIVersion && New.SwiftABIVersion &&
1163 Old.SwiftABIVersion != New.SwiftABIVersion)
1164 return make_error<StringError>("Swift ABI version in " + G.getName() +
1165 " does not match first registered flags",
1167
1168 // HasCategoryClassProperties and HasSignedObjCClassROs can be disabled before
1169 // they are registered, if necessary, but once they are in use must be
1170 // supported by subsequent objects.
1171 if (Info.Finalized && Old.HasCategoryClassProperties &&
1172 !New.HasCategoryClassProperties)
1173 return make_error<StringError>("ObjC category class property support in " +
1174 G.getName() +
1175 " does not match first registered flags",
1177 if (Info.Finalized && Old.HasSignedObjCClassROs && !New.HasSignedObjCClassROs)
1178 return make_error<StringError>("ObjC class_ro_t pointer signing in " +
1179 G.getName() +
1180 " does not match first registered flags",
1182
1183 // If we cannot change the flags, ignore any remaining differences. Adding
1184 // Swift or changing its version are unlikely to cause problems in practice.
1185 if (Info.Finalized)
1186 return Error::success();
1187
1188 // Use the minimum Swift version.
1189 if (Old.SwiftVersion && New.SwiftVersion)
1190 New.SwiftVersion = std::min(Old.SwiftVersion, New.SwiftVersion);
1191 else if (Old.SwiftVersion)
1192 New.SwiftVersion = Old.SwiftVersion;
1193 // Add a Swift ABI version if it was pure objc before.
1194 if (!New.SwiftABIVersion)
1195 New.SwiftABIVersion = Old.SwiftABIVersion;
1196 // Disable class properties if any object does not support it.
1197 if (Old.HasCategoryClassProperties != New.HasCategoryClassProperties)
1198 New.HasCategoryClassProperties = false;
1199 // Disable signed class ro data if any object does not support it.
1200 if (Old.HasSignedObjCClassROs != New.HasSignedObjCClassROs)
1201 New.HasSignedObjCClassROs = false;
1202
1203 LLVM_DEBUG({
1204 dbgs() << "MachOPlatform: Merging __objc_imageinfo flags for "
1205 << MR.getTargetJITDylib().getName() << " (was "
1206 << formatv("{0:x4}", Old.rawFlags()) << ")"
1207 << " with " << G.getName() << " (" << formatv("{0:x4}", NewFlags)
1208 << ")"
1209 << " -> " << formatv("{0:x4}", New.rawFlags()) << "\n";
1210 });
1211
1212 Info.Flags = New.rawFlags();
1213 return Error::success();
1214}
1215
1216Error MachOPlatform::MachOPlatformPlugin::fixTLVSectionsAndEdges(
1217 jitlink::LinkGraph &G, JITDylib &JD) {
1218 auto TLVBootStrapSymbolName = G.intern("__tlv_bootstrap");
1219 // Rename external references to __tlv_bootstrap to ___orc_rt_tlv_get_addr.
1220 for (auto *Sym : G.external_symbols())
1221 if (Sym->getName() == TLVBootStrapSymbolName) {
1222 auto TLSGetADDR =
1223 MP.getExecutionSession().intern("___orc_rt_macho_tlv_get_addr");
1224 Sym->setName(std::move(TLSGetADDR));
1225 break;
1226 }
1227
1228 // Store key in __thread_vars struct fields.
1229 if (auto *ThreadDataSec = G.findSectionByName(MachOThreadVarsSectionName)) {
1230 std::optional<uint64_t> Key;
1231 {
1232 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1233 auto I = MP.JITDylibToPThreadKey.find(&JD);
1234 if (I != MP.JITDylibToPThreadKey.end())
1235 Key = I->second;
1236 }
1237
1238 if (!Key) {
1239 if (auto KeyOrErr = MP.createPThreadKey())
1240 Key = *KeyOrErr;
1241 else
1242 return KeyOrErr.takeError();
1243 }
1244
1245 uint64_t PlatformKeyBits =
1246 support::endian::byte_swap(*Key, G.getEndianness());
1247
1248 for (auto *B : ThreadDataSec->blocks()) {
1249 if (B->getSize() != 3 * G.getPointerSize())
1250 return make_error<StringError>("__thread_vars block at " +
1251 formatv("{0:x}", B->getAddress()) +
1252 " has unexpected size",
1254
1255 auto NewBlockContent = G.allocateBuffer(B->getSize());
1256 llvm::copy(B->getContent(), NewBlockContent.data());
1257 memcpy(NewBlockContent.data() + G.getPointerSize(), &PlatformKeyBits,
1258 G.getPointerSize());
1259 B->setContent(NewBlockContent);
1260 }
1261 }
1262
1263 // Transform any TLV edges into GOT edges.
1264 for (auto *B : G.blocks())
1265 for (auto &E : B->edges())
1266 if (E.getKind() ==
1268 E.setKind(jitlink::x86_64::
1269 RequestGOTAndTransformToPCRel32GOTLoadREXRelaxable);
1270
1271 return Error::success();
1272}
1273
1274std::optional<MachOPlatform::MachOPlatformPlugin::UnwindSections>
1275MachOPlatform::MachOPlatformPlugin::findUnwindSectionInfo(
1276 jitlink::LinkGraph &G) {
1277 using namespace jitlink;
1278
1279 UnwindSections US;
1280
1281 // ScanSection records a section range and adds any executable blocks that
1282 // that section points to to the CodeBlocks vector.
1283 SmallVector<Block *> CodeBlocks;
1284 auto ScanUnwindInfoSection = [&](Section &Sec, ExecutorAddrRange &SecRange,
1285 auto AddCodeBlocks) {
1286 if (Sec.blocks().empty())
1287 return;
1288 SecRange = (*Sec.blocks().begin())->getRange();
1289 for (auto *B : Sec.blocks()) {
1290 auto R = B->getRange();
1291 SecRange.Start = std::min(SecRange.Start, R.Start);
1292 SecRange.End = std::max(SecRange.End, R.End);
1293 AddCodeBlocks(*B);
1294 }
1295 };
1296
1297 if (Section *EHFrameSec = G.findSectionByName(MachOEHFrameSectionName)) {
1298 ScanUnwindInfoSection(*EHFrameSec, US.DwarfSection, [&](Block &B) {
1299 if (auto *Fn = jitlink::EHFrameCFIBlockInspector::FromEdgeScan(B)
1300 .getPCBeginEdge())
1301 if (Fn->getTarget().isDefined())
1302 CodeBlocks.push_back(&Fn->getTarget().getBlock());
1303 });
1304 }
1305
1306 if (Section *CUInfoSec = G.findSectionByName(MachOUnwindInfoSectionName)) {
1307 ScanUnwindInfoSection(
1308 *CUInfoSec, US.CompactUnwindSection, [&](Block &B) {
1309 for (auto &E : B.edges()) {
1310 assert(E.getTarget().isDefined() &&
1311 "unwind-info record edge has external target");
1312 assert(E.getKind() == Edge::KeepAlive &&
1313 "unwind-info record has unexpected edge kind");
1314 CodeBlocks.push_back(&E.getTarget().getBlock());
1315 }
1316 });
1317 }
1318
1319 // If we didn't find any pointed-to code-blocks then there's no need to
1320 // register any info.
1321 if (CodeBlocks.empty())
1322 return std::nullopt;
1323
1324 // We have info to register. Sort the code blocks into address order and
1325 // build a list of contiguous address ranges covering them all.
1326 llvm::sort(CodeBlocks, [](const Block *LHS, const Block *RHS) {
1327 return LHS->getAddress() < RHS->getAddress();
1328 });
1329 for (auto *B : CodeBlocks) {
1330 if (US.CodeRanges.empty() || US.CodeRanges.back().End != B->getAddress())
1331 US.CodeRanges.push_back(B->getRange());
1332 else
1333 US.CodeRanges.back().End = B->getRange().End;
1334 }
1335
1336 LLVM_DEBUG({
1337 dbgs() << "MachOPlatform identified unwind info in " << G.getName() << ":\n"
1338 << " DWARF: ";
1339 if (US.DwarfSection.Start)
1340 dbgs() << US.DwarfSection << "\n";
1341 else
1342 dbgs() << "none\n";
1343 dbgs() << " Compact-unwind: ";
1344 if (US.CompactUnwindSection.Start)
1345 dbgs() << US.CompactUnwindSection << "\n";
1346 else
1347 dbgs() << "none\n"
1348 << "for code ranges:\n";
1349 for (auto &CR : US.CodeRanges)
1350 dbgs() << " " << CR << "\n";
1351 if (US.CodeRanges.size() >= G.sections_size())
1352 dbgs() << "WARNING: High number of discontiguous code ranges! "
1353 "Padding may be interfering with coalescing.\n";
1354 });
1355
1356 return US;
1357}
1358
1359Error MachOPlatform::MachOPlatformPlugin::registerObjectPlatformSections(
1360 jitlink::LinkGraph &G, JITDylib &JD, ExecutorAddr HeaderAddr,
1361 bool InBootstrapPhase) {
1362
1363 // Get a pointer to the thread data section if there is one. It will be used
1364 // below.
1365 jitlink::Section *ThreadDataSection =
1366 G.findSectionByName(MachOThreadDataSectionName);
1367
1368 // Handle thread BSS section if there is one.
1369 if (auto *ThreadBSSSection = G.findSectionByName(MachOThreadBSSSectionName)) {
1370 // If there's already a thread data section in this graph then merge the
1371 // thread BSS section content into it, otherwise just treat the thread
1372 // BSS section as the thread data section.
1373 if (ThreadDataSection)
1374 G.mergeSections(*ThreadDataSection, *ThreadBSSSection);
1375 else
1376 ThreadDataSection = ThreadBSSSection;
1377 }
1378
1380
1381 // Collect data sections to register.
1382 StringRef DataSections[] = {MachODataDataSectionName,
1385 for (auto &SecName : DataSections) {
1386 if (auto *Sec = G.findSectionByName(SecName)) {
1387 jitlink::SectionRange R(*Sec);
1388 if (!R.empty())
1389 MachOPlatformSecs.push_back({SecName, R.getRange()});
1390 }
1391 }
1392
1393 // Having merged thread BSS (if present) and thread data (if present),
1394 // record the resulting section range.
1395 if (ThreadDataSection) {
1396 jitlink::SectionRange R(*ThreadDataSection);
1397 if (!R.empty())
1398 MachOPlatformSecs.push_back({MachOThreadDataSectionName, R.getRange()});
1399 }
1400
1401 // If any platform sections were found then add an allocation action to call
1402 // the registration function.
1403 StringRef PlatformSections[] = {MachOModInitFuncSectionName,
1404 ObjCRuntimeObjectSectionName};
1405
1406 for (auto &SecName : PlatformSections) {
1407 auto *Sec = G.findSectionByName(SecName);
1408 if (!Sec)
1409 continue;
1410 jitlink::SectionRange R(*Sec);
1411 if (R.empty())
1412 continue;
1413
1414 MachOPlatformSecs.push_back({SecName, R.getRange()});
1415 }
1416
1417 std::optional<std::tuple<SmallVector<ExecutorAddrRange>, ExecutorAddrRange,
1418 ExecutorAddrRange>>
1419 UnwindInfo;
1420 if (auto UI = findUnwindSectionInfo(G))
1421 UnwindInfo = std::make_tuple(std::move(UI->CodeRanges), UI->DwarfSection,
1422 UI->CompactUnwindSection);
1423
1424 if (!MachOPlatformSecs.empty() || UnwindInfo) {
1425 // Dump the scraped inits.
1426 LLVM_DEBUG({
1427 dbgs() << "MachOPlatform: Scraped " << G.getName() << " init sections:\n";
1428 for (auto &KV : MachOPlatformSecs)
1429 dbgs() << " " << KV.first << ": " << KV.second << "\n";
1430 });
1431
1432 assert(HeaderAddr && "Null header registered for JD");
1433 using SPSRegisterObjectPlatformSectionsArgs = SPSArgList<
1434 SPSExecutorAddr,
1435 SPSOptional<SPSTuple<SPSSequence<SPSExecutorAddrRange>,
1437 SPSSequence<SPSTuple<SPSString, SPSExecutorAddrRange>>>;
1438
1439 AllocActionCallPair AllocActions = {
1440 cantFail(
1442 MP.RegisterObjectPlatformSections.Addr, HeaderAddr, UnwindInfo,
1443 MachOPlatformSecs)),
1444 cantFail(
1446 MP.DeregisterObjectPlatformSections.Addr, HeaderAddr,
1447 UnwindInfo, MachOPlatformSecs))};
1448
1449 if (LLVM_LIKELY(!InBootstrapPhase))
1450 G.allocActions().push_back(std::move(AllocActions));
1451 else {
1452 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1453 MP.Bootstrap->DeferredAAs.push_back(std::move(AllocActions));
1454 }
1455 }
1456
1457 return Error::success();
1458}
1459
1460Error MachOPlatform::MachOPlatformPlugin::createObjCRuntimeObject(
1461 jitlink::LinkGraph &G) {
1462
1463 bool NeedTextSegment = false;
1464 size_t NumRuntimeSections = 0;
1465
1466 for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsData)
1467 if (G.findSectionByName(ObjCRuntimeSectionName))
1468 ++NumRuntimeSections;
1469
1470 for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsText) {
1471 if (G.findSectionByName(ObjCRuntimeSectionName)) {
1472 ++NumRuntimeSections;
1473 NeedTextSegment = true;
1474 }
1475 }
1476
1477 // Early out for no runtime sections.
1478 if (NumRuntimeSections == 0)
1479 return Error::success();
1480
1481 // If there were any runtime sections then we need to add an __objc_imageinfo
1482 // section.
1483 ++NumRuntimeSections;
1484
1485 size_t MachOSize = sizeof(MachO::mach_header_64) +
1486 (NeedTextSegment + 1) * sizeof(MachO::segment_command_64) +
1487 NumRuntimeSections * sizeof(MachO::section_64);
1488
1489 auto &Sec = G.createSection(ObjCRuntimeObjectSectionName,
1491 G.createMutableContentBlock(Sec, MachOSize, ExecutorAddr(), 16, 0, true);
1492
1493 return Error::success();
1494}
1495
1496Error MachOPlatform::MachOPlatformPlugin::populateObjCRuntimeObject(
1497 jitlink::LinkGraph &G, MaterializationResponsibility &MR) {
1498
1499 auto *ObjCRuntimeObjectSec =
1500 G.findSectionByName(ObjCRuntimeObjectSectionName);
1501
1502 if (!ObjCRuntimeObjectSec)
1503 return Error::success();
1504
1505 switch (G.getTargetTriple().getArch()) {
1506 case Triple::aarch64:
1507 case Triple::x86_64:
1508 // Supported.
1509 break;
1510 default:
1511 return make_error<StringError>("Unrecognized MachO arch in triple " +
1512 G.getTargetTriple().str(),
1514 }
1515
1516 auto &SecBlock = **ObjCRuntimeObjectSec->blocks().begin();
1517
1518 struct SecDesc {
1519 MachO::section_64 Sec;
1520 unique_function<void(size_t RecordOffset)> AddFixups;
1521 };
1522
1523 std::vector<SecDesc> TextSections, DataSections;
1524 auto AddSection = [&](SecDesc &SD, jitlink::Section &GraphSec) {
1525 jitlink::SectionRange SR(GraphSec);
1526 StringRef FQName = GraphSec.getName();
1527 memset(&SD.Sec, 0, sizeof(MachO::section_64));
1528 memcpy(SD.Sec.sectname, FQName.drop_front(7).data(), FQName.size() - 7);
1529 memcpy(SD.Sec.segname, FQName.data(), 6);
1530 SD.Sec.addr = SR.getStart() - SecBlock.getAddress();
1531 SD.Sec.size = SR.getSize();
1532 SD.Sec.flags = MachO::S_REGULAR;
1533 };
1534
1535 // Add the __objc_imageinfo section.
1536 {
1537 DataSections.push_back({});
1538 auto &SD = DataSections.back();
1539 memset(&SD.Sec, 0, sizeof(SD.Sec));
1540 memcpy(SD.Sec.sectname, "__objc_imageinfo", 16);
1541 strcpy(SD.Sec.segname, "__DATA");
1542 SD.Sec.size = 8;
1543 jitlink::Symbol *ObjCImageInfoSym = nullptr;
1544 SD.AddFixups = [&, ObjCImageInfoSym](size_t RecordOffset) mutable {
1545 auto PointerEdge = getPointerEdgeKind(G);
1546
1547 // Look for an existing __objc_imageinfo symbol.
1548 if (!ObjCImageInfoSym) {
1549 auto Name = G.intern(ObjCImageInfoSymbolName);
1550 ObjCImageInfoSym = G.findExternalSymbolByName(Name);
1551 if (!ObjCImageInfoSym)
1552 ObjCImageInfoSym = G.findAbsoluteSymbolByName(Name);
1553 if (!ObjCImageInfoSym) {
1554 ObjCImageInfoSym = G.findDefinedSymbolByName(Name);
1555 if (ObjCImageInfoSym) {
1556 std::optional<uint32_t> Flags;
1557 {
1558 std::lock_guard<std::mutex> Lock(PluginMutex);
1559 auto It = ObjCImageInfos.find(&MR.getTargetJITDylib());
1560 if (It != ObjCImageInfos.end()) {
1561 It->second.Finalized = true;
1562 Flags = It->second.Flags;
1563 }
1564 }
1565
1566 if (Flags) {
1567 // We own the definition of __objc_image_info; write the final
1568 // merged flags value.
1569 auto Content = ObjCImageInfoSym->getBlock().getMutableContent(G);
1570 assert(
1571 Content.size() == 8 &&
1572 "__objc_image_info size should have been verified already");
1573 support::endian::write32(&Content[4], *Flags, G.getEndianness());
1574 }
1575 }
1576 }
1577 if (!ObjCImageInfoSym)
1578 ObjCImageInfoSym = &G.addExternalSymbol(std::move(Name), 8, false);
1579 }
1580
1581 SecBlock.addEdge(PointerEdge,
1582 RecordOffset + ((char *)&SD.Sec.addr - (char *)&SD.Sec),
1583 *ObjCImageInfoSym, -SecBlock.getAddress().getValue());
1584 };
1585 }
1586
1587 for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsData) {
1588 if (auto *GraphSec = G.findSectionByName(ObjCRuntimeSectionName)) {
1589 DataSections.push_back({});
1590 AddSection(DataSections.back(), *GraphSec);
1591 }
1592 }
1593
1594 for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsText) {
1595 if (auto *GraphSec = G.findSectionByName(ObjCRuntimeSectionName)) {
1596 TextSections.push_back({});
1597 AddSection(TextSections.back(), *GraphSec);
1598 }
1599 }
1600
1601 assert(ObjCRuntimeObjectSec->blocks_size() == 1 &&
1602 "Unexpected number of blocks in runtime sections object");
1603
1604 // Build the header struct up-front. This also gives us a chance to check
1605 // that the triple is supported, which we'll assume below.
1606 MachO::mach_header_64 Hdr;
1608 switch (G.getTargetTriple().getArch()) {
1609 case Triple::aarch64:
1612 break;
1613 case Triple::x86_64:
1616 break;
1617 default:
1618 llvm_unreachable("Unsupported architecture");
1619 }
1620
1622 Hdr.ncmds = 1 + !TextSections.empty();
1623 Hdr.sizeofcmds =
1624 Hdr.ncmds * sizeof(MachO::segment_command_64) +
1625 (TextSections.size() + DataSections.size()) * sizeof(MachO::section_64);
1626 Hdr.flags = 0;
1627 Hdr.reserved = 0;
1628
1629 auto SecContent = SecBlock.getAlreadyMutableContent();
1630 char *P = SecContent.data();
1631 auto WriteMachOStruct = [&](auto S) {
1632 if (G.getEndianness() != llvm::endianness::native)
1634 memcpy(P, &S, sizeof(S));
1635 P += sizeof(S);
1636 };
1637
1638 auto WriteSegment = [&](StringRef Name, std::vector<SecDesc> &Secs) {
1639 MachO::segment_command_64 SegLC;
1640 memset(&SegLC, 0, sizeof(SegLC));
1641 memcpy(SegLC.segname, Name.data(), Name.size());
1642 SegLC.cmd = MachO::LC_SEGMENT_64;
1643 SegLC.cmdsize = sizeof(MachO::segment_command_64) +
1644 Secs.size() * sizeof(MachO::section_64);
1645 SegLC.nsects = Secs.size();
1646 WriteMachOStruct(SegLC);
1647 for (auto &SD : Secs) {
1648 if (SD.AddFixups)
1649 SD.AddFixups(P - SecContent.data());
1650 WriteMachOStruct(SD.Sec);
1651 }
1652 };
1653
1654 WriteMachOStruct(Hdr);
1655 if (!TextSections.empty())
1656 WriteSegment("__TEXT", TextSections);
1657 if (!DataSections.empty())
1658 WriteSegment("__DATA", DataSections);
1659
1660 assert(P == SecContent.end() && "Underflow writing ObjC runtime object");
1661 return Error::success();
1662}
1663
1664Error MachOPlatform::MachOPlatformPlugin::prepareSymbolTableRegistration(
1665 jitlink::LinkGraph &G, JITSymTabVector &JITSymTabInfo) {
1666
1667 auto *CStringSec = G.findSectionByName(MachOCStringSectionName);
1668 if (!CStringSec)
1669 CStringSec = &G.createSection(MachOCStringSectionName,
1671
1672 // Make a map of existing strings so that we can re-use them:
1673 DenseMap<StringRef, jitlink::Symbol *> ExistingStrings;
1674 for (auto *Sym : CStringSec->symbols()) {
1675
1676 // The LinkGraph builder should have created single strings blocks, and all
1677 // plugins should have maintained this invariant.
1678 auto Content = Sym->getBlock().getContent();
1679 ExistingStrings.insert(
1680 std::make_pair(StringRef(Content.data(), Content.size()), Sym));
1681 }
1682
1683 // Add all symbol names to the string section, and record the symbols for
1684 // those names.
1685 {
1686 SmallVector<jitlink::Symbol *> SymsToProcess;
1687 llvm::append_range(SymsToProcess, G.defined_symbols());
1688 llvm::append_range(SymsToProcess, G.absolute_symbols());
1689
1690 for (auto *Sym : SymsToProcess) {
1691 if (!Sym->hasName())
1692 continue;
1693
1694 auto I = ExistingStrings.find(*Sym->getName());
1695 if (I == ExistingStrings.end()) {
1696 auto &NameBlock = G.createMutableContentBlock(
1697 *CStringSec, G.allocateCString(*Sym->getName()),
1698 orc::ExecutorAddr(), 1, 0);
1699 auto &SymbolNameSym = G.addAnonymousSymbol(
1700 NameBlock, 0, NameBlock.getSize(), false, true);
1701 JITSymTabInfo.push_back({Sym, &SymbolNameSym});
1702 } else
1703 JITSymTabInfo.push_back({Sym, I->second});
1704 }
1705 }
1706
1707 return Error::success();
1708}
1709
1710Error MachOPlatform::MachOPlatformPlugin::addSymbolTableRegistration(
1711 jitlink::LinkGraph &G, MaterializationResponsibility &MR,
1712 JITSymTabVector &JITSymTabInfo, bool InBootstrapPhase) {
1713
1714 ExecutorAddr HeaderAddr;
1715 {
1716 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1717 auto I = MP.JITDylibToHeaderAddr.find(&MR.getTargetJITDylib());
1718 assert(I != MP.JITDylibToHeaderAddr.end() && "No header registered for JD");
1719 assert(I->second && "Null header registered for JD");
1720 HeaderAddr = I->second;
1721 }
1722
1723 if (LLVM_UNLIKELY(InBootstrapPhase)) {
1724 // If we're in the bootstrap phase then just record these symbols in the
1725 // bootstrap object and then bail out -- registration will be attached to
1726 // the bootstrap graph.
1727 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1728 auto &SymTab = MP.Bootstrap->SymTab;
1729 for (auto &[OriginalSymbol, NameSym] : JITSymTabInfo)
1730 SymTab.push_back({NameSym->getAddress(), OriginalSymbol->getAddress(),
1731 flagsForSymbol(*OriginalSymbol)});
1732 return Error::success();
1733 }
1734
1735 SymbolTableVector SymTab;
1736 for (auto &[OriginalSymbol, NameSym] : JITSymTabInfo)
1737 SymTab.push_back({NameSym->getAddress(), OriginalSymbol->getAddress(),
1738 flagsForSymbol(*OriginalSymbol)});
1739
1740 G.allocActions().push_back(
1742 MP.RegisterObjectSymbolTable.Addr, HeaderAddr, SymTab)),
1744 MP.DeregisterObjectSymbolTable.Addr, HeaderAddr, SymTab))});
1745
1746 return Error::success();
1747}
1748
1749template <typename MachOTraits>
1751 const MachOPlatform::HeaderOptions &Opts,
1753 jitlink::Section &HeaderSection) {
1754 auto HdrInfo =
1756 MachOBuilder<MachOTraits> B(HdrInfo.PageSize);
1757
1758 B.Header.filetype = MachO::MH_DYLIB;
1759 B.Header.cputype = HdrInfo.CPUType;
1760 B.Header.cpusubtype = HdrInfo.CPUSubType;
1761
1762 if (Opts.IDDylib)
1763 B.template addLoadCommand<MachO::LC_ID_DYLIB>(
1764 Opts.IDDylib->Name, Opts.IDDylib->Timestamp,
1765 Opts.IDDylib->CurrentVersion, Opts.IDDylib->CompatibilityVersion);
1766 else
1767 B.template addLoadCommand<MachO::LC_ID_DYLIB>(JD.getName(), 0, 0, 0);
1768
1769 if (Opts.UUID)
1770 B.template addLoadCommand<MachO::LC_UUID>(*Opts.UUID);
1771
1772 for (auto &BV : Opts.BuildVersions)
1773 B.template addLoadCommand<MachO::LC_BUILD_VERSION>(
1774 BV.Platform, BV.MinOS, BV.SDK, static_cast<uint32_t>(0));
1775
1776 if (Opts.TargetTriple)
1777 B.template addLoadCommand<MachO::LC_TARGET_TRIPLE>(*Opts.TargetTriple);
1778
1780 for (auto &LD : Opts.LoadDylibs) {
1781 switch (LD.K) {
1782 case LoadKind::Default:
1783 B.template addLoadCommand<MachO::LC_LOAD_DYLIB>(
1784 LD.D.Name, LD.D.Timestamp, LD.D.CurrentVersion,
1785 LD.D.CompatibilityVersion);
1786 break;
1787 case LoadKind::Weak:
1788 B.template addLoadCommand<MachO::LC_LOAD_WEAK_DYLIB>(
1789 LD.D.Name, LD.D.Timestamp, LD.D.CurrentVersion,
1790 LD.D.CompatibilityVersion);
1791 break;
1792 }
1793 }
1794 for (auto &P : Opts.RPaths)
1795 B.template addLoadCommand<MachO::LC_RPATH>(P);
1796
1797 auto HeaderContent = G.allocateBuffer(B.layout());
1798 B.write(HeaderContent);
1799
1800 return G.createContentBlock(HeaderSection, HeaderContent, ExecutorAddr(), 8,
1801 0);
1802}
1803
1805 SymbolStringPtr HeaderStartSymbol,
1808 createHeaderInterface(MOP, std::move(HeaderStartSymbol))),
1809 MOP(MOP), Opts(std::move(Opts)) {}
1810
1812 std::unique_ptr<MaterializationResponsibility> R) {
1813 auto G = createPlatformGraph(MOP, "<MachOHeaderMU>");
1814 addMachOHeader(R->getTargetJITDylib(), *G, R->getInitializerSymbol());
1815 MOP.getObjectLinkingLayer().emit(std::move(R), std::move(G));
1816}
1817
1819 const SymbolStringPtr &Sym) {}
1820
1821void SimpleMachOHeaderMU::addMachOHeader(
1823 const SymbolStringPtr &InitializerSymbol) {
1824 auto &HeaderSection = G.createSection("__header", MemProt::Read);
1825 auto &HeaderBlock = createHeaderBlock(JD, G, HeaderSection);
1826
1827 // Init symbol is header-start symbol.
1828 G.addDefinedSymbol(HeaderBlock, 0, *InitializerSymbol, HeaderBlock.getSize(),
1830 true);
1831 for (auto &HS : AdditionalHeaderSymbols)
1832 G.addDefinedSymbol(HeaderBlock, HS.Offset, HS.Name, HeaderBlock.getSize(),
1834 true);
1835}
1836
1839 jitlink::Section &HeaderSection) {
1840 switch (MOP.getExecutionSession().getTargetTriple().getArch()) {
1841 case Triple::aarch64:
1842 case Triple::x86_64:
1843 return ::createHeaderBlock<MachO64LE>(MOP, Opts, JD, G, HeaderSection);
1844 default:
1845 llvm_unreachable("Unsupported architecture");
1846 }
1847}
1848
1849MaterializationUnit::Interface SimpleMachOHeaderMU::createHeaderInterface(
1850 MachOPlatform &MOP, const SymbolStringPtr &HeaderStartSymbol) {
1851 SymbolFlagsMap HeaderSymbolFlags;
1852
1853 HeaderSymbolFlags[HeaderStartSymbol] = JITSymbolFlags::Exported;
1854 for (auto &HS : AdditionalHeaderSymbols)
1855 HeaderSymbolFlags[MOP.getExecutionSession().intern(HS.Name)] =
1857
1858 return MaterializationUnit::Interface(std::move(HeaderSymbolFlags),
1859 HeaderStartSymbol);
1860}
1861
1863 switch (TT.getArch()) {
1864 case Triple::aarch64:
1865 return {/* PageSize = */ 16 * 1024,
1866 /* CPUType = */ MachO::CPU_TYPE_ARM64,
1867 /* CPUSubType = */ MachO::CPU_SUBTYPE_ARM64_ALL};
1868 case Triple::x86_64:
1869 return {/* PageSize = */ 4 * 1024,
1870 /* CPUType = */ MachO::CPU_TYPE_X86_64,
1871 /* CPUSubType = */ MachO::CPU_SUBTYPE_X86_64_ALL};
1872 default:
1873 llvm_unreachable("Unrecognized architecture");
1874 }
1875}
1876
1877} // End namespace orc.
1878} // End namespace llvm.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:344
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:343
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
#define _
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
#define P(N)
static StringRef getName(Value *V)
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
unsigned size() const
Definition DenseMap.h:172
bool empty() const
Definition DenseMap.h:171
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:176
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Manages the enabling and disabling of subtarget specific features.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
An ExecutionSession represents a running JIT program.
Definition Core.h:1111
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition Core.h:1154
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1165
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Definition Core.h:1134
Represents an address in the executor process.
Represents a JIT'd dynamic library.
Definition Core.h:675
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition Core.h:1649
Mediates between MachO initialization and ExecutionSession state.
Error teardownJITDylib(JITDylib &JD) override
This method will be called outside the session lock each time a JITDylib is removed to allow the Plat...
static ArrayRef< std::pair< const char *, const char * > > standardLazyCompilationAliases()
Returns a list of aliases required to enable lazy compilation via the ORC runtime.
Error setupJITDylib(JITDylib &JD) override
This method will be called outside the session lock each time a JITDylib is created (unless it is cre...
static ArrayRef< std::pair< const char *, const char * > > standardRuntimeUtilityAliases()
Returns the array of standard runtime utility aliases for MachO.
static Expected< std::unique_ptr< MachOPlatform > > Create(ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD, std::unique_ptr< DefinitionGenerator > OrcRuntime, HeaderOptionsBuilder BuildHeaderOpts=defaultHeaderOpts, HeaderOptions PlatformJDOpts={}, MachOHeaderMUBuilder BuildMachOHeaderMU=buildSimpleMachOHeaderMU, std::optional< SymbolAliasMap > RuntimeAliases=std::nullopt)
Try to create a MachOPlatform instance, adding the ORC runtime to the given JITDylib.
static HeaderOptions defaultHeaderOpts(JITDylib &JD)
std::vector< std::pair< ExecutorAddr, MachOJITDylibDepInfo > > MachOJITDylibDepInfoMap
unique_function< std::unique_ptr< MaterializationUnit >(MachOPlatform &MOP, HeaderOptions Opts)> MachOHeaderMUBuilder
Used by setupJITDylib to create MachO header MaterializationUnits for JITDylibs.
Error notifyAdding(ResourceTracker &RT, const MaterializationUnit &MU) override
This method will be called under the ExecutionSession lock each time a MaterializationUnit is added t...
static SymbolAliasMap standardPlatformAliases(ExecutionSession &ES)
Returns an AliasMap containing the default aliases for the MachOPlatform.
ExecutionSession & getExecutionSession() const
Error notifyRemoving(ResourceTracker &RT) override
This method will be called under the ExecutionSession lock when a ResourceTracker is removed.
unique_function< HeaderOptions(JITDylib &JD)> HeaderOptionsBuilder
Callback for generating HeaderOptions structs for new JITDylibs.
static ArrayRef< std::pair< const char *, const char * > > requiredCXXAliases()
Returns the array of required CXX aliases.
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:349
Error defineMaterializing(SymbolFlagsMap SymbolFlags)
Attempt to claim responsibility for new definitions.
Definition Core.h:1780
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
Definition Core.h:388
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition Core.h:374
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
virtual StringRef getName() const =0
Return the name of this materialization unit.
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization symbol for this MaterializationUnit (if any).
An ObjectLayer implementation built on JITLink.
static void lookupInitSymbolsAsync(unique_function< void(Error)> OnComplete, ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
Performs an async lookup for the given symbols in each of the given JITDylibs, calling the given hand...
Definition Core.cpp:1489
API to remove / transfer ownership of JIT resources.
Definition Core.h:63
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition Core.h:78
MachOPlatform::HeaderOptions Opts
void materialize(std::unique_ptr< MaterializationResponsibility > R) override
Implementations of this method should materialize all symbols in the materialzation unit,...
virtual jitlink::Block & createHeaderBlock(JITDylib &JD, jitlink::LinkGraph &G, jitlink::Section &HeaderSection)
SimpleMachOHeaderMU(MachOPlatform &MOP, SymbolStringPtr HeaderStartSymbol, MachOPlatform::HeaderOptions Opts)
void discard(const JITDylib &JD, const SymbolStringPtr &Sym) override
Implementations of this method should discard the given symbol from the source (e....
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName, VisitMembersFunction VisitMembers=VisitMembersFunction(), GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibraryDefinitionGenerator from the given path.
Pointer to a pooled string representing a symbol name.
A utility class for serializing to a blob from a variadic list.
Input char buffer with underflow check.
Output char buffer with overflow check.
static bool deserialize(SPSInputBuffer &IB, MachOPlatform::MachOExecutorSymbolFlags &SF)
static bool serialize(SPSOutputBuffer &OB, const MachOPlatform::MachOExecutorSymbolFlags &SF)
static bool serialize(SPSOutputBuffer &OB, const MachOPlatform::MachOJITDylibDepInfo &DDI)
static bool deserialize(SPSInputBuffer &IB, MachOPlatform::MachOJITDylibDepInfo &DDI)
Specialize to describe how to serialize/deserialize to/from the given concrete type.
static Expected< WrapperFunctionCall > Create(ExecutorAddr FnAddr, const ArgTs &...Args)
Create a WrapperFunctionCall using the given SPS serializer to serialize the arguments.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ MH_DYLIB
Definition MachO.h:48
@ S_REGULAR
S_REGULAR - Regular section.
Definition MachO.h:127
void swapStruct(fat_header &mh)
Definition MachO.h:1203
@ MH_MAGIC_64
Definition MachO.h:32
@ CPU_SUBTYPE_ARM64_ALL
Definition MachO.h:1715
@ CPU_SUBTYPE_X86_64_ALL
Definition MachO.h:1682
@ CPU_TYPE_ARM64
Definition MachO.h:1639
@ CPU_TYPE_X86_64
Definition MachO.h:1635
SPSTuple< bool, SPSSequence< SPSExecutorAddr > > SPSMachOJITDylibDepInfo
std::vector< AllocActionCallPair > AllocActions
A vector of allocation actions to be run for this allocation.
SPSSequence< SPSTuple< SPSExecutorAddr, SPSMachOJITDylibDepInfo > > SPSMachOJITDylibDepInfoMap
SPSTuple< SPSExecutorAddr, SPSExecutorAddr > SPSExecutorAddrRange
LLVM_ABI StringRef MachOSwift5EntrySectionName
LLVM_ABI StringRef MachOThreadBSSSectionName
LLVM_ABI StringRef MachOThreadVarsSectionName
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition Core.h:153
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition Core.h:148
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition Core.h:58
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition Core.h:523
LLVM_ABI StringRef MachOObjCProtoListSectionName
LLVM_ABI StringRef MachOSwift5ProtosSectionName
LLVM_ABI StringRef MachOEHFrameSectionName
LLVM_ABI StringRef MachOModInitFuncSectionName
LLVM_ABI StringRef MachOObjCConstSectionName
LLVM_ABI StringRef MachODataDataSectionName
std::unique_ptr< ReExportsMaterializationUnit > reexports(JITDylib &SourceJD, SymbolAliasMap Aliases, JITDylibLookupFlags SourceJDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Create a materialization unit for re-exporting symbols from another JITDylib with alternative names/f...
Definition Core.h:532
LLVM_ABI StringRef MachOCompactUnwindSectionName
LLVM_ABI StringRef MachOSwift5ProtoSectionName
static void addAliases(ExecutionSession &ES, SymbolAliasMap &Aliases, ArrayRef< std::pair< const char *, const char * > > AL)
LLVM_ABI StringRef MachOObjCCatListSectionName
LLVM_ABI StringRef MachOObjCClassRefsSectionName
LLVM_ABI StringRef MachOObjCDataSectionName
LLVM_ABI StringRef MachOObjCClassNameSectionName
LLVM_ABI StringRef MachOObjCMethNameSectionName
LLVM_ABI StringRef MachOInitSectionNames[22]
LLVM_ABI StringRef MachOObjCClassListSectionName
LLVM_ABI StringRef MachOObjCSelRefsSectionName
LLVM_ABI StringRef MachOSwift5FieldMetadataSectionName
LLVM_ABI StringRef MachOCStringSectionName
LLVM_ABI StringRef MachOObjCMethTypeSectionName
LLVM_ABI StringRef MachOSwift5TypesSectionName
LLVM_ABI StringRef MachOObjCNLCatListSectionName
jitlink::Block & createHeaderBlock(MachOPlatform &MOP, const MachOPlatform::HeaderOptions &Opts, JITDylib &JD, jitlink::LinkGraph &G, jitlink::Section &HeaderSection)
LLVM_ABI StringRef MachOObjCNLClassListSectionName
LLVM_ABI StringRef MachOObjCImageInfoSectionName
LLVM_ABI MachOHeaderInfo getMachOHeaderInfoFromTriple(const Triple &TT)
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition Core.cpp:40
LLVM_ABI StringRef MachOThreadDataSectionName
LLVM_ABI StringRef MachOUnwindInfoSectionName
LLVM_ABI StringRef MachODataCommonSectionName
LLVM_ABI StringRef MachOObjCProtoRefsSectionName
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:551
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition Core.h:173
LLVM_ABI StringRef MachOSwift5TypeRefSectionName
LLVM_ABI StringRef MachOObjCCatList2SectionName
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
LLVM_ABI iterator begin() const
value_type byte_swap(value_type value, endianness endian)
Definition Endian.h:44
uint32_t read32(const void *P, endianness E)
Definition Endian.h:412
void write32(void *P, uint32_t V, endianness E)
Definition Endian.h:455
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
static LLVM_ABI std::optional< BuildVersionOpts > fromTriple(const Triple &TT, uint32_t MinOS, uint32_t SDK)
Configuration for the mach-o header of a JITDylib.
std::optional< std::string > TargetTriple
Optional LC_TARGET_TRIPLE.
std::optional< Dylib > IDDylib
Override for LC_IC_DYLIB.
std::optional< std::array< uint8_t, 16 > > UUID
Optional UUID. If set, this will be used to add an LC_UUID command.
std::vector< std::string > RPaths
List of LC_RPATHs.
std::vector< BuildVersionOpts > BuildVersions
List of LC_BUILD_VERSIONs.
std::vector< LoadDylibCmd > LoadDylibs
List of LC_LOAD_DYLIBs.