22#define DEBUG_TYPE "orc"
30template <
typename SPSSerializer,
typename... ArgTs>
32getArgDataBufferType(
const ArgTs &...Args) {
34 ArgData.
resize(SPSSerializer::size(Args...));
37 if (SPSSerializer::serialize(OB, Args...))
42std::unique_ptr<jitlink::LinkGraph> createPlatformGraph(
ELFNixPlatform &MOP,
45 return std::make_unique<jitlink::LinkGraph>(
46 std::move(Name), ES.getSymbolStringPool(), ES.getTargetTriple(),
51class ELFNixPlatformCompleteBootstrapMaterializationUnit
54 ELFNixPlatformCompleteBootstrapMaterializationUnit(
62 MOP(MOP), PlatformJDName(PlatformJDName),
63 CompleteBootstrapSymbol(std::move(CompleteBootstrapSymbol)),
64 DeferredAAsMap(std::move(DeferredAAs)),
65 ELFNixHeaderAddr(ELFNixHeaderAddr),
66 PlatformBootstrap(PlatformBootstrap),
67 PlatformShutdown(PlatformShutdown), RegisterJITDylib(RegisterJITDylib),
68 DeregisterJITDylib(DeregisterJITDylib) {}
71 return "ELFNixPlatformCompleteBootstrap";
74 void materialize(std::unique_ptr<MaterializationResponsibility> R)
override {
76 auto G = createPlatformGraph(MOP,
"<OrcRTCompleteBootstrap>");
77 auto &PlaceholderSection =
79 auto &PlaceholderBlock =
80 G->createZeroFillBlock(PlaceholderSection, 1,
ExecutorAddr(), 1, 0);
81 G->addDefinedSymbol(PlaceholderBlock, 0, *CompleteBootstrapSymbol, 1,
82 Linkage::Strong, Scope::Hidden,
false,
true);
85 G->allocActions().push_back(
87 PlatformBootstrap, ELFNixHeaderAddr)),
92 G->allocActions().push_back(
95 RegisterJITDylib, PlatformJDName, ELFNixHeaderAddr)),
97 DeregisterJITDylib, ELFNixHeaderAddr))});
100 for (
auto &[Fn, CallDatas] : DeferredAAsMap) {
101 for (
auto &CallData : CallDatas) {
102 G->allocActions().push_back(
130 createDSOHandleSectionInterface(ENP, DSOHandleSymbol)),
135 void materialize(std::unique_ptr<MaterializationResponsibility> R)
override {
139 jitlink::Edge::Kind EdgeKind;
141 switch (ES.getTargetTriple().getArch()) {
165 auto G = std::make_unique<jitlink::LinkGraph>(
166 "<DSOHandleMU>", ES.getSymbolStringPool(), ES.getTargetTriple(),
168 auto &DSOHandleSection =
170 auto &DSOHandleBlock =
G->createContentBlock(
171 DSOHandleSection, getDSOHandleContent(
G->getPointerSize()),
173 auto &DSOHandleSymbol =
G->addDefinedSymbol(
174 DSOHandleBlock, 0, *R->getInitializerSymbol(), DSOHandleBlock.getSize(),
176 DSOHandleBlock.addEdge(EdgeKind, 0, DSOHandleSymbol, 0);
194 static const char Content[8] = {0};
195 assert(PointerSize <=
sizeof Content);
196 return {Content, PointerSize};
207Expected<std::unique_ptr<ELFNixPlatform>>
210 std::unique_ptr<DefinitionGenerator> OrcRuntime,
211 std::optional<SymbolAliasMap> RuntimeAliases) {
213 auto &ES = ObjLinkingLayer.getExecutionSession();
216 if (!supportedTarget(ES.getTargetTriple()))
218 ES.getTargetTriple().str(),
221 auto &EPC = ES.getExecutorProcessControl();
224 if (!RuntimeAliases) {
226 if (!StandardRuntimeAliases)
227 return StandardRuntimeAliases.takeError();
228 RuntimeAliases = std::move(*StandardRuntimeAliases);
232 if (
auto Err = PlatformJD.define(
symbolAliases(std::move(*RuntimeAliases))))
233 return std::move(Err);
236 if (
auto Err = PlatformJD.define(
238 {EPC.getJITDispatchInfo().JITDispatchFunction,
240 {ES.intern(
"__orc_rt_jit_dispatch_ctx"),
241 {EPC.getJITDispatchInfo().JITDispatchContext,
243 return std::move(Err);
247 auto P = std::unique_ptr<ELFNixPlatform>(
new ELFNixPlatform(
248 ObjLinkingLayer, PlatformJD, std::move(OrcRuntime), Err));
250 return std::move(Err);
256 JITDylib &PlatformJD,
const char *OrcRuntimePath,
257 std::optional<SymbolAliasMap> RuntimeAliases) {
260 auto OrcRuntimeArchiveGenerator =
262 if (!OrcRuntimeArchiveGenerator)
263 return OrcRuntimeArchiveGenerator.takeError();
265 return Create(ObjLinkingLayer, PlatformJD,
266 std::move(*OrcRuntimeArchiveGenerator),
267 std::move(RuntimeAliases));
271 if (
auto Err = JD.
define(std::make_unique<DSOHandleMaterializationUnit>(
272 *
this, DSOHandleSymbol)))
275 return ES.lookup({&JD}, DSOHandleSymbol).takeError();
279 std::lock_guard<std::mutex> Lock(PlatformMutex);
280 auto I = JITDylibToHandleAddr.find(&JD);
281 if (
I != JITDylibToHandleAddr.end()) {
282 assert(HandleAddrToJITDylib.count(
I->second) &&
283 "HandleAddrToJITDylib missing entry");
284 HandleAddrToJITDylib.erase(
I->second);
285 JITDylibToHandleAddr.erase(
I);
298 RegisteredInitSymbols[&JD].add(InitSym,
301 dbgs() <<
"ELFNixPlatform: Registered init symbol " << *InitSym
302 <<
" for MU " << MU.
getName() <<
"\n";
312 ArrayRef<std::pair<const char *, const char *>> AL) {
313 for (
auto &KV : AL) {
314 auto AliasName = ES.
intern(KV.first);
315 assert(!Aliases.
count(AliasName) &&
"Duplicate symbol name in alias map");
316 Aliases[std::move(AliasName)] = {ES.
intern(KV.second),
333 static const std::pair<const char *, const char *> RequiredCXXAliases[] = {
334 {
"__cxa_atexit",
"__orc_rt_elfnix_cxa_atexit"},
335 {
"atexit",
"__orc_rt_elfnix_atexit"}};
342 static const std::pair<const char *, const char *>
343 StandardRuntimeUtilityAliases[] = {
344 {
"__orc_rt_run_program",
"__orc_rt_elfnix_run_program"},
345 {
"__orc_rt_jit_dlerror",
"__orc_rt_elfnix_jit_dlerror"},
346 {
"__orc_rt_jit_dlopen",
"__orc_rt_elfnix_jit_dlopen"},
347 {
"__orc_rt_jit_dlupdate",
"__orc_rt_elfnix_jit_dlupdate"},
348 {
"__orc_rt_jit_dlclose",
"__orc_rt_elfnix_jit_dlclose"},
349 {
"__orc_rt_jit_dlsym",
"__orc_rt_elfnix_jit_dlsym"},
350 {
"__orc_rt_log_error",
"__orc_rt_log_error_to_stderr"}};
353 StandardRuntimeUtilityAliases);
358 static const std::pair<const char *, const char *>
359 StandardLazyCompilationAliases[] = {
360 {
"__orc_rt_reenter",
"__orc_rt_sysv_reenter"}};
363 StandardLazyCompilationAliases);
366bool ELFNixPlatform::supportedTarget(
const Triple &TT) {
367 switch (TT.getArch()) {
381ELFNixPlatform::ELFNixPlatform(
383 std::unique_ptr<DefinitionGenerator> OrcRuntimeGenerator,
Error &Err)
384 : ES(ObjLinkingLayer.getExecutionSession()), PlatformJD(PlatformJD),
385 ObjLinkingLayer(ObjLinkingLayer),
386 DSOHandleSymbol(ES.intern(
"__dso_handle")) {
388 ObjLinkingLayer.
addPlugin(std::make_unique<ELFNixPlatformPlugin>(*
this));
390 PlatformJD.
addGenerator(std::move(OrcRuntimeGenerator));
404 if ((Err = ES.lookup(
407 {PlatformBootstrap.Name, PlatformShutdown.Name,
408 RegisterJITDylib.Name, DeregisterJITDylib.Name,
409 RegisterInitSections.Name, DeregisterInitSections.Name,
410 RegisterFiniSections.Name, DeregisterFiniSections.Name,
411 RegisterObjectSections.Name,
412 DeregisterObjectSections.Name, CreatePThreadKey.Name}))
418 std::unique_lock<std::mutex> Lock(BI.Mutex);
419 BI.CV.wait(Lock, [&]() {
return BI.ActiveGraphs == 0; });
424 auto BootstrapCompleteSymbol =
425 ES.intern(
"__orc_rt_elfnix_complete_bootstrap");
426 if ((Err = PlatformJD.define(
427 std::make_unique<ELFNixPlatformCompleteBootstrapMaterializationUnit>(
428 *
this, PlatformJD.getName(), BootstrapCompleteSymbol,
429 std::move(BI.DeferredRTFnMap), BI.ELFNixHeaderAddr,
430 PlatformBootstrap.Addr, PlatformShutdown.Addr,
431 RegisterJITDylib.Addr, DeregisterJITDylib.Addr))))
435 std::move(BootstrapCompleteSymbol))
440 if (
auto E2 = associateRuntimeSupportFunctions(PlatformJD)) {
446Error ELFNixPlatform::associateRuntimeSupportFunctions(
JITDylib &PlatformJD) {
449 using RecordInitializersSPSSig =
450 SPSExpected<SPSELFNixJITDylibDepInfoMap>(SPSExecutorAddr);
451 WFs[ES.intern(
"__orc_rt_elfnix_push_initializers_tag")] =
452 ES.wrapAsyncWithSPS<RecordInitializersSPSSig>(
453 this, &ELFNixPlatform::rt_recordInitializers);
455 using LookupSymbolSPSSig =
456 SPSExpected<SPSExecutorAddr>(SPSExecutorAddr,
SPSString);
457 WFs[ES.intern(
"__orc_rt_elfnix_symbol_lookup_tag")] =
458 ES.wrapAsyncWithSPS<LookupSymbolSPSSig>(
this,
459 &ELFNixPlatform::rt_lookupSymbol);
461 return ES.registerJITDispatchHandlers(PlatformJD, std::move(WFs));
464void ELFNixPlatform::pushInitializersLoop(
465 PushInitializersSendResultFn SendResult,
JITDylibSP JD) {
466 DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols;
467 DenseMap<JITDylib *, SmallVector<JITDylib *>> JDDepMap;
470 ES.runSessionLocked([&]() {
471 while (!Worklist.empty()) {
474 auto DepJD = Worklist.back();
483 auto &
DM = It->second;
486 if (KV.first == DepJD)
488 DM.push_back(KV.first);
489 Worklist.push_back(KV.first);
494 auto RISItr = RegisteredInitSymbols.find(DepJD);
495 if (RISItr != RegisteredInitSymbols.end()) {
496 NewInitSymbols[DepJD] = std::move(RISItr->second);
497 RegisteredInitSymbols.erase(RISItr);
504 if (NewInitSymbols.
empty()) {
510 DenseMap<JITDylib *, ExecutorAddr> HeaderAddrs;
513 std::lock_guard<std::mutex> Lock(PlatformMutex);
514 for (
auto &KV : JDDepMap) {
515 auto I = JITDylibToHandleAddr.find(KV.first);
516 if (
I != JITDylibToHandleAddr.end())
517 HeaderAddrs[KV.first] =
I->second;
523 DIM.reserve(JDDepMap.size());
524 for (
auto &KV : JDDepMap) {
525 auto HI = HeaderAddrs.
find(KV.first);
527 if (HI == HeaderAddrs.
end())
531 for (
auto &Dep : KV.second) {
532 auto HJ = HeaderAddrs.
find(Dep);
533 if (HJ != HeaderAddrs.
end())
534 DepInfo.push_back(HJ->second);
536 DIM.push_back(std::make_pair(
H, std::move(DepInfo)));
544 [
this, SendResult = std::move(SendResult), JD](
Error Err)
mutable {
546 SendResult(std::move(Err));
548 pushInitializersLoop(std::move(SendResult), JD);
550 ES, std::move(NewInitSymbols));
553void ELFNixPlatform::rt_recordInitializers(
554 PushInitializersSendResultFn SendResult,
ExecutorAddr JDHeaderAddr) {
557 std::lock_guard<std::mutex> Lock(PlatformMutex);
558 auto I = HandleAddrToJITDylib.find(JDHeaderAddr);
559 if (
I != HandleAddrToJITDylib.end())
564 dbgs() <<
"ELFNixPlatform::rt_recordInitializers(" << JDHeaderAddr <<
") ";
566 dbgs() <<
"pushing initializers for " << JD->
getName() <<
"\n";
568 dbgs() <<
"No JITDylib for header address.\n";
573 formatv(
"{0:x}", JDHeaderAddr),
578 pushInitializersLoop(std::move(SendResult), JD);
581void ELFNixPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult,
583 StringRef SymbolName) {
585 dbgs() <<
"ELFNixPlatform::rt_lookupSymbol(\"" << Handle <<
"\")\n";
588 JITDylib *JD =
nullptr;
591 std::lock_guard<std::mutex> Lock(PlatformMutex);
592 auto I = HandleAddrToJITDylib.find(Handle);
593 if (
I != HandleAddrToJITDylib.end())
598 LLVM_DEBUG(
dbgs() <<
" No JITDylib for handle " << Handle <<
"\n");
606 class RtLookupNotifyComplete {
608 RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult)
609 : SendResult(std::
move(SendResult)) {}
610 void operator()(Expected<SymbolMap>
Result) {
612 assert(
Result->size() == 1 &&
"Unexpected result map count");
613 SendResult(
Result->begin()->second.getAddress());
615 SendResult(
Result.takeError());
620 SendSymbolAddressFn SendResult;
629Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineStart(
630 jitlink::LinkGraph &
G) {
632 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
633 ++MP.Bootstrap.load()->ActiveGraphs;
637Error ELFNixPlatform::ELFNixPlatformPlugin::
638 bootstrapPipelineRecordRuntimeFunctions(jitlink::LinkGraph &
G) {
640 std::pair<StringRef, ExecutorAddr *> RuntimeSymbols[] = {
641 {*MP.DSOHandleSymbol, &MP.Bootstrap.load()->ELFNixHeaderAddr},
642 {*MP.PlatformBootstrap.Name, &MP.PlatformBootstrap.Addr},
643 {*MP.PlatformShutdown.Name, &MP.PlatformShutdown.Addr},
644 {*MP.RegisterJITDylib.Name, &MP.RegisterJITDylib.Addr},
645 {*MP.DeregisterJITDylib.Name, &MP.DeregisterJITDylib.Addr},
646 {*MP.RegisterObjectSections.Name, &MP.RegisterObjectSections.Addr},
647 {*MP.DeregisterObjectSections.Name, &MP.DeregisterObjectSections.Addr},
648 {*MP.RegisterInitSections.Name, &MP.RegisterInitSections.Addr},
649 {*MP.DeregisterInitSections.Name, &MP.DeregisterInitSections.Addr},
650 {*MP.RegisterFiniSections.Name, &MP.RegisterFiniSections.Addr},
651 {*MP.DeregisterFiniSections.Name, &MP.DeregisterFiniSections.Addr},
652 {*MP.CreatePThreadKey.Name, &MP.CreatePThreadKey.Addr}};
654 bool RegisterELFNixHeader =
false;
656 for (
auto *Sym :
G.defined_symbols()) {
657 for (
auto &RTSym : RuntimeSymbols) {
658 if (Sym->hasName() && *Sym->getName() == RTSym.first) {
661 "Duplicate " + RTSym.first +
662 " detected during ELFNixPlatform bootstrap",
665 if (*Sym->getName() == *MP.DSOHandleSymbol)
666 RegisterELFNixHeader =
true;
668 *RTSym.second = Sym->getAddress();
673 if (RegisterELFNixHeader) {
676 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
677 MP.JITDylibToHandleAddr[&MP.PlatformJD] =
678 MP.Bootstrap.load()->ELFNixHeaderAddr;
679 MP.HandleAddrToJITDylib[MP.Bootstrap.load()->ELFNixHeaderAddr] =
686Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineEnd(
687 jitlink::LinkGraph &
G) {
688 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
689 assert(MP.Bootstrap &&
"DeferredAAs reset before bootstrap completed");
690 --MP.Bootstrap.load()->ActiveGraphs;
693 if (MP.Bootstrap.load()->ActiveGraphs == 0)
694 MP.Bootstrap.load()->CV.notify_all();
698Error ELFNixPlatform::registerPerObjectSections(
699 jitlink::LinkGraph &
G,
const ELFPerObjectSectionsToRegister &POSR,
700 bool IsBootstrapping) {
701 using SPSRegisterPerObjSectionsArgs =
702 SPSArgList<SPSELFPerObjectSectionsToRegister>;
705 Bootstrap.load()->addArgumentsToRTFnMap(
706 &RegisterObjectSections, &DeregisterObjectSections,
707 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR),
708 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR));
712 G.allocActions().push_back(
714 RegisterObjectSections.Addr, POSR)),
716 DeregisterObjectSections.Addr, POSR))});
721Expected<uint64_t> ELFNixPlatform::createPThreadKey() {
722 if (!CreatePThreadKey.Addr)
724 "Attempting to create pthread key in target, but runtime support has "
725 "not been loaded yet",
728 Expected<uint64_t>
Result(0);
729 if (
auto Err = ES.callSPSWrapper<SPSExpected<uint64_t>(
void)>(
730 CreatePThreadKey.Addr,
Result))
731 return std::move(Err);
735void ELFNixPlatform::ELFNixPlatformPlugin::modifyPassConfig(
736 MaterializationResponsibility &MR, jitlink::LinkGraph &LG,
737 jitlink::PassConfiguration &Config) {
738 using namespace jitlink;
740 bool InBootstrapPhase =
744 if (InBootstrapPhase) {
746 [
this](LinkGraph &
G) {
return bootstrapPipelineStart(
G); });
748 return bootstrapPipelineRecordRuntimeFunctions(
G);
755 if (InitSymbol == MP.DSOHandleSymbol && !InBootstrapPhase) {
756 addDSOHandleSupportPasses(MR, Config);
764 [
this, &MR](jitlink::LinkGraph &
G) ->
Error {
765 if (
auto Err = preserveInitSections(
G, MR))
772 addEHAndTLVSupportPasses(MR, Config, InBootstrapPhase);
776 InBootstrapPhase](jitlink::LinkGraph &
G) {
777 return registerInitSections(G, JD, InBootstrapPhase);
782 InBootstrapPhase](jitlink::LinkGraph &
G) {
783 return registerFiniSections(G, JD, InBootstrapPhase);
788 if (InBootstrapPhase)
790 [
this](LinkGraph &
G) {
return bootstrapPipelineEnd(
G); });
793void ELFNixPlatform::ELFNixPlatformPlugin::addDSOHandleSupportPasses(
794 MaterializationResponsibility &MR, jitlink::PassConfiguration &Config) {
797 jitlink::LinkGraph &
G) ->
Error {
798 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
799 return Sym->getName() == MP.DSOHandleSymbol;
801 assert(
I !=
G.defined_symbols().end() &&
"Missing DSO handle symbol");
803 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
804 auto HandleAddr = (*I)->getAddress();
805 MP.HandleAddrToJITDylib[HandleAddr] = &JD;
806 MP.JITDylibToHandleAddr[&JD] = HandleAddr;
808 G.allocActions().push_back(
810 SPSArgList<SPSString, SPSExecutorAddr>>(
811 MP.RegisterJITDylib.Addr, JD.getName(), HandleAddr)),
813 MP.DeregisterJITDylib.Addr, HandleAddr))});
819void ELFNixPlatform::ELFNixPlatformPlugin::addEHAndTLVSupportPasses(
821 bool IsBootstrapping) {
830 return fixTLVSectionsAndEdges(G, JD);
836 jitlink::LinkGraph &
G) ->
Error {
837 ELFPerObjectSectionsToRegister POSR;
840 jitlink::SectionRange
R(*EHFrameSection);
847 jitlink::Section *ThreadDataSection =
855 if (ThreadDataSection)
856 G.mergeSections(*ThreadDataSection, *ThreadBSSSection);
858 ThreadDataSection = ThreadBSSSection;
863 if (ThreadDataSection) {
864 jitlink::SectionRange
R(*ThreadDataSection);
870 if (
auto Err = MP.registerPerObjectSections(
G, POSR, IsBootstrapping))
878Error ELFNixPlatform::ELFNixPlatformPlugin::preserveInitSections(
879 jitlink::LinkGraph &
G, MaterializationResponsibility &MR) {
883 jitlink::Symbol *InitSym =
nullptr;
885 for (
auto &InitSection :
G.sections()) {
894 auto &
B = **InitSection.blocks().begin();
895 InitSym = &
G.addDefinedSymbol(
901 for (
auto *
B : InitSection.blocks()) {
905 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
911 for (
auto &FiniSection :
G.sections()) {
919 auto &
B = **FiniSection.blocks().begin();
920 InitSym = &
G.addDefinedSymbol(
926 for (
auto *
B : FiniSection.blocks()) {
930 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
939Error ELFNixPlatform::ELFNixPlatformPlugin::registerInitSections(
940 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
945 for (
auto &Sec :
G.sections())
952 auto getInitSectionInfo =
953 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
954 StringRef
Name = Sec->getName();
955 if (
Name.starts_with(
".init_array")) {
956 StringRef PrioStr =
Name;
960 return {0, Prio, HasPrio};
962 if (
Name.starts_with(
".init"))
963 return {1, 0,
false};
964 if (
Name.starts_with(
".ctors")) {
965 StringRef PrioStr =
Name;
969 return {2, Prio, HasPrio};
971 return {3, 0,
false};
980 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
981 auto [LType, LPrio, LHasPrio] = getInitSectionInfo(
LHS);
982 auto [RType, RPrio, RHasPrio] = getInitSectionInfo(
RHS);
985 return LType < RType;
991 if (LHasPrio && RHasPrio)
992 return LPrio < RPrio;
997 }
else if (LType == 2) {
1000 if (LHasPrio && RHasPrio)
1001 return LPrio > RPrio;
1010 for (
auto &Sec : OrderedInitSections)
1011 ELFNixPlatformSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1015 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" init sections:\n";
1016 for (
auto &Sec :
G.sections()) {
1017 jitlink::SectionRange
R(Sec);
1018 dbgs() <<
" " << Sec.getName() <<
": " <<
R.getRange() <<
"\n";
1022 ExecutorAddr HeaderAddr;
1024 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1025 auto I = MP.JITDylibToHandleAddr.find(&JD);
1026 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1027 assert(
I->second &&
"Null header registered for JD");
1028 HeaderAddr =
I->second;
1031 using SPSRegisterInitSectionsArgs =
1032 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1035 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1036 &MP.RegisterInitSections, &MP.DeregisterInitSections,
1037 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1038 ELFNixPlatformSecs),
1039 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1040 ELFNixPlatformSecs));
1044 G.allocActions().push_back(
1046 MP.RegisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs)),
1048 MP.DeregisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs))});
1053Error ELFNixPlatform::ELFNixPlatformPlugin::registerFiniSections(
1054 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
1059 for (
auto &Sec :
G.sections())
1066 auto getFiniSectionInfo =
1067 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
1068 StringRef
Name = Sec->getName();
1069 if (
Name.starts_with(
".dtors")) {
1070 StringRef PrioStr =
Name;
1074 return {0, Prio, HasPrio};
1076 if (
Name.starts_with(
".fini"))
1077 if (!
Name.starts_with(
".fini_array"))
1078 return {1, 0,
false};
1079 if (
Name.starts_with(
".fini_array")) {
1080 StringRef PrioStr =
Name;
1084 return {2, Prio, HasPrio};
1086 return {3, 0,
false};
1094 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
1095 auto [LType, LPrio, LHasPrio] = getFiniSectionInfo(
LHS);
1096 auto [RType, RPrio, RHasPrio] = getFiniSectionInfo(
RHS);
1099 return LType < RType;
1105 if (LHasPrio && RHasPrio)
1106 return LPrio < RPrio;
1111 }
else if (LType == 2) {
1114 if (LHasPrio && RHasPrio)
1115 return LPrio > RPrio;
1124 for (
auto *Sec : OrderedFiniSections)
1125 ELFNixFiniSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1127 if (ELFNixFiniSecs.
empty())
1132 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" fini sections:\n";
1133 for (
auto *Sec : OrderedFiniSections) {
1134 jitlink::SectionRange
R(*Sec);
1135 dbgs() <<
" " << Sec->getName() <<
": " <<
R.getRange() <<
"\n";
1139 ExecutorAddr HeaderAddr;
1141 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1142 auto I = MP.JITDylibToHandleAddr.find(&JD);
1143 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1144 assert(
I->second &&
"Null header registered for JD");
1145 HeaderAddr =
I->second;
1148 using SPSRegisterFiniSectionsArgs =
1149 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1152 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1153 &MP.RegisterFiniSections, &MP.DeregisterFiniSections,
1154 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1156 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1161 G.allocActions().push_back(
1163 MP.RegisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs)),
1165 MP.DeregisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs))});
1170Error ELFNixPlatform::ELFNixPlatformPlugin::fixTLVSectionsAndEdges(
1171 jitlink::LinkGraph &
G, JITDylib &JD) {
1172 auto TLSGetAddrSymbolName =
G.intern(
"__tls_get_addr");
1173 auto TLSDescResolveSymbolName =
G.intern(
"__tlsdesc_resolver");
1174 auto TLSGetOffsetSymbolName =
G.intern(
"__tls_get_offset");
1175 for (
auto *Sym :
G.external_symbols()) {
1176 if (Sym->getName() == TLSGetAddrSymbolName) {
1178 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_addr");
1179 Sym->setName(std::move(TLSGetAddr));
1180 }
else if (Sym->getName() == TLSDescResolveSymbolName) {
1182 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tlsdesc_resolver");
1183 Sym->setName(std::move(TLSGetAddr));
1184 }
else if (Sym->getName() == TLSGetOffsetSymbolName) {
1186 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_offset");
1187 Sym->setName(std::move(TLSGetAddr));
1191 auto *TLSInfoEntrySection =
G.findSectionByName(
"$__TLSINFO");
1193 if (TLSInfoEntrySection) {
1194 std::optional<uint64_t>
Key;
1196 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1197 auto I = MP.JITDylibToPThreadKey.find(&JD);
1198 if (
I != MP.JITDylibToPThreadKey.end())
1202 if (
auto KeyOrErr = MP.createPThreadKey())
1205 return KeyOrErr.takeError();
1208 uint64_t PlatformKeyBits =
1211 for (
auto *
B : TLSInfoEntrySection->blocks()) {
1214 assert(
B->getSize() == (
G.getPointerSize() * 2) &&
1215 "TLS descriptor must be 2 words length");
1216 auto TLSInfoEntryContent =
B->getMutableContent(
G);
1217 memcpy(TLSInfoEntryContent.data(), &PlatformKeyBits,
G.getPointerSize());
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
static StringRef getName(Value *V)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Helper for Errors used as out-parameters.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
StringRef - Represent a constant reference to a string, i.e.
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Manages the enabling and disabling of subtarget specific features.
Triple - Helper class for working with autoconf configuration names.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
void addEdge(Edge::Kind K, Edge::OffsetT Offset, Symbol &Target, Edge::AddendT Addend)
Add an edge to this block.
const std::string & getName() const
Get the name for this JITLinkDylib.
Block & getBlock()
Return the Block for this Symbol (Symbol must be defined).
An ExecutionSession represents a running JIT program.
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Represents an address in the executor process.
Represents a JIT'd dynamic library.
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
LinkGraphLinkingLayer & addPlugin(std::shared_ptr< Plugin > P)
Add a plugin.
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
virtual StringRef getName() const =0
Return the name of this materialization unit.
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization symbol for this MaterializationUnit (if any).
An ObjectLayer implementation built on JITLink.
void emit(std::unique_ptr< MaterializationResponsibility > R, std::unique_ptr< MemoryBuffer > O) override
Emit an object file.
API to remove / transfer ownership of JIT resources.
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName, VisitMembersFunction VisitMembers=VisitMembersFunction(), GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibraryDefinitionGenerator from the given path.
Pointer to a pooled string representing a symbol name.
A utility class for serializing to a blob from a variadic list.
Output char buffer with overflow check.
Represents a serialized wrapper function call.
SmallVector< char, 24 > ArgDataBufferType
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.
@ Pointer64
A plain 64-bit pointer value relocation.
@ Pointer64
A plain 64-bit pointer value relocation.
@ Pointer64
A plain 64-bit pointer value relocation.
@ Pointer64
A plain 64-bit pointer value relocation.
LLVM_ABI const char * getGenericEdgeKindName(Edge::Kind K)
Returns the string name of the given generic edge kind, or "unknown" otherwise.
SPSSequence< char > SPSString
SPS tag type for strings, which are equivalent to sequences of chars.
LLVM_ABI StringRef ELFThreadBSSSectionName
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...
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
IntrusiveRefCntPtr< JITDylib > JITDylibSP
std::vector< std::pair< ExecutorAddr, ELFNixJITDylibDepInfo > > ELFNixJITDylibDepInfoMap
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
std::vector< ExecutorAddr > ELFNixJITDylibDepInfo
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
LLVM_ABI StringRef ELFEHFrameSectionName
@ MatchExportedSymbolsOnly
static void addAliases(ExecutionSession &ES, SymbolAliasMap &Aliases, ArrayRef< std::pair< const char *, const char * > > AL)
std::unordered_map< std::pair< RuntimeFunction *, RuntimeFunction * >, SmallVector< std::pair< shared::WrapperFunctionCall::ArgDataBufferType, shared::WrapperFunctionCall::ArgDataBufferType > >, FunctionPairKeyHash, FunctionPairKeyEqual > DeferredRuntimeFnMap
LLVM_ABI bool isELFFinalizerSection(StringRef SecName)
LLVM_ABI StringRef ELFThreadDataSectionName
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
@ Ready
Emitted to memory, but waiting on transitive dependencies.
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
LLVM_ABI bool isELFInitializerSection(StringRef SecName)
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
value_type byte_swap(value_type value, endianness endian)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
LinkGraphPassList PostAllocationPasses
Post-allocation passes.
LinkGraphPassList PostFixupPasses
Post-fixup passes.
LinkGraphPassList PostPrunePasses
Post-prune passes.
LinkGraphPassList PrePrunePasses
Pre-prune passes.
ExecutorAddrRange EHFrameSection
ExecutorAddrRange ThreadDataSection