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