23#define DEBUG_TYPE "orc"
31template <
typename SPSSerializer,
typename... ArgTs>
33getArgDataBufferType(
const ArgTs &...Args) {
35 ArgData.
resize(SPSSerializer::size(Args...));
38 if (SPSSerializer::serialize(OB, Args...))
43std::unique_ptr<jitlink::LinkGraph> createPlatformGraph(
ELFNixPlatform &MOP,
46 return std::make_unique<jitlink::LinkGraph>(
47 std::move(Name), ES.getSymbolStringPool(), ES.getTargetTriple(),
52class ELFNixPlatformCompleteBootstrapMaterializationUnit
55 ELFNixPlatformCompleteBootstrapMaterializationUnit(
63 MOP(MOP), PlatformJDName(PlatformJDName),
64 CompleteBootstrapSymbol(std::move(CompleteBootstrapSymbol)),
65 DeferredAAsMap(std::move(DeferredAAs)),
66 ELFNixHeaderAddr(ELFNixHeaderAddr),
67 PlatformBootstrap(PlatformBootstrap),
68 PlatformShutdown(PlatformShutdown), RegisterJITDylib(RegisterJITDylib),
69 DeregisterJITDylib(DeregisterJITDylib) {}
72 return "ELFNixPlatformCompleteBootstrap";
75 void materialize(std::unique_ptr<MaterializationResponsibility> R)
override {
77 auto G = createPlatformGraph(MOP,
"<OrcRTCompleteBootstrap>");
78 auto &PlaceholderSection =
80 auto &PlaceholderBlock =
81 G->createZeroFillBlock(PlaceholderSection, 1,
ExecutorAddr(), 1, 0);
82 G->addDefinedSymbol(PlaceholderBlock, 0, *CompleteBootstrapSymbol, 1,
83 Linkage::Strong, Scope::Hidden,
false,
true);
86 G->allocActions().push_back(
88 PlatformBootstrap, ELFNixHeaderAddr)),
93 G->allocActions().push_back(
96 RegisterJITDylib, PlatformJDName, ELFNixHeaderAddr)),
98 DeregisterJITDylib, ELFNixHeaderAddr))});
101 for (
auto &[Fn, CallDatas] : DeferredAAsMap) {
102 for (
auto &CallData : CallDatas) {
103 G->allocActions().push_back(
131 createDSOHandleSectionInterface(ENP, DSOHandleSymbol)),
136 void materialize(std::unique_ptr<MaterializationResponsibility> R)
override {
140 jitlink::Edge::Kind EdgeKind;
142 switch (ES.getTargetTriple().getArch()) {
166 auto G = std::make_unique<jitlink::LinkGraph>(
167 "<DSOHandleMU>", ES.getSymbolStringPool(), ES.getTargetTriple(),
169 auto &DSOHandleSection =
171 auto &DSOHandleBlock =
G->createContentBlock(
172 DSOHandleSection, getDSOHandleContent(
G->getPointerSize()),
174 auto &DSOHandleSymbol =
G->addDefinedSymbol(
175 DSOHandleBlock, 0, *R->getInitializerSymbol(), DSOHandleBlock.getSize(),
177 DSOHandleBlock.addEdge(EdgeKind, 0, DSOHandleSymbol, 0);
195 static const char Content[8] = {0};
196 assert(PointerSize <=
sizeof Content);
197 return {Content, PointerSize};
208Expected<std::unique_ptr<ELFNixPlatform>>
211 std::unique_ptr<DefinitionGenerator> OrcRuntime,
212 std::optional<SymbolAliasMap> RuntimeAliases) {
214 auto &ES = ObjLinkingLayer.getExecutionSession();
217 if (!supportedTarget(ES.getTargetTriple()))
219 ES.getTargetTriple().str(),
223 if (!RuntimeAliases) {
225 if (!StandardRuntimeAliases)
226 return StandardRuntimeAliases.takeError();
227 RuntimeAliases = std::move(*StandardRuntimeAliases);
231 if (
auto Err = PlatformJD.define(
symbolAliases(std::move(*RuntimeAliases))))
232 return std::move(Err);
238 ES.getBootstrapJITDylib(),
239 {{Mangle(rt::DispatchName), Mangle(rt::DispatchCtxName)}});
241 return Exports.takeError();
243 PlatformJD.define(
reexports(ES.getBootstrapJITDylib(), *Exports)))
250 ObjLinkingLayer, PlatformJD, std::move(OrcRuntime), Err));
252 return std::move(Err);
258 JITDylib &PlatformJD,
const char *OrcRuntimePath,
259 std::optional<SymbolAliasMap> RuntimeAliases) {
262 auto OrcRuntimeArchiveGenerator =
264 if (!OrcRuntimeArchiveGenerator)
265 return OrcRuntimeArchiveGenerator.takeError();
267 return Create(ObjLinkingLayer, PlatformJD,
268 std::move(*OrcRuntimeArchiveGenerator),
269 std::move(RuntimeAliases));
273 if (
auto Err = JD.
define(std::make_unique<DSOHandleMaterializationUnit>(
274 *
this, DSOHandleSymbol)))
277 return ES.lookup({&JD}, DSOHandleSymbol).takeError();
281 std::lock_guard<std::mutex> Lock(PlatformMutex);
282 auto I = JITDylibToHandleAddr.find(&JD);
283 if (
I != JITDylibToHandleAddr.end()) {
284 assert(HandleAddrToJITDylib.count(
I->second) &&
285 "HandleAddrToJITDylib missing entry");
286 HandleAddrToJITDylib.erase(
I->second);
287 JITDylibToHandleAddr.erase(
I);
300 RegisteredInitSymbols[&JD].add(InitSym,
303 dbgs() <<
"ELFNixPlatform: Registered init symbol " << *InitSym
304 <<
" for MU " << MU.
getName() <<
"\n";
314 ArrayRef<std::pair<const char *, const char *>> AL) {
315 for (
auto &KV : AL) {
316 auto AliasName = ES.
intern(KV.first);
317 assert(!Aliases.
count(AliasName) &&
"Duplicate symbol name in alias map");
318 Aliases[std::move(AliasName)] = {ES.
intern(KV.second),
335 static const std::pair<const char *, const char *> RequiredCXXAliases[] = {
336 {
"__cxa_atexit",
"__orc_rt_elfnix_cxa_atexit"},
337 {
"atexit",
"__orc_rt_elfnix_atexit"}};
344 static const std::pair<const char *, const char *>
345 StandardRuntimeUtilityAliases[] = {
346 {
"__orc_rt_run_program",
"__orc_rt_elfnix_run_program"},
347 {
"__orc_rt_jit_dlerror",
"__orc_rt_elfnix_jit_dlerror"},
348 {
"__orc_rt_jit_dlopen",
"__orc_rt_elfnix_jit_dlopen"},
349 {
"__orc_rt_jit_dlupdate",
"__orc_rt_elfnix_jit_dlupdate"},
350 {
"__orc_rt_jit_dlclose",
"__orc_rt_elfnix_jit_dlclose"},
351 {
"__orc_rt_jit_dlsym",
"__orc_rt_elfnix_jit_dlsym"},
352 {
"__orc_rt_log_error",
"__orc_rt_log_error_to_stderr"}};
355 StandardRuntimeUtilityAliases);
360 static const std::pair<const char *, const char *>
361 StandardLazyCompilationAliases[] = {
362 {
"__orc_rt_reenter",
"__orc_rt_sysv_reenter"}};
365 StandardLazyCompilationAliases);
368bool ELFNixPlatform::supportedTarget(
const Triple &TT) {
369 switch (TT.getArch()) {
383ELFNixPlatform::ELFNixPlatform(
385 std::unique_ptr<DefinitionGenerator> OrcRuntimeGenerator,
Error &Err)
386 : ES(ObjLinkingLayer.getExecutionSession()), PlatformJD(PlatformJD),
387 ObjLinkingLayer(ObjLinkingLayer),
388 DSOHandleSymbol(ES.intern(
"__dso_handle")) {
390 ObjLinkingLayer.
addPlugin(std::make_unique<ELFNixPlatformPlugin>(*
this));
392 PlatformJD.
addGenerator(std::move(OrcRuntimeGenerator));
406 if ((Err = ES.lookup(
409 {PlatformBootstrap.Name, PlatformShutdown.Name,
410 RegisterJITDylib.Name, DeregisterJITDylib.Name,
411 RegisterInitSections.Name, DeregisterInitSections.Name,
412 RegisterFiniSections.Name, DeregisterFiniSections.Name,
413 RegisterObjectSections.Name,
414 DeregisterObjectSections.Name, CreatePThreadKey.Name}))
420 std::unique_lock<std::mutex> Lock(BI.Mutex);
421 BI.CV.wait(Lock, [&]() {
return BI.ActiveGraphs == 0; });
426 auto BootstrapCompleteSymbol =
427 ES.intern(
"__orc_rt_elfnix_complete_bootstrap");
428 if ((Err = PlatformJD.define(
429 std::make_unique<ELFNixPlatformCompleteBootstrapMaterializationUnit>(
430 *
this, PlatformJD.getName(), BootstrapCompleteSymbol,
431 std::move(BI.DeferredRTFnMap), BI.ELFNixHeaderAddr,
432 PlatformBootstrap.Addr, PlatformShutdown.Addr,
433 RegisterJITDylib.Addr, DeregisterJITDylib.Addr))))
437 std::move(BootstrapCompleteSymbol))
442 if (
auto E2 = associateRuntimeSupportFunctions(PlatformJD)) {
448Error ELFNixPlatform::associateRuntimeSupportFunctions(
JITDylib &PlatformJD) {
451 using RecordInitializersSPSSig =
452 SPSExpected<SPSELFNixJITDylibDepInfoMap>(SPSExecutorAddr);
453 WFs[ES.intern(
"__orc_rt_elfnix_push_initializers_tag")] =
454 ES.wrapAsyncWithSPS<RecordInitializersSPSSig>(
455 this, &ELFNixPlatform::rt_recordInitializers);
457 using LookupSymbolSPSSig =
458 SPSExpected<SPSExecutorAddr>(SPSExecutorAddr,
SPSString);
459 WFs[ES.intern(
"__orc_rt_elfnix_symbol_lookup_tag")] =
460 ES.wrapAsyncWithSPS<LookupSymbolSPSSig>(
this,
461 &ELFNixPlatform::rt_lookupSymbol);
463 return ES.registerJITDispatchHandlers(PlatformJD, std::move(WFs));
466void ELFNixPlatform::pushInitializersLoop(
467 PushInitializersSendResultFn SendResult,
JITDylibSP JD) {
468 DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols;
469 DenseMap<JITDylib *, SmallVector<JITDylib *>> JDDepMap;
472 ES.runSessionLocked([&]() {
473 while (!Worklist.empty()) {
476 auto DepJD = Worklist.back();
485 auto &
DM = It->second;
488 if (KV.first == DepJD)
490 DM.push_back(KV.first);
491 Worklist.push_back(KV.first);
496 auto RISItr = RegisteredInitSymbols.find(DepJD);
497 if (RISItr != RegisteredInitSymbols.end()) {
498 NewInitSymbols[DepJD] = std::move(RISItr->second);
499 RegisteredInitSymbols.erase(RISItr);
506 if (NewInitSymbols.
empty()) {
512 DenseMap<JITDylib *, ExecutorAddr> HeaderAddrs;
515 std::lock_guard<std::mutex> Lock(PlatformMutex);
516 for (
auto &KV : JDDepMap) {
517 auto I = JITDylibToHandleAddr.find(KV.first);
518 if (
I != JITDylibToHandleAddr.end())
519 HeaderAddrs[KV.first] =
I->second;
525 DIM.reserve(JDDepMap.size());
526 for (
auto &KV : JDDepMap) {
527 auto HI = HeaderAddrs.
find(KV.first);
529 if (HI == HeaderAddrs.
end())
533 for (
auto &Dep : KV.second) {
534 auto HJ = HeaderAddrs.
find(Dep);
535 if (HJ != HeaderAddrs.
end())
536 DepInfo.push_back(HJ->second);
538 DIM.push_back(std::make_pair(
H, std::move(DepInfo)));
546 [
this, SendResult = std::move(SendResult), JD](
Error Err)
mutable {
548 SendResult(std::move(Err));
550 pushInitializersLoop(std::move(SendResult), JD);
552 ES, std::move(NewInitSymbols));
555void ELFNixPlatform::rt_recordInitializers(
556 PushInitializersSendResultFn SendResult,
ExecutorAddr JDHeaderAddr) {
559 std::lock_guard<std::mutex> Lock(PlatformMutex);
560 auto I = HandleAddrToJITDylib.find(JDHeaderAddr);
561 if (
I != HandleAddrToJITDylib.end())
566 dbgs() <<
"ELFNixPlatform::rt_recordInitializers(" << JDHeaderAddr <<
") ";
568 dbgs() <<
"pushing initializers for " << JD->
getName() <<
"\n";
570 dbgs() <<
"No JITDylib for header address.\n";
575 formatv(
"{0:x}", JDHeaderAddr),
580 pushInitializersLoop(std::move(SendResult), JD);
583void ELFNixPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult,
585 StringRef SymbolName) {
587 dbgs() <<
"ELFNixPlatform::rt_lookupSymbol(\"" << Handle <<
"\")\n";
590 JITDylib *JD =
nullptr;
593 std::lock_guard<std::mutex> Lock(PlatformMutex);
594 auto I = HandleAddrToJITDylib.find(Handle);
595 if (
I != HandleAddrToJITDylib.end())
600 LLVM_DEBUG(
dbgs() <<
" No JITDylib for handle " << Handle <<
"\n");
608 class RtLookupNotifyComplete {
610 RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult)
611 : SendResult(std::
move(SendResult)) {}
612 void operator()(Expected<SymbolMap>
Result) {
614 assert(
Result->size() == 1 &&
"Unexpected result map count");
615 SendResult(
Result->begin()->second.getAddress());
617 SendResult(
Result.takeError());
622 SendSymbolAddressFn SendResult;
631Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineStart(
632 jitlink::LinkGraph &
G) {
634 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
635 ++MP.Bootstrap.load()->ActiveGraphs;
639Error ELFNixPlatform::ELFNixPlatformPlugin::
640 bootstrapPipelineRecordRuntimeFunctions(jitlink::LinkGraph &
G) {
642 std::pair<StringRef, ExecutorAddr *> RuntimeSymbols[] = {
643 {*MP.DSOHandleSymbol, &MP.Bootstrap.load()->ELFNixHeaderAddr},
644 {*MP.PlatformBootstrap.Name, &MP.PlatformBootstrap.Addr},
645 {*MP.PlatformShutdown.Name, &MP.PlatformShutdown.Addr},
646 {*MP.RegisterJITDylib.Name, &MP.RegisterJITDylib.Addr},
647 {*MP.DeregisterJITDylib.Name, &MP.DeregisterJITDylib.Addr},
648 {*MP.RegisterObjectSections.Name, &MP.RegisterObjectSections.Addr},
649 {*MP.DeregisterObjectSections.Name, &MP.DeregisterObjectSections.Addr},
650 {*MP.RegisterInitSections.Name, &MP.RegisterInitSections.Addr},
651 {*MP.DeregisterInitSections.Name, &MP.DeregisterInitSections.Addr},
652 {*MP.RegisterFiniSections.Name, &MP.RegisterFiniSections.Addr},
653 {*MP.DeregisterFiniSections.Name, &MP.DeregisterFiniSections.Addr},
654 {*MP.CreatePThreadKey.Name, &MP.CreatePThreadKey.Addr}};
656 bool RegisterELFNixHeader =
false;
658 for (
auto *Sym :
G.defined_symbols()) {
659 for (
auto &RTSym : RuntimeSymbols) {
660 if (Sym->hasName() && *Sym->getName() == RTSym.first) {
663 "Duplicate " + RTSym.first +
664 " detected during ELFNixPlatform bootstrap",
667 if (*Sym->getName() == *MP.DSOHandleSymbol)
668 RegisterELFNixHeader =
true;
670 *RTSym.second = Sym->getAddress();
675 if (RegisterELFNixHeader) {
678 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
679 MP.JITDylibToHandleAddr[&MP.PlatformJD] =
680 MP.Bootstrap.load()->ELFNixHeaderAddr;
681 MP.HandleAddrToJITDylib[MP.Bootstrap.load()->ELFNixHeaderAddr] =
688Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineEnd(
689 jitlink::LinkGraph &
G) {
690 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
691 assert(MP.Bootstrap &&
"DeferredAAs reset before bootstrap completed");
692 --MP.Bootstrap.load()->ActiveGraphs;
695 if (MP.Bootstrap.load()->ActiveGraphs == 0)
696 MP.Bootstrap.load()->CV.notify_all();
700Error ELFNixPlatform::registerPerObjectSections(
701 jitlink::LinkGraph &
G,
const ELFPerObjectSectionsToRegister &POSR,
702 bool IsBootstrapping) {
703 using SPSRegisterPerObjSectionsArgs =
704 SPSArgList<SPSELFPerObjectSectionsToRegister>;
707 Bootstrap.load()->addArgumentsToRTFnMap(
708 &RegisterObjectSections, &DeregisterObjectSections,
709 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR),
710 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR));
714 G.allocActions().push_back(
716 RegisterObjectSections.Addr, POSR)),
718 DeregisterObjectSections.Addr, POSR))});
723Expected<uint64_t> ELFNixPlatform::createPThreadKey() {
724 if (!CreatePThreadKey.Addr)
726 "Attempting to create pthread key in target, but runtime support has "
727 "not been loaded yet",
730 Expected<uint64_t>
Result(0);
731 if (
auto Err = ES.callSPSWrapper<SPSExpected<uint64_t>(
void)>(
732 CreatePThreadKey.Addr,
Result))
733 return std::move(Err);
737void ELFNixPlatform::ELFNixPlatformPlugin::modifyPassConfig(
738 MaterializationResponsibility &MR, jitlink::LinkGraph &LG,
739 jitlink::PassConfiguration &Config) {
740 using namespace jitlink;
742 bool InBootstrapPhase =
746 if (InBootstrapPhase) {
748 [
this](LinkGraph &
G) {
return bootstrapPipelineStart(
G); });
750 return bootstrapPipelineRecordRuntimeFunctions(
G);
757 if (InitSymbol == MP.DSOHandleSymbol && !InBootstrapPhase) {
758 addDSOHandleSupportPasses(MR, Config);
766 [
this, &MR](jitlink::LinkGraph &
G) ->
Error {
767 if (
auto Err = preserveInitSections(
G, MR))
774 addEHAndTLVSupportPasses(MR, Config, InBootstrapPhase);
778 InBootstrapPhase](jitlink::LinkGraph &
G) {
779 return registerInitSections(G, JD, InBootstrapPhase);
784 InBootstrapPhase](jitlink::LinkGraph &
G) {
785 return registerFiniSections(G, JD, InBootstrapPhase);
790 if (InBootstrapPhase)
792 [
this](LinkGraph &
G) {
return bootstrapPipelineEnd(
G); });
795void ELFNixPlatform::ELFNixPlatformPlugin::addDSOHandleSupportPasses(
796 MaterializationResponsibility &MR, jitlink::PassConfiguration &Config) {
799 jitlink::LinkGraph &
G) ->
Error {
800 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
801 return Sym->getName() == MP.DSOHandleSymbol;
803 assert(
I !=
G.defined_symbols().end() &&
"Missing DSO handle symbol");
805 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
806 auto HandleAddr = (*I)->getAddress();
807 MP.HandleAddrToJITDylib[HandleAddr] = &JD;
808 MP.JITDylibToHandleAddr[&JD] = HandleAddr;
810 G.allocActions().push_back(
812 SPSArgList<SPSString, SPSExecutorAddr>>(
813 MP.RegisterJITDylib.Addr, JD.getName(), HandleAddr)),
815 MP.DeregisterJITDylib.Addr, HandleAddr))});
821void ELFNixPlatform::ELFNixPlatformPlugin::addEHAndTLVSupportPasses(
823 bool IsBootstrapping) {
832 return fixTLVSectionsAndEdges(G, JD);
838 jitlink::LinkGraph &
G) ->
Error {
839 ELFPerObjectSectionsToRegister POSR;
842 jitlink::SectionRange
R(*EHFrameSection);
849 jitlink::Section *ThreadDataSection =
857 if (ThreadDataSection)
858 G.mergeSections(*ThreadDataSection, *ThreadBSSSection);
860 ThreadDataSection = ThreadBSSSection;
865 if (ThreadDataSection) {
866 jitlink::SectionRange
R(*ThreadDataSection);
872 if (
auto Err = MP.registerPerObjectSections(
G, POSR, IsBootstrapping))
880Error ELFNixPlatform::ELFNixPlatformPlugin::preserveInitSections(
881 jitlink::LinkGraph &
G, MaterializationResponsibility &MR) {
885 jitlink::Symbol *InitSym =
nullptr;
887 for (
auto &InitSection :
G.sections()) {
896 auto &
B = **InitSection.blocks().begin();
897 InitSym = &
G.addDefinedSymbol(
903 for (
auto *
B : InitSection.blocks()) {
907 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
913 for (
auto &FiniSection :
G.sections()) {
921 auto &
B = **FiniSection.blocks().begin();
922 InitSym = &
G.addDefinedSymbol(
928 for (
auto *
B : FiniSection.blocks()) {
932 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
941Error ELFNixPlatform::ELFNixPlatformPlugin::registerInitSections(
942 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
947 for (
auto &Sec :
G.sections())
954 auto getInitSectionInfo =
955 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
956 StringRef
Name = Sec->getName();
957 if (
Name.starts_with(
".init_array")) {
958 StringRef PrioStr =
Name;
962 return {0, Prio, HasPrio};
964 if (
Name.starts_with(
".init"))
965 return {1, 0,
false};
966 if (
Name.starts_with(
".ctors")) {
967 StringRef PrioStr =
Name;
971 return {2, Prio, HasPrio};
973 return {3, 0,
false};
982 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
983 auto [LType, LPrio, LHasPrio] = getInitSectionInfo(
LHS);
984 auto [RType, RPrio, RHasPrio] = getInitSectionInfo(
RHS);
987 return LType < RType;
993 if (LHasPrio && RHasPrio)
994 return LPrio < RPrio;
999 }
else if (LType == 2) {
1002 if (LHasPrio && RHasPrio)
1003 return LPrio > RPrio;
1012 for (
auto &Sec : OrderedInitSections)
1013 ELFNixPlatformSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1017 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" init sections:\n";
1018 for (
auto &Sec :
G.sections()) {
1019 jitlink::SectionRange
R(Sec);
1020 dbgs() <<
" " << Sec.getName() <<
": " <<
R.getRange() <<
"\n";
1024 ExecutorAddr HeaderAddr;
1026 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1027 auto I = MP.JITDylibToHandleAddr.find(&JD);
1028 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1029 assert(
I->second &&
"Null header registered for JD");
1030 HeaderAddr =
I->second;
1033 using SPSRegisterInitSectionsArgs =
1034 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1037 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1038 &MP.RegisterInitSections, &MP.DeregisterInitSections,
1039 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1040 ELFNixPlatformSecs),
1041 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1042 ELFNixPlatformSecs));
1046 G.allocActions().push_back(
1048 MP.RegisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs)),
1050 MP.DeregisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs))});
1055Error ELFNixPlatform::ELFNixPlatformPlugin::registerFiniSections(
1056 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
1061 for (
auto &Sec :
G.sections())
1068 auto getFiniSectionInfo =
1069 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
1070 StringRef
Name = Sec->getName();
1071 if (
Name.starts_with(
".dtors")) {
1072 StringRef PrioStr =
Name;
1076 return {0, Prio, HasPrio};
1078 if (
Name.starts_with(
".fini"))
1079 if (!
Name.starts_with(
".fini_array"))
1080 return {1, 0,
false};
1081 if (
Name.starts_with(
".fini_array")) {
1082 StringRef PrioStr =
Name;
1086 return {2, Prio, HasPrio};
1088 return {3, 0,
false};
1096 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
1097 auto [LType, LPrio, LHasPrio] = getFiniSectionInfo(
LHS);
1098 auto [RType, RPrio, RHasPrio] = getFiniSectionInfo(
RHS);
1101 return LType < RType;
1107 if (LHasPrio && RHasPrio)
1108 return LPrio < RPrio;
1113 }
else if (LType == 2) {
1116 if (LHasPrio && RHasPrio)
1117 return LPrio > RPrio;
1126 for (
auto *Sec : OrderedFiniSections)
1127 ELFNixFiniSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1129 if (ELFNixFiniSecs.
empty())
1134 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" fini sections:\n";
1135 for (
auto *Sec : OrderedFiniSections) {
1136 jitlink::SectionRange
R(*Sec);
1137 dbgs() <<
" " << Sec->getName() <<
": " <<
R.getRange() <<
"\n";
1141 ExecutorAddr HeaderAddr;
1143 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1144 auto I = MP.JITDylibToHandleAddr.find(&JD);
1145 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1146 assert(
I->second &&
"Null header registered for JD");
1147 HeaderAddr =
I->second;
1150 using SPSRegisterFiniSectionsArgs =
1151 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1154 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1155 &MP.RegisterFiniSections, &MP.DeregisterFiniSections,
1156 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1158 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1163 G.allocActions().push_back(
1165 MP.RegisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs)),
1167 MP.DeregisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs))});
1172Error ELFNixPlatform::ELFNixPlatformPlugin::fixTLVSectionsAndEdges(
1173 jitlink::LinkGraph &
G, JITDylib &JD) {
1174 auto TLSGetAddrSymbolName =
G.intern(
"__tls_get_addr");
1175 auto TLSDescResolveSymbolName =
G.intern(
"__tlsdesc_resolver");
1176 auto TLSGetOffsetSymbolName =
G.intern(
"__tls_get_offset");
1177 for (
auto *Sym :
G.external_symbols()) {
1178 if (Sym->getName() == TLSGetAddrSymbolName) {
1180 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_addr");
1181 Sym->setName(std::move(TLSGetAddr));
1182 }
else if (Sym->getName() == TLSDescResolveSymbolName) {
1184 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tlsdesc_resolver");
1185 Sym->setName(std::move(TLSGetAddr));
1186 }
else if (Sym->getName() == TLSGetOffsetSymbolName) {
1188 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_offset");
1189 Sym->setName(std::move(TLSGetAddr));
1193 auto *TLSInfoEntrySection =
G.findSectionByName(
"$__TLSINFO");
1195 if (TLSInfoEntrySection) {
1196 std::optional<uint64_t>
Key;
1198 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1199 auto I = MP.JITDylibToPThreadKey.find(&JD);
1200 if (
I != MP.JITDylibToPThreadKey.end())
1204 if (
auto KeyOrErr = MP.createPThreadKey())
1207 return KeyOrErr.takeError();
1213 for (
auto *
B : TLSInfoEntrySection->blocks()) {
1216 assert(
B->getSize() == (
G.getPointerSize() * 2) &&
1217 "TLS descriptor must be 2 words length");
1218 auto TLSInfoEntryContent =
B->getMutableContent(
G);
1219 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)
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().
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.
Mangles symbol names then uniques them in the context of an ExecutionSession.
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
LLVM_ABI StringRef ELFEHFrameSectionName
std::unique_ptr< ReExportsMaterializationUnit > reexports(JITDylib &SourceJD, SymbolAliasMap Aliases, JITDylibLookupFlags SourceJDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Create a materialization unit for re-exporting symbols from another JITDylib with alternative names/f...
@ MatchExportedSymbolsOnly
static void addAliases(ExecutionSession &ES, SymbolAliasMap &Aliases, ArrayRef< std::pair< const char *, const char * > > AL)
DenseMap< std::pair< RuntimeFunction *, RuntimeFunction * >, SmallVector< std::pair< shared::WrapperFunctionCall::ArgDataBufferType, shared::WrapperFunctionCall::ArgDataBufferType > > > 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 Expected< SymbolAliasMap > buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols)
Build a SymbolAliasMap for the common case where you want to re-export symbols from another JITDylib ...
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)
Swap the bytes of value to match the given endianness.
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