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 =
803 &MR.getTargetJITDylib() == &MP.PlatformJD && MP.Bootstrap;
804
805 // If we're in the bootstrap phase then increment the active graphs.
806 if (InBootstrapPhase) {
807 Config.PrePrunePasses.push_back(
808 [this](LinkGraph &G) { return bootstrapPipelineStart(G); });
809 Config.PostAllocationPasses.push_back([this](LinkGraph &G) {
810 return bootstrapPipelineRecordRuntimeFunctions(G);
811 });
812 }
813
814 // --- Handle Initializers ---
815 if (auto InitSymbol = MR.getInitializerSymbol()) {
816
817 // If the initializer symbol is the MachOHeader start symbol then just
818 // register it and then bail out -- the header materialization unit
819 // definitely doesn't need any other passes.
820 if (InitSymbol == MP.MachOHeaderStartSymbol && !InBootstrapPhase) {
821 Config.PostAllocationPasses.push_back([this, &MR](LinkGraph &G) {
822 return associateJITDylibHeaderSymbol(G, MR);
823 });
824 return;
825 }
826
827 // If the object contains an init symbol other than the header start symbol
828 // then add passes to preserve, process and register the init
829 // sections/symbols.
830 Config.PrePrunePasses.push_back([this, &MR](LinkGraph &G) {
831 if (auto Err = preserveImportantSections(G, MR))
832 return Err;
833 return processObjCImageInfo(G, MR);
834 });
835 Config.PostPrunePasses.push_back(
836 [this](LinkGraph &G) { return createObjCRuntimeObject(G); });
837 Config.PostAllocationPasses.push_back(
838 [this, &MR](LinkGraph &G) { return populateObjCRuntimeObject(G, MR); });
839 }
840
841 // Insert TLV lowering at the start of the PostPrunePasses, since we want
842 // it to run before GOT/PLT lowering.
843 Config.PostPrunePasses.insert(
844 Config.PostPrunePasses.begin(),
845 [this, &JD = MR.getTargetJITDylib()](LinkGraph &G) {
846 return fixTLVSectionsAndEdges(G, JD);
847 });
848
849 // Add symbol table prepare and register passes: These will add strings for
850 // all symbols to the c-strings section, and build a symbol table registration
851 // call.
852 auto JITSymTabInfo = std::make_shared<JITSymTabVector>();
853 Config.PostPrunePasses.push_back([this, JITSymTabInfo](LinkGraph &G) {
854 return prepareSymbolTableRegistration(G, *JITSymTabInfo);
855 });
856 Config.PostFixupPasses.push_back([this, &MR, JITSymTabInfo,
857 InBootstrapPhase](LinkGraph &G) {
858 return addSymbolTableRegistration(G, MR, *JITSymTabInfo, InBootstrapPhase);
859 });
860
861 // Add a pass to register the final addresses of any special sections in the
862 // object with the runtime.
863 Config.PostAllocationPasses.push_back(
864 [this, &JD = MR.getTargetJITDylib(), InBootstrapPhase](LinkGraph &G) {
865 return registerObjectPlatformSections(G, JD, InBootstrapPhase);
866 });
867
868 // If we're in the bootstrap phase then steal allocation actions and then
869 // decrement the active graphs.
870 if (InBootstrapPhase)
871 Config.PostFixupPasses.push_back(
872 [this](LinkGraph &G) { return bootstrapPipelineEnd(G); });
873}
874
875Error MachOPlatform::MachOPlatformPlugin::bootstrapPipelineStart(
877 // Increment the active graphs count in BootstrapInfo.
878 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
879 ++MP.Bootstrap.load()->ActiveGraphs;
880 return Error::success();
881}
882
883Error MachOPlatform::MachOPlatformPlugin::
884 bootstrapPipelineRecordRuntimeFunctions(jitlink::LinkGraph &G) {
885 // Record bootstrap function names.
886 std::pair<StringRef, ExecutorAddr *> RuntimeSymbols[] = {
887 {*MP.MachOHeaderStartSymbol, &MP.Bootstrap.load()->MachOHeaderAddr},
888 {*MP.PlatformBootstrap.Name, &MP.PlatformBootstrap.Addr},
889 {*MP.PlatformShutdown.Name, &MP.PlatformShutdown.Addr},
890 {*MP.RegisterJITDylib.Name, &MP.RegisterJITDylib.Addr},
891 {*MP.DeregisterJITDylib.Name, &MP.DeregisterJITDylib.Addr},
892 {*MP.RegisterObjectSymbolTable.Name, &MP.RegisterObjectSymbolTable.Addr},
893 {*MP.DeregisterObjectSymbolTable.Name,
894 &MP.DeregisterObjectSymbolTable.Addr},
895 {*MP.RegisterObjectPlatformSections.Name,
896 &MP.RegisterObjectPlatformSections.Addr},
897 {*MP.DeregisterObjectPlatformSections.Name,
898 &MP.DeregisterObjectPlatformSections.Addr},
899 {*MP.CreatePThreadKey.Name, &MP.CreatePThreadKey.Addr},
900 {*MP.RegisterObjCRuntimeObject.Name, &MP.RegisterObjCRuntimeObject.Addr},
901 {*MP.DeregisterObjCRuntimeObject.Name,
902 &MP.DeregisterObjCRuntimeObject.Addr}};
903
904 bool RegisterMachOHeader = false;
905
906 for (auto *Sym : G.defined_symbols()) {
907 for (auto &RTSym : RuntimeSymbols) {
908 if (Sym->hasName() && *Sym->getName() == RTSym.first) {
909 if (*RTSym.second)
910 return make_error<StringError>(
911 "Duplicate " + RTSym.first +
912 " detected during MachOPlatform bootstrap",
914
915 if (Sym->getName() == MP.MachOHeaderStartSymbol)
916 RegisterMachOHeader = true;
917
918 *RTSym.second = Sym->getAddress();
919 }
920 }
921 }
922
923 if (RegisterMachOHeader) {
924 // If this graph defines the macho header symbol then create the internal
925 // mapping between it and PlatformJD.
926 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
927 MP.JITDylibToHeaderAddr[&MP.PlatformJD] =
928 MP.Bootstrap.load()->MachOHeaderAddr;
929 MP.HeaderAddrToJITDylib[MP.Bootstrap.load()->MachOHeaderAddr] =
930 &MP.PlatformJD;
931 }
932
933 return Error::success();
934}
935
936Error MachOPlatform::MachOPlatformPlugin::bootstrapPipelineEnd(
938 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
939 assert(MP.Bootstrap && "DeferredAAs reset before bootstrap completed");
940 --MP.Bootstrap.load()->ActiveGraphs;
941 // Notify Bootstrap->CV while holding the mutex because the mutex is
942 // also keeping Bootstrap->CV alive.
943 if (MP.Bootstrap.load()->ActiveGraphs == 0)
944 MP.Bootstrap.load()->CV.notify_all();
945 return Error::success();
946}
947
948Error MachOPlatform::MachOPlatformPlugin::associateJITDylibHeaderSymbol(
950 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
951 return Sym->getName() == MP.MachOHeaderStartSymbol;
952 });
953 assert(I != G.defined_symbols().end() && "Missing MachO header start symbol");
954
955 auto &JD = MR.getTargetJITDylib();
956 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
957 auto HeaderAddr = (*I)->getAddress();
958 MP.JITDylibToHeaderAddr[&JD] = HeaderAddr;
959 MP.HeaderAddrToJITDylib[HeaderAddr] = &JD;
960 // We can unconditionally add these actions to the Graph because this pass
961 // isn't used during bootstrap.
962 G.allocActions().push_back(
963 {cantFail(
965 MP.RegisterJITDylib.Addr, JD.getName(), HeaderAddr)),
967 MP.DeregisterJITDylib.Addr, HeaderAddr))});
968 return Error::success();
969}
970
971Error MachOPlatform::MachOPlatformPlugin::preserveImportantSections(
973 // __objc_imageinfo is "important": we want to preserve it and record its
974 // address in the first graph that it appears in, then verify and discard it
975 // in all subsequent graphs. In this pass we preserve unconditionally -- we'll
976 // manually throw it away in the processObjCImageInfo pass.
977 if (auto *ObjCImageInfoSec =
978 G.findSectionByName(MachOObjCImageInfoSectionName)) {
979 if (ObjCImageInfoSec->blocks_size() != 1)
980 return make_error<StringError>(
981 "In " + G.getName() +
982 "__DATA,__objc_imageinfo contains multiple blocks",
984 G.addAnonymousSymbol(**ObjCImageInfoSec->blocks().begin(), 0, 0, false,
985 true);
986
987 for (auto *B : ObjCImageInfoSec->blocks())
988 if (!B->edges_empty())
989 return make_error<StringError>("In " + G.getName() + ", " +
991 " contains references to symbols",
993 }
994
995 // Init sections are important: We need to preserve them and so that their
996 // addresses can be captured and reported to the ORC runtime in
997 // registerObjectPlatformSections.
998 if (const auto &InitSymName = MR.getInitializerSymbol()) {
999
1000 jitlink::Symbol *InitSym = nullptr;
1001 for (auto &InitSectionName : MachOInitSectionNames) {
1002 // Skip ObjCImageInfo -- this shouldn't have any dependencies, and we may
1003 // remove it later.
1004 if (InitSectionName == MachOObjCImageInfoSectionName)
1005 continue;
1006
1007 // Skip non-init sections.
1008 auto *InitSection = G.findSectionByName(InitSectionName);
1009 if (!InitSection || InitSection->empty())
1010 continue;
1011
1012 // Create the init symbol if it has not been created already and attach it
1013 // to the first block.
1014 if (!InitSym) {
1015 auto &B = **InitSection->blocks().begin();
1016 InitSym = &G.addDefinedSymbol(
1017 B, 0, *InitSymName, B.getSize(), jitlink::Linkage::Strong,
1018 jitlink::Scope::SideEffectsOnly, false, true);
1019 }
1020
1021 // Add keep-alive edges to anonymous symbols in all other init blocks.
1022 for (auto *B : InitSection->blocks()) {
1023 if (B == &InitSym->getBlock())
1024 continue;
1025
1026 auto &S = G.addAnonymousSymbol(*B, 0, B->getSize(), false, true);
1027 InitSym->getBlock().addEdge(jitlink::Edge::KeepAlive, 0, S, 0);
1028 }
1029 }
1030 }
1031
1032 return Error::success();
1033}
1034
1035Error MachOPlatform::MachOPlatformPlugin::processObjCImageInfo(
1037
1038 // If there's an ObjC imagine info then either
1039 // (1) It's the first __objc_imageinfo we've seen in this JITDylib. In
1040 // this case we name and record it.
1041 // OR
1042 // (2) We already have a recorded __objc_imageinfo for this JITDylib,
1043 // in which case we just verify it.
1044 auto *ObjCImageInfo = G.findSectionByName(MachOObjCImageInfoSectionName);
1045 if (!ObjCImageInfo)
1046 return Error::success();
1047
1048 auto ObjCImageInfoBlocks = ObjCImageInfo->blocks();
1049
1050 // Check that the section is not empty if present.
1051 if (ObjCImageInfoBlocks.empty())
1052 return make_error<StringError>("Empty " + MachOObjCImageInfoSectionName +
1053 " section in " + G.getName(),
1055
1056 // Check that there's only one block in the section.
1057 if (std::next(ObjCImageInfoBlocks.begin()) != ObjCImageInfoBlocks.end())
1058 return make_error<StringError>("Multiple blocks in " +
1060 " section in " + G.getName(),
1062
1063 // Check that the __objc_imageinfo section is unreferenced.
1064 // FIXME: We could optimize this check if Symbols had a ref-count.
1065 for (auto &Sec : G.sections()) {
1066 if (&Sec != ObjCImageInfo)
1067 for (auto *B : Sec.blocks())
1068 for (auto &E : B->edges())
1069 if (E.getTarget().isDefined() &&
1070 &E.getTarget().getBlock().getSection() == ObjCImageInfo)
1071 return make_error<StringError>(MachOObjCImageInfoSectionName +
1072 " is referenced within file " +
1073 G.getName(),
1075 }
1076
1077 auto &ObjCImageInfoBlock = **ObjCImageInfoBlocks.begin();
1078 auto *ObjCImageInfoData = ObjCImageInfoBlock.getContent().data();
1079 auto Version = support::endian::read32(ObjCImageInfoData, G.getEndianness());
1080 auto Flags =
1081 support::endian::read32(ObjCImageInfoData + 4, G.getEndianness());
1082
1083 // Lock the mutex while we verify / update the ObjCImageInfos map.
1084 std::lock_guard<std::mutex> Lock(PluginMutex);
1085
1086 auto ObjCImageInfoItr = ObjCImageInfos.find(&MR.getTargetJITDylib());
1087 if (ObjCImageInfoItr != ObjCImageInfos.end()) {
1088 // We've already registered an __objc_imageinfo section. Verify the
1089 // content of this new section matches, then delete it.
1090 if (ObjCImageInfoItr->second.Version != Version)
1091 return make_error<StringError>(
1092 "ObjC version in " + G.getName() +
1093 " does not match first registered version",
1095 if (ObjCImageInfoItr->second.Flags != Flags)
1096 if (Error E = mergeImageInfoFlags(G, MR, ObjCImageInfoItr->second, Flags))
1097 return E;
1098
1099 // __objc_imageinfo is valid. Delete the block.
1100 for (auto *S : ObjCImageInfo->symbols())
1101 G.removeDefinedSymbol(*S);
1102 G.removeBlock(ObjCImageInfoBlock);
1103 } else {
1104 LLVM_DEBUG({
1105 dbgs() << "MachOPlatform: Registered __objc_imageinfo for "
1106 << MR.getTargetJITDylib().getName() << " in " << G.getName()
1107 << "; flags = " << formatv("{0:x4}", Flags) << "\n";
1108 });
1109 // We haven't registered an __objc_imageinfo section yet. Register and
1110 // move on. The section should already be marked no-dead-strip.
1111 G.addDefinedSymbol(ObjCImageInfoBlock, 0, ObjCImageInfoSymbolName,
1112 ObjCImageInfoBlock.getSize(), jitlink::Linkage::Strong,
1113 jitlink::Scope::Hidden, false, true);
1114 if (auto Err = MR.defineMaterializing(
1115 {{MR.getExecutionSession().intern(ObjCImageInfoSymbolName),
1116 JITSymbolFlags()}}))
1117 return Err;
1118 ObjCImageInfos[&MR.getTargetJITDylib()] = {Version, Flags, false};
1119 }
1120
1121 return Error::success();
1122}
1123
1124Error MachOPlatform::MachOPlatformPlugin::mergeImageInfoFlags(
1126 ObjCImageInfo &Info, uint32_t NewFlags) {
1127 if (Info.Flags == NewFlags)
1128 return Error::success();
1129
1130 ObjCImageInfoFlags Old(Info.Flags);
1131 ObjCImageInfoFlags New(NewFlags);
1132
1133 // Check for incompatible flags.
1134 if (Old.SwiftABIVersion && New.SwiftABIVersion &&
1135 Old.SwiftABIVersion != New.SwiftABIVersion)
1136 return make_error<StringError>("Swift ABI version in " + G.getName() +
1137 " does not match first registered flags",
1139
1140 // HasCategoryClassProperties and HasSignedObjCClassROs can be disabled before
1141 // they are registered, if necessary, but once they are in use must be
1142 // supported by subsequent objects.
1143 if (Info.Finalized && Old.HasCategoryClassProperties &&
1144 !New.HasCategoryClassProperties)
1145 return make_error<StringError>("ObjC category class property support in " +
1146 G.getName() +
1147 " does not match first registered flags",
1149 if (Info.Finalized && Old.HasSignedObjCClassROs && !New.HasSignedObjCClassROs)
1150 return make_error<StringError>("ObjC class_ro_t pointer signing in " +
1151 G.getName() +
1152 " does not match first registered flags",
1154
1155 // If we cannot change the flags, ignore any remaining differences. Adding
1156 // Swift or changing its version are unlikely to cause problems in practice.
1157 if (Info.Finalized)
1158 return Error::success();
1159
1160 // Use the minimum Swift version.
1161 if (Old.SwiftVersion && New.SwiftVersion)
1162 New.SwiftVersion = std::min(Old.SwiftVersion, New.SwiftVersion);
1163 else if (Old.SwiftVersion)
1164 New.SwiftVersion = Old.SwiftVersion;
1165 // Add a Swift ABI version if it was pure objc before.
1166 if (!New.SwiftABIVersion)
1167 New.SwiftABIVersion = Old.SwiftABIVersion;
1168 // Disable class properties if any object does not support it.
1169 if (Old.HasCategoryClassProperties != New.HasCategoryClassProperties)
1170 New.HasCategoryClassProperties = false;
1171 // Disable signed class ro data if any object does not support it.
1172 if (Old.HasSignedObjCClassROs != New.HasSignedObjCClassROs)
1173 New.HasSignedObjCClassROs = false;
1174
1175 LLVM_DEBUG({
1176 dbgs() << "MachOPlatform: Merging __objc_imageinfo flags for "
1177 << MR.getTargetJITDylib().getName() << " (was "
1178 << formatv("{0:x4}", Old.rawFlags()) << ")"
1179 << " with " << G.getName() << " (" << formatv("{0:x4}", NewFlags)
1180 << ")"
1181 << " -> " << formatv("{0:x4}", New.rawFlags()) << "\n";
1182 });
1183
1184 Info.Flags = New.rawFlags();
1185 return Error::success();
1186}
1187
1188Error MachOPlatform::MachOPlatformPlugin::fixTLVSectionsAndEdges(
1190 auto TLVBootStrapSymbolName = G.intern("__tlv_bootstrap");
1191 // Rename external references to __tlv_bootstrap to ___orc_rt_tlv_get_addr.
1192 for (auto *Sym : G.external_symbols())
1193 if (Sym->getName() == TLVBootStrapSymbolName) {
1194 auto TLSGetADDR =
1195 MP.getExecutionSession().intern("___orc_rt_macho_tlv_get_addr");
1196 Sym->setName(std::move(TLSGetADDR));
1197 break;
1198 }
1199
1200 // Store key in __thread_vars struct fields.
1201 if (auto *ThreadDataSec = G.findSectionByName(MachOThreadVarsSectionName)) {
1202 std::optional<uint64_t> Key;
1203 {
1204 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1205 auto I = MP.JITDylibToPThreadKey.find(&JD);
1206 if (I != MP.JITDylibToPThreadKey.end())
1207 Key = I->second;
1208 }
1209
1210 if (!Key) {
1211 if (auto KeyOrErr = MP.createPThreadKey())
1212 Key = *KeyOrErr;
1213 else
1214 return KeyOrErr.takeError();
1215 }
1216
1217 uint64_t PlatformKeyBits =
1218 support::endian::byte_swap(*Key, G.getEndianness());
1219
1220 for (auto *B : ThreadDataSec->blocks()) {
1221 if (B->getSize() != 3 * G.getPointerSize())
1222 return make_error<StringError>("__thread_vars block at " +
1223 formatv("{0:x}", B->getAddress()) +
1224 " has unexpected size",
1226
1227 auto NewBlockContent = G.allocateBuffer(B->getSize());
1228 llvm::copy(B->getContent(), NewBlockContent.data());
1229 memcpy(NewBlockContent.data() + G.getPointerSize(), &PlatformKeyBits,
1230 G.getPointerSize());
1231 B->setContent(NewBlockContent);
1232 }
1233 }
1234
1235 // Transform any TLV edges into GOT edges.
1236 for (auto *B : G.blocks())
1237 for (auto &E : B->edges())
1238 if (E.getKind() ==
1240 E.setKind(jitlink::x86_64::
1241 RequestGOTAndTransformToPCRel32GOTLoadREXRelaxable);
1242
1243 return Error::success();
1244}
1245
1246std::optional<MachOPlatform::MachOPlatformPlugin::UnwindSections>
1247MachOPlatform::MachOPlatformPlugin::findUnwindSectionInfo(
1249 using namespace jitlink;
1250
1251 UnwindSections US;
1252
1253 // ScanSection records a section range and adds any executable blocks that
1254 // that section points to to the CodeBlocks vector.
1255 SmallVector<Block *> CodeBlocks;
1256 auto ScanUnwindInfoSection = [&](Section &Sec, ExecutorAddrRange &SecRange) {
1257 if (Sec.blocks().empty())
1258 return;
1259 SecRange = (*Sec.blocks().begin())->getRange();
1260 for (auto *B : Sec.blocks()) {
1261 auto R = B->getRange();
1262 SecRange.Start = std::min(SecRange.Start, R.Start);
1263 SecRange.End = std::max(SecRange.End, R.End);
1264 for (auto &E : B->edges()) {
1265 if (!E.getTarget().isDefined())
1266 continue;
1267 auto &TargetBlock = E.getTarget().getBlock();
1268 auto &TargetSection = TargetBlock.getSection();
1269 if ((TargetSection.getMemProt() & MemProt::Exec) == MemProt::Exec)
1270 CodeBlocks.push_back(&TargetBlock);
1271 }
1272 }
1273 };
1274
1275 if (Section *EHFrameSec = G.findSectionByName(MachOEHFrameSectionName))
1276 ScanUnwindInfoSection(*EHFrameSec, US.DwarfSection);
1277
1278 if (Section *CUInfoSec =
1279 G.findSectionByName(MachOCompactUnwindInfoSectionName))
1280 ScanUnwindInfoSection(*CUInfoSec, US.CompactUnwindSection);
1281
1282 // If we didn't find any pointed-to code-blocks then there's no need to
1283 // register any info.
1284 if (CodeBlocks.empty())
1285 return std::nullopt;
1286
1287 // We have info to register. Sort the code blocks into address order and
1288 // build a list of contiguous address ranges covering them all.
1289 llvm::sort(CodeBlocks, [](const Block *LHS, const Block *RHS) {
1290 return LHS->getAddress() < RHS->getAddress();
1291 });
1292 for (auto *B : CodeBlocks) {
1293 if (US.CodeRanges.empty() || US.CodeRanges.back().End != B->getAddress())
1294 US.CodeRanges.push_back(B->getRange());
1295 else
1296 US.CodeRanges.back().End = B->getRange().End;
1297 }
1298
1299 LLVM_DEBUG({
1300 dbgs() << "MachOPlatform identified unwind info in " << G.getName() << ":\n"
1301 << " DWARF: ";
1302 if (US.DwarfSection.Start)
1303 dbgs() << US.DwarfSection << "\n";
1304 else
1305 dbgs() << "none\n";
1306 dbgs() << " Compact-unwind: ";
1307 if (US.CompactUnwindSection.Start)
1308 dbgs() << US.CompactUnwindSection << "\n";
1309 else
1310 dbgs() << "none\n"
1311 << "for code ranges:\n";
1312 for (auto &CR : US.CodeRanges)
1313 dbgs() << " " << CR << "\n";
1314 if (US.CodeRanges.size() >= G.sections_size())
1315 dbgs() << "WARNING: High number of discontiguous code ranges! "
1316 "Padding may be interfering with coalescing.\n";
1317 });
1318
1319 return US;
1320}
1321
1322Error MachOPlatform::MachOPlatformPlugin::registerObjectPlatformSections(
1323 jitlink::LinkGraph &G, JITDylib &JD, bool InBootstrapPhase) {
1324
1325 // Get a pointer to the thread data section if there is one. It will be used
1326 // below.
1327 jitlink::Section *ThreadDataSection =
1328 G.findSectionByName(MachOThreadDataSectionName);
1329
1330 // Handle thread BSS section if there is one.
1331 if (auto *ThreadBSSSection = G.findSectionByName(MachOThreadBSSSectionName)) {
1332 // If there's already a thread data section in this graph then merge the
1333 // thread BSS section content into it, otherwise just treat the thread
1334 // BSS section as the thread data section.
1335 if (ThreadDataSection)
1336 G.mergeSections(*ThreadDataSection, *ThreadBSSSection);
1337 else
1338 ThreadDataSection = ThreadBSSSection;
1339 }
1340
1342
1343 // Collect data sections to register.
1344 StringRef DataSections[] = {MachODataDataSectionName,
1347 for (auto &SecName : DataSections) {
1348 if (auto *Sec = G.findSectionByName(SecName)) {
1350 if (!R.empty())
1351 MachOPlatformSecs.push_back({SecName, R.getRange()});
1352 }
1353 }
1354
1355 // Having merged thread BSS (if present) and thread data (if present),
1356 // record the resulting section range.
1357 if (ThreadDataSection) {
1358 jitlink::SectionRange R(*ThreadDataSection);
1359 if (!R.empty())
1360 MachOPlatformSecs.push_back({MachOThreadDataSectionName, R.getRange()});
1361 }
1362
1363 // If any platform sections were found then add an allocation action to call
1364 // the registration function.
1365 StringRef PlatformSections[] = {MachOModInitFuncSectionName,
1366 ObjCRuntimeObjectSectionName};
1367
1368 for (auto &SecName : PlatformSections) {
1369 auto *Sec = G.findSectionByName(SecName);
1370 if (!Sec)
1371 continue;
1373 if (R.empty())
1374 continue;
1375
1376 MachOPlatformSecs.push_back({SecName, R.getRange()});
1377 }
1378
1379 std::optional<std::tuple<SmallVector<ExecutorAddrRange>, ExecutorAddrRange,
1381 UnwindInfo;
1382 if (auto UI = findUnwindSectionInfo(G))
1383 UnwindInfo = std::make_tuple(std::move(UI->CodeRanges), UI->DwarfSection,
1384 UI->CompactUnwindSection);
1385
1386 if (!MachOPlatformSecs.empty() || UnwindInfo) {
1387 // Dump the scraped inits.
1388 LLVM_DEBUG({
1389 dbgs() << "MachOPlatform: Scraped " << G.getName() << " init sections:\n";
1390 for (auto &KV : MachOPlatformSecs)
1391 dbgs() << " " << KV.first << ": " << KV.second << "\n";
1392 });
1393
1394 using SPSRegisterObjectPlatformSectionsArgs = SPSArgList<
1399
1400 shared::AllocActions &allocActions = LLVM_LIKELY(!InBootstrapPhase)
1401 ? G.allocActions()
1402 : MP.Bootstrap.load()->DeferredAAs;
1403
1404 ExecutorAddr HeaderAddr;
1405 {
1406 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1407 auto I = MP.JITDylibToHeaderAddr.find(&JD);
1408 assert(I != MP.JITDylibToHeaderAddr.end() &&
1409 "No header registered for JD");
1410 assert(I->second && "Null header registered for JD");
1411 HeaderAddr = I->second;
1412 }
1413 allocActions.push_back(
1414 {cantFail(
1415 WrapperFunctionCall::Create<SPSRegisterObjectPlatformSectionsArgs>(
1416 MP.RegisterObjectPlatformSections.Addr, HeaderAddr, UnwindInfo,
1417 MachOPlatformSecs)),
1418 cantFail(
1419 WrapperFunctionCall::Create<SPSRegisterObjectPlatformSectionsArgs>(
1420 MP.DeregisterObjectPlatformSections.Addr, HeaderAddr,
1421 UnwindInfo, MachOPlatformSecs))});
1422 }
1423
1424 return Error::success();
1425}
1426
1427Error MachOPlatform::MachOPlatformPlugin::createObjCRuntimeObject(
1429
1430 bool NeedTextSegment = false;
1431 size_t NumRuntimeSections = 0;
1432
1433 for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsData)
1434 if (G.findSectionByName(ObjCRuntimeSectionName))
1435 ++NumRuntimeSections;
1436
1437 for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsText) {
1438 if (G.findSectionByName(ObjCRuntimeSectionName)) {
1439 ++NumRuntimeSections;
1440 NeedTextSegment = true;
1441 }
1442 }
1443
1444 // Early out for no runtime sections.
1445 if (NumRuntimeSections == 0)
1446 return Error::success();
1447
1448 // If there were any runtime sections then we need to add an __objc_imageinfo
1449 // section.
1450 ++NumRuntimeSections;
1451
1452 size_t MachOSize = sizeof(MachO::mach_header_64) +
1453 (NeedTextSegment + 1) * sizeof(MachO::segment_command_64) +
1454 NumRuntimeSections * sizeof(MachO::section_64);
1455
1456 auto &Sec = G.createSection(ObjCRuntimeObjectSectionName,
1457 MemProt::Read | MemProt::Write);
1458 G.createMutableContentBlock(Sec, MachOSize, ExecutorAddr(), 16, 0, true);
1459
1460 return Error::success();
1461}
1462
1463Error MachOPlatform::MachOPlatformPlugin::populateObjCRuntimeObject(
1465
1466 auto *ObjCRuntimeObjectSec =
1467 G.findSectionByName(ObjCRuntimeObjectSectionName);
1468
1469 if (!ObjCRuntimeObjectSec)
1470 return Error::success();
1471
1472 switch (G.getTargetTriple().getArch()) {
1473 case Triple::aarch64:
1474 case Triple::x86_64:
1475 // Supported.
1476 break;
1477 default:
1478 return make_error<StringError>("Unrecognized MachO arch in triple " +
1479 G.getTargetTriple().str(),
1481 }
1482
1483 auto &SecBlock = **ObjCRuntimeObjectSec->blocks().begin();
1484
1485 struct SecDesc {
1487 unique_function<void(size_t RecordOffset)> AddFixups;
1488 };
1489
1490 std::vector<SecDesc> TextSections, DataSections;
1491 auto AddSection = [&](SecDesc &SD, jitlink::Section &GraphSec) {
1492 jitlink::SectionRange SR(GraphSec);
1493 StringRef FQName = GraphSec.getName();
1494 memset(&SD.Sec, 0, sizeof(MachO::section_64));
1495 memcpy(SD.Sec.sectname, FQName.drop_front(7).data(), FQName.size() - 7);
1496 memcpy(SD.Sec.segname, FQName.data(), 6);
1497 SD.Sec.addr = SR.getStart() - SecBlock.getAddress();
1498 SD.Sec.size = SR.getSize();
1499 SD.Sec.flags = MachO::S_REGULAR;
1500 };
1501
1502 // Add the __objc_imageinfo section.
1503 {
1504 DataSections.push_back({});
1505 auto &SD = DataSections.back();
1506 memset(&SD.Sec, 0, sizeof(SD.Sec));
1507 memcpy(SD.Sec.sectname, "__objc_imageinfo", 16);
1508 strcpy(SD.Sec.segname, "__DATA");
1509 SD.Sec.size = 8;
1510 SD.AddFixups = [&](size_t RecordOffset) {
1511 auto PointerEdge = getPointerEdgeKind(G);
1512
1513 // Look for an existing __objc_imageinfo symbol.
1514 jitlink::Symbol *ObjCImageInfoSym = nullptr;
1515 for (auto *Sym : G.external_symbols())
1516 if (Sym->hasName() && *Sym->getName() == ObjCImageInfoSymbolName) {
1517 ObjCImageInfoSym = Sym;
1518 break;
1519 }
1520 if (!ObjCImageInfoSym)
1521 for (auto *Sym : G.absolute_symbols())
1522 if (Sym->hasName() && *Sym->getName() == ObjCImageInfoSymbolName) {
1523 ObjCImageInfoSym = Sym;
1524 break;
1525 }
1526 if (!ObjCImageInfoSym)
1527 for (auto *Sym : G.defined_symbols())
1528 if (Sym->hasName() && *Sym->getName() == ObjCImageInfoSymbolName) {
1529 ObjCImageInfoSym = Sym;
1530 std::optional<uint32_t> Flags;
1531 {
1532 std::lock_guard<std::mutex> Lock(PluginMutex);
1533 auto It = ObjCImageInfos.find(&MR.getTargetJITDylib());
1534 if (It != ObjCImageInfos.end()) {
1535 It->second.Finalized = true;
1536 Flags = It->second.Flags;
1537 }
1538 }
1539
1540 if (Flags) {
1541 // We own the definition of __objc_image_info; write the final
1542 // merged flags value.
1543 auto Content = Sym->getBlock().getMutableContent(G);
1544 assert(Content.size() == 8 &&
1545 "__objc_image_info size should have been verified already");
1546 support::endian::write32(&Content[4], *Flags, G.getEndianness());
1547 }
1548 break;
1549 }
1550 if (!ObjCImageInfoSym)
1551 ObjCImageInfoSym =
1552 &G.addExternalSymbol(ObjCImageInfoSymbolName, 8, false);
1553
1554 SecBlock.addEdge(PointerEdge,
1555 RecordOffset + ((char *)&SD.Sec.addr - (char *)&SD.Sec),
1556 *ObjCImageInfoSym, -SecBlock.getAddress().getValue());
1557 };
1558 }
1559
1560 for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsData) {
1561 if (auto *GraphSec = G.findSectionByName(ObjCRuntimeSectionName)) {
1562 DataSections.push_back({});
1563 AddSection(DataSections.back(), *GraphSec);
1564 }
1565 }
1566
1567 for (auto ObjCRuntimeSectionName : ObjCRuntimeObjectSectionsText) {
1568 if (auto *GraphSec = G.findSectionByName(ObjCRuntimeSectionName)) {
1569 TextSections.push_back({});
1570 AddSection(TextSections.back(), *GraphSec);
1571 }
1572 }
1573
1574 assert(ObjCRuntimeObjectSec->blocks_size() == 1 &&
1575 "Unexpected number of blocks in runtime sections object");
1576
1577 // Build the header struct up-front. This also gives us a chance to check
1578 // that the triple is supported, which we'll assume below.
1581 switch (G.getTargetTriple().getArch()) {
1582 case Triple::aarch64:
1585 break;
1586 case Triple::x86_64:
1589 break;
1590 default:
1591 llvm_unreachable("Unsupported architecture");
1592 }
1593
1595 Hdr.ncmds = 1 + !TextSections.empty();
1596 Hdr.sizeofcmds =
1597 Hdr.ncmds * sizeof(MachO::segment_command_64) +
1598 (TextSections.size() + DataSections.size()) * sizeof(MachO::section_64);
1599 Hdr.flags = 0;
1600 Hdr.reserved = 0;
1601
1602 auto SecContent = SecBlock.getAlreadyMutableContent();
1603 char *P = SecContent.data();
1604 auto WriteMachOStruct = [&](auto S) {
1605 if (G.getEndianness() != llvm::endianness::native)
1607 memcpy(P, &S, sizeof(S));
1608 P += sizeof(S);
1609 };
1610
1611 auto WriteSegment = [&](StringRef Name, std::vector<SecDesc> &Secs) {
1613 memset(&SegLC, 0, sizeof(SegLC));
1614 memcpy(SegLC.segname, Name.data(), Name.size());
1615 SegLC.cmd = MachO::LC_SEGMENT_64;
1616 SegLC.cmdsize = sizeof(MachO::segment_command_64) +
1617 Secs.size() * sizeof(MachO::section_64);
1618 SegLC.nsects = Secs.size();
1619 WriteMachOStruct(SegLC);
1620 for (auto &SD : Secs) {
1621 if (SD.AddFixups)
1622 SD.AddFixups(P - SecContent.data());
1623 WriteMachOStruct(SD.Sec);
1624 }
1625 };
1626
1627 WriteMachOStruct(Hdr);
1628 if (!TextSections.empty())
1629 WriteSegment("__TEXT", TextSections);
1630 if (!DataSections.empty())
1631 WriteSegment("__DATA", DataSections);
1632
1633 assert(P == SecContent.end() && "Underflow writing ObjC runtime object");
1634 return Error::success();
1635}
1636
1637Error MachOPlatform::MachOPlatformPlugin::prepareSymbolTableRegistration(
1638 jitlink::LinkGraph &G, JITSymTabVector &JITSymTabInfo) {
1639
1640 auto *CStringSec = G.findSectionByName(MachOCStringSectionName);
1641 if (!CStringSec)
1642 CStringSec = &G.createSection(MachOCStringSectionName,
1643 MemProt::Read | MemProt::Exec);
1644
1645 // Make a map of existing strings so that we can re-use them:
1647 for (auto *Sym : CStringSec->symbols()) {
1648
1649 // The LinkGraph builder should have created single strings blocks, and all
1650 // plugins should have maintained this invariant.
1651 auto Content = Sym->getBlock().getContent();
1652 ExistingStrings.insert(
1653 std::make_pair(StringRef(Content.data(), Content.size()), Sym));
1654 }
1655
1656 // Add all symbol names to the string section, and record the symbols for
1657 // those names.
1658 {
1659 SmallVector<jitlink::Symbol *> SymsToProcess;
1660 for (auto *Sym : G.defined_symbols())
1661 SymsToProcess.push_back(Sym);
1662 for (auto *Sym : G.absolute_symbols())
1663 SymsToProcess.push_back(Sym);
1664
1665 for (auto *Sym : SymsToProcess) {
1666 if (!Sym->hasName())
1667 continue;
1668
1669 auto I = ExistingStrings.find(*Sym->getName());
1670 if (I == ExistingStrings.end()) {
1671 auto &NameBlock = G.createMutableContentBlock(
1672 *CStringSec, G.allocateCString(*Sym->getName()),
1673 orc::ExecutorAddr(), 1, 0);
1674 auto &SymbolNameSym = G.addAnonymousSymbol(
1675 NameBlock, 0, NameBlock.getSize(), false, true);
1676 JITSymTabInfo.push_back({Sym, &SymbolNameSym});
1677 } else
1678 JITSymTabInfo.push_back({Sym, I->second});
1679 }
1680 }
1681
1682 return Error::success();
1683}
1684
1685Error MachOPlatform::MachOPlatformPlugin::addSymbolTableRegistration(
1687 JITSymTabVector &JITSymTabInfo, bool InBootstrapPhase) {
1688
1689 ExecutorAddr HeaderAddr;
1690 {
1691 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1692 auto I = MP.JITDylibToHeaderAddr.find(&MR.getTargetJITDylib());
1693 assert(I != MP.JITDylibToHeaderAddr.end() && "No header registered for JD");
1694 assert(I->second && "Null header registered for JD");
1695 HeaderAddr = I->second;
1696 }
1697
1698 if (LLVM_UNLIKELY(InBootstrapPhase)) {
1699 // If we're in the bootstrap phase then just record these symbols in the
1700 // bootstrap object and then bail out -- registration will be attached to
1701 // the bootstrap graph.
1702 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
1703 auto &SymTab = MP.Bootstrap.load()->SymTab;
1704 for (auto &[OriginalSymbol, NameSym] : JITSymTabInfo)
1705 SymTab.push_back({NameSym->getAddress(), OriginalSymbol->getAddress(),
1706 flagsForSymbol(*OriginalSymbol)});
1707 return Error::success();
1708 }
1709
1710 SymbolTableVector SymTab;
1711 for (auto &[OriginalSymbol, NameSym] : JITSymTabInfo)
1712 SymTab.push_back({NameSym->getAddress(), OriginalSymbol->getAddress(),
1713 flagsForSymbol(*OriginalSymbol)});
1714
1715 G.allocActions().push_back(
1716 {cantFail(WrapperFunctionCall::Create<SPSRegisterSymbolsArgs>(
1717 MP.RegisterObjectSymbolTable.Addr, HeaderAddr, SymTab)),
1718 cantFail(WrapperFunctionCall::Create<SPSRegisterSymbolsArgs>(
1719 MP.DeregisterObjectSymbolTable.Addr, HeaderAddr, SymTab))});
1720
1721 return Error::success();
1722}
1723
1724template <typename MachOTraits>
1726 const MachOPlatform::HeaderOptions &Opts,
1728 jitlink::Section &HeaderSection) {
1729 auto HdrInfo =
1731 MachOBuilder<MachOTraits> B(HdrInfo.PageSize);
1732
1733 B.Header.filetype = MachO::MH_DYLIB;
1734 B.Header.cputype = HdrInfo.CPUType;
1735 B.Header.cpusubtype = HdrInfo.CPUSubType;
1736
1737 if (Opts.IDDylib)
1738 B.template addLoadCommand<MachO::LC_ID_DYLIB>(
1739 Opts.IDDylib->Name, Opts.IDDylib->Timestamp,
1740 Opts.IDDylib->CurrentVersion, Opts.IDDylib->CompatibilityVersion);
1741 else
1742 B.template addLoadCommand<MachO::LC_ID_DYLIB>(JD.getName(), 0, 0, 0);
1743
1744 for (auto &BV : Opts.BuildVersions)
1745 B.template addLoadCommand<MachO::LC_BUILD_VERSION>(
1746 BV.Platform, BV.MinOS, BV.SDK, static_cast<uint32_t>(0));
1747 for (auto &D : Opts.LoadDylibs)
1748 B.template addLoadCommand<MachO::LC_LOAD_DYLIB>(
1749 D.Name, D.Timestamp, D.CurrentVersion, D.CompatibilityVersion);
1750 for (auto &P : Opts.RPaths)
1751 B.template addLoadCommand<MachO::LC_RPATH>(P);
1752
1753 auto HeaderContent = G.allocateBuffer(B.layout());
1754 B.write(HeaderContent);
1755
1756 return G.createContentBlock(HeaderSection, HeaderContent, ExecutorAddr(), 8,
1757 0);
1758}
1759
1761 SymbolStringPtr HeaderStartSymbol,
1764 createHeaderInterface(MOP, std::move(HeaderStartSymbol))),
1765 MOP(MOP), Opts(std::move(Opts)) {}
1766
1768 std::unique_ptr<MaterializationResponsibility> R) {
1769 auto G = createPlatformGraph(MOP, "<MachOHeaderMU>");
1770 addMachOHeader(R->getTargetJITDylib(), *G, R->getInitializerSymbol());
1771 MOP.getObjectLinkingLayer().emit(std::move(R), std::move(G));
1772}
1773
1775 const SymbolStringPtr &Sym) {}
1776
1777void SimpleMachOHeaderMU::addMachOHeader(
1779 const SymbolStringPtr &InitializerSymbol) {
1780 auto &HeaderSection = G.createSection("__header", MemProt::Read);
1781 auto &HeaderBlock = createHeaderBlock(JD, G, HeaderSection);
1782
1783 // Init symbol is header-start symbol.
1784 G.addDefinedSymbol(HeaderBlock, 0, *InitializerSymbol, HeaderBlock.getSize(),
1786 true);
1787 for (auto &HS : AdditionalHeaderSymbols)
1788 G.addDefinedSymbol(HeaderBlock, HS.Offset, HS.Name, HeaderBlock.getSize(),
1790 true);
1791}
1792
1795 jitlink::Section &HeaderSection) {
1797 case Triple::aarch64:
1798 case Triple::x86_64:
1799 return ::createHeaderBlock<MachO64LE>(MOP, Opts, JD, G, HeaderSection);
1800 default:
1801 llvm_unreachable("Unsupported architecture");
1802 }
1803}
1804
1805MaterializationUnit::Interface SimpleMachOHeaderMU::createHeaderInterface(
1806 MachOPlatform &MOP, const SymbolStringPtr &HeaderStartSymbol) {
1807 SymbolFlagsMap HeaderSymbolFlags;
1808
1809 HeaderSymbolFlags[HeaderStartSymbol] = JITSymbolFlags::Exported;
1810 for (auto &HS : AdditionalHeaderSymbols)
1811 HeaderSymbolFlags[MOP.getExecutionSession().intern(HS.Name)] =
1813
1814 return MaterializationUnit::Interface(std::move(HeaderSymbolFlags),
1815 HeaderStartSymbol);
1816}
1817
1819 switch (TT.getArch()) {
1820 case Triple::aarch64:
1821 return {/* PageSize = */ 16 * 1024,
1822 /* CPUType = */ MachO::CPU_TYPE_ARM64,
1823 /* CPUSubType = */ MachO::CPU_SUBTYPE_ARM64_ALL};
1824 case Triple::x86_64:
1825 return {/* PageSize = */ 4 * 1024,
1826 /* CPUType = */ MachO::CPU_TYPE_X86_64,
1827 /* CPUSubType = */ MachO::CPU_SUBTYPE_X86_64_ALL};
1828 default:
1829 llvm_unreachable("Unrecognized architecture");
1830 }
1831}
1832
1833} // End namespace orc.
1834} // 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:1339
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition: Core.h:1382
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1393
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:1607
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition: Core.h:1388
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:1788
Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition: Core.cpp:1897
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition: Core.h:1403
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:1822
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition: Core.h:1805
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:1952
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