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