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