27#define DEBUG_TYPE "orc"
45template <
typename SPSSerializer,
typename... ArgTs>
47getArgDataBufferType(
const ArgTs &...Args) {
49 ArgData.
resize(SPSSerializer::size(Args...));
52 if (SPSSerializer::serialize(OB, Args...))
57std::unique_ptr<jitlink::LinkGraph> createPlatformGraph(
ELFNixPlatform &MOP,
60 return std::make_unique<jitlink::LinkGraph>(
61 std::move(Name), ES.getSymbolStringPool(), ES.getTargetTriple(),
67class ELFNixPlatformCompleteBootstrapMaterializationUnit
70 ELFNixPlatformCompleteBootstrapMaterializationUnit(
71 ELFNixPlatform &MOP, StringRef PlatformJDName,
73 ExecutorAddr ELFNixHeaderAddr, ExecutorAddr PlatformBootstrap,
74 ExecutorAddr PlatformShutdown, ExecutorAddr RegisterJITDylib,
75 ExecutorAddr DeregisterJITDylib)
76 : MaterializationUnit(
78 MOP(MOP), PlatformJDName(PlatformJDName),
79 CompleteBootstrapSymbol(std::move(CompleteBootstrapSymbol)),
80 DeferredAAsMap(std::move(DeferredAAs)),
81 ELFNixHeaderAddr(ELFNixHeaderAddr),
82 PlatformBootstrap(PlatformBootstrap),
83 PlatformShutdown(PlatformShutdown), RegisterJITDylib(RegisterJITDylib),
84 DeregisterJITDylib(DeregisterJITDylib) {}
86 StringRef
getName()
const override {
87 return "ELFNixPlatformCompleteBootstrap";
90 void materialize(std::unique_ptr<MaterializationResponsibility> R)
override {
91 using namespace jitlink;
92 auto G = createPlatformGraph(MOP,
"<OrcRTCompleteBootstrap>");
93 auto &PlaceholderSection =
94 G->createSection(
"__orc_rt_cplt_bs", MemProt::Read);
95 auto &PlaceholderBlock =
96 G->createZeroFillBlock(PlaceholderSection, 1, ExecutorAddr(), 1, 0);
97 G->addDefinedSymbol(PlaceholderBlock, 0, *CompleteBootstrapSymbol, 1,
98 Linkage::Strong, Scope::Hidden,
false,
true);
101 G->allocActions().push_back(
103 PlatformBootstrap, ELFNixHeaderAddr)),
108 G->allocActions().push_back(
110 SPSArgList<SPSString, SPSExecutorAddr>>(
111 RegisterJITDylib, PlatformJDName, ELFNixHeaderAddr)),
113 DeregisterJITDylib, ELFNixHeaderAddr))});
116 for (
auto &[Fn, CallDatas] : DeferredAAsMap) {
117 for (
auto &CallData : CallDatas) {
118 G->allocActions().push_back(
119 {WrapperFunctionCall(Fn.first->Addr, std::move(CallData.first)),
120 WrapperFunctionCall(Fn.second->Addr, std::move(CallData.second))});
124 MOP.getObjectLinkingLayer().emit(std::move(R), std::move(
G));
127 void discard(
const JITDylib &JD,
const SymbolStringPtr &Sym)
override {}
131 StringRef PlatformJDName;
132 SymbolStringPtr CompleteBootstrapSymbol;
134 ExecutorAddr ELFNixHeaderAddr;
135 ExecutorAddr PlatformBootstrap;
136 ExecutorAddr PlatformShutdown;
137 ExecutorAddr RegisterJITDylib;
138 ExecutorAddr DeregisterJITDylib;
143 DSOHandleMaterializationUnit(ELFNixPlatform &ENP,
144 const SymbolStringPtr &DSOHandleSymbol)
145 : MaterializationUnit(
146 createDSOHandleSectionInterface(ENP, DSOHandleSymbol)),
149 StringRef
getName()
const override {
return "DSOHandleMU"; }
151 void materialize(std::unique_ptr<MaterializationResponsibility> R)
override {
153 auto &ES = ENP.getExecutionSession();
155 jitlink::Edge::Kind EdgeKind;
156 unsigned PointerSize = ES.getTargetTriple().getArchPointerBitWidth() / 8;
158 switch (ES.getTargetTriple().getArch()) {
180 if (ES.getTargetTriple().isABIN32()) {
194 auto G = std::make_unique<jitlink::LinkGraph>(
195 "<DSOHandleMU>", ES.getSymbolStringPool(), ES.getTargetTriple(),
197 auto &DSOHandleSection =
198 G->createSection(
".data.__dso_handle", MemProt::Read);
199 auto &DSOHandleBlock =
G->createContentBlock(
200 DSOHandleSection, getDSOHandleContent(
G->getPointerSize()),
201 orc::ExecutorAddr(), 8, 0);
202 auto &DSOHandleSymbol =
G->addDefinedSymbol(
203 DSOHandleBlock, 0, *
R->getInitializerSymbol(), DSOHandleBlock.getSize(),
204 jitlink::Linkage::Strong, jitlink::Scope::Default,
false,
true);
205 DSOHandleBlock.addEdge(EdgeKind, 0, DSOHandleSymbol, 0);
207 ENP.getObjectLinkingLayer().emit(std::move(R), std::move(
G));
210 void discard(
const JITDylib &JD,
const SymbolStringPtr &Sym)
override {}
213 static MaterializationUnit::Interface
214 createDSOHandleSectionInterface(ELFNixPlatform &ENP,
215 const SymbolStringPtr &DSOHandleSymbol) {
218 return MaterializationUnit::Interface(std::move(SymbolFlags),
222 ArrayRef<char> getDSOHandleContent(
size_t PointerSize) {
223 static const char Content[8] = {0};
224 assert(PointerSize <=
sizeof Content);
236Expected<std::unique_ptr<ELFNixPlatform>>
239 std::unique_ptr<DefinitionGenerator> OrcRuntime,
240 std::optional<SymbolAliasMap> RuntimeAliases) {
242 auto &ES = ObjLinkingLayer.getExecutionSession();
245 if (!supportedTarget(ES.getTargetTriple()))
247 ES.getTargetTriple().str(),
251 if (!RuntimeAliases) {
253 if (!StandardRuntimeAliases)
254 return StandardRuntimeAliases.takeError();
255 RuntimeAliases = std::move(*StandardRuntimeAliases);
259 if (
auto Err = PlatformJD.define(
symbolAliases(std::move(*RuntimeAliases))))
260 return std::move(Err);
266 ES.getBootstrapJITDylib(),
267 {{Mangle(rt::DispatchName), Mangle(rt::DispatchCtxName)}});
269 return Exports.takeError();
271 PlatformJD.define(
reexports(ES.getBootstrapJITDylib(), *Exports)))
278 ObjLinkingLayer, PlatformJD, std::move(OrcRuntime), Err));
280 return std::move(Err);
286 JITDylib &PlatformJD,
const char *OrcRuntimePath,
287 std::optional<SymbolAliasMap> RuntimeAliases) {
290 auto OrcRuntimeArchiveGenerator =
292 if (!OrcRuntimeArchiveGenerator)
293 return OrcRuntimeArchiveGenerator.takeError();
295 return Create(ObjLinkingLayer, PlatformJD,
296 std::move(*OrcRuntimeArchiveGenerator),
297 std::move(RuntimeAliases));
301 if (
auto Err = JD.
define(std::make_unique<DSOHandleMaterializationUnit>(
302 *
this, DSOHandleSymbol)))
305 return ES.lookup({&JD}, DSOHandleSymbol).takeError();
309 std::lock_guard<std::mutex> Lock(PlatformMutex);
310 auto I = JITDylibToHandleAddr.find(&JD);
311 if (
I != JITDylibToHandleAddr.end()) {
312 assert(HandleAddrToJITDylib.count(
I->second) &&
313 "HandleAddrToJITDylib missing entry");
314 HandleAddrToJITDylib.erase(
I->second);
315 JITDylibToHandleAddr.erase(
I);
328 RegisteredInitSymbols[&JD].add(InitSym,
331 dbgs() <<
"ELFNixPlatform: Registered init symbol " << *InitSym
332 <<
" for MU " << MU.
getName() <<
"\n";
342 ArrayRef<std::pair<const char *, const char *>> AL) {
343 for (
auto &KV : AL) {
344 auto AliasName = ES.
intern(KV.first);
345 assert(!Aliases.
count(AliasName) &&
"Duplicate symbol name in alias map");
346 Aliases[std::move(AliasName)] = {ES.
intern(KV.second),
363 static const std::pair<const char *, const char *> RequiredCXXAliases[] = {
364 {
"__cxa_atexit",
"__orc_rt_elfnix_cxa_atexit"},
365 {
"atexit",
"__orc_rt_elfnix_atexit"}};
372 static const std::pair<const char *, const char *>
373 StandardRuntimeUtilityAliases[] = {
374 {
"__orc_rt_run_program",
"__orc_rt_elfnix_run_program"},
375 {
"__orc_rt_jit_dlerror",
"__orc_rt_elfnix_jit_dlerror"},
376 {
"__orc_rt_jit_dlopen",
"__orc_rt_elfnix_jit_dlopen"},
377 {
"__orc_rt_jit_dlupdate",
"__orc_rt_elfnix_jit_dlupdate"},
378 {
"__orc_rt_jit_dlclose",
"__orc_rt_elfnix_jit_dlclose"},
379 {
"__orc_rt_jit_dlsym",
"__orc_rt_elfnix_jit_dlsym"},
380 {
"__orc_rt_log_error",
"__orc_rt_log_error_to_stderr"}};
383 StandardRuntimeUtilityAliases);
388 static const std::pair<const char *, const char *>
389 StandardLazyCompilationAliases[] = {
390 {
"__orc_rt_reenter",
"__orc_rt_sysv_reenter"}};
393 StandardLazyCompilationAliases);
396bool ELFNixPlatform::supportedTarget(
const Triple &TT) {
397 switch (TT.getArch()) {
415ELFNixPlatform::ELFNixPlatform(
417 std::unique_ptr<DefinitionGenerator> OrcRuntimeGenerator,
Error &Err)
418 : ES(ObjLinkingLayer.getExecutionSession()), PlatformJD(PlatformJD),
419 ObjLinkingLayer(ObjLinkingLayer),
420 DSOHandleSymbol(ES.intern(
"__dso_handle")) {
422 ObjLinkingLayer.
addPlugin(std::make_unique<ELFNixPlatformPlugin>(*
this));
424 PlatformJD.
addGenerator(std::move(OrcRuntimeGenerator));
438 if ((Err = ES.lookup(
441 {PlatformBootstrap.Name, PlatformShutdown.Name,
442 RegisterJITDylib.Name, DeregisterJITDylib.Name,
443 RegisterInitSections.Name, DeregisterInitSections.Name,
444 RegisterFiniSections.Name, DeregisterFiniSections.Name,
445 RegisterObjectSections.Name,
446 DeregisterObjectSections.Name, CreatePThreadKey.Name}))
452 std::unique_lock<std::mutex> Lock(BI.Mutex);
453 BI.CV.wait(Lock, [&]() {
return BI.ActiveGraphs == 0; });
458 auto BootstrapCompleteSymbol =
459 ES.intern(
"__orc_rt_elfnix_complete_bootstrap");
460 if ((Err = PlatformJD.define(
461 std::make_unique<ELFNixPlatformCompleteBootstrapMaterializationUnit>(
462 *
this, PlatformJD.getName(), BootstrapCompleteSymbol,
463 std::move(BI.DeferredRTFnMap), BI.ELFNixHeaderAddr,
464 PlatformBootstrap.Addr, PlatformShutdown.Addr,
465 RegisterJITDylib.Addr, DeregisterJITDylib.Addr))))
469 std::move(BootstrapCompleteSymbol))
474 if (
auto E2 = associateRuntimeSupportFunctions(PlatformJD)) {
480Error ELFNixPlatform::associateRuntimeSupportFunctions(
JITDylib &PlatformJD) {
481 using RecordInitializersSPSSig =
482 SPSExpected<SPSELFNixJITDylibDepInfoMap>(SPSExecutorAddr);
483 using LookupSymbolSPSSig =
484 SPSExpected<SPSExecutorAddr>(SPSExecutorAddr,
SPSString);
486 return ES.registerCallControllerHandlers(
490 &ELFNixPlatform::rt_recordInitializers),
493 &ELFNixPlatform::rt_lookupSymbol));
496void ELFNixPlatform::pushInitializersLoop(
497 PushInitializersSendResultFn SendResult,
JITDylibSP JD) {
498 DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols;
499 DenseMap<JITDylib *, SmallVector<JITDylib *>> JDDepMap;
502 ES.runSessionLocked([&]() {
503 while (!Worklist.empty()) {
506 auto DepJD = Worklist.back();
515 auto &
DM = It->second;
518 if (KV.first == DepJD)
520 DM.push_back(KV.first);
521 Worklist.push_back(KV.first);
526 auto RISItr = RegisteredInitSymbols.find(DepJD);
527 if (RISItr != RegisteredInitSymbols.end()) {
528 NewInitSymbols[DepJD] = std::move(RISItr->second);
529 RegisteredInitSymbols.erase(RISItr);
536 if (NewInitSymbols.
empty()) {
542 DenseMap<JITDylib *, ExecutorAddr> HeaderAddrs;
545 std::lock_guard<std::mutex> Lock(PlatformMutex);
546 for (
auto &KV : JDDepMap) {
547 auto I = JITDylibToHandleAddr.find(KV.first);
548 if (
I != JITDylibToHandleAddr.end())
549 HeaderAddrs[KV.first] =
I->second;
555 DIM.reserve(JDDepMap.size());
556 for (
auto &KV : JDDepMap) {
557 auto HI = HeaderAddrs.
find(KV.first);
559 if (HI == HeaderAddrs.
end())
563 for (
auto &Dep : KV.second) {
564 auto HJ = HeaderAddrs.
find(Dep);
565 if (HJ != HeaderAddrs.
end())
566 DepInfo.push_back(HJ->second);
568 DIM.push_back(std::make_pair(
H, std::move(DepInfo)));
576 [
this, SendResult = std::move(SendResult), JD](
Error Err)
mutable {
578 SendResult(std::move(Err));
580 pushInitializersLoop(std::move(SendResult), JD);
582 ES, std::move(NewInitSymbols));
585void ELFNixPlatform::rt_recordInitializers(
586 PushInitializersSendResultFn SendResult,
ExecutorAddr JDHeaderAddr) {
589 std::lock_guard<std::mutex> Lock(PlatformMutex);
590 auto I = HandleAddrToJITDylib.find(JDHeaderAddr);
591 if (
I != HandleAddrToJITDylib.end())
596 dbgs() <<
"ELFNixPlatform::rt_recordInitializers(" << JDHeaderAddr <<
") ";
598 dbgs() <<
"pushing initializers for " << JD->
getName() <<
"\n";
600 dbgs() <<
"No JITDylib for header address.\n";
605 formatv(
"{0:x}", JDHeaderAddr),
610 pushInitializersLoop(std::move(SendResult), JD);
613void ELFNixPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult,
615 StringRef SymbolName) {
617 dbgs() <<
"ELFNixPlatform::rt_lookupSymbol(\"" << Handle <<
"\")\n";
620 JITDylib *JD =
nullptr;
623 std::lock_guard<std::mutex> Lock(PlatformMutex);
624 auto I = HandleAddrToJITDylib.find(Handle);
625 if (
I != HandleAddrToJITDylib.end())
630 LLVM_DEBUG(
dbgs() <<
" No JITDylib for handle " << Handle <<
"\n");
638 class RtLookupNotifyComplete {
640 RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult)
641 : SendResult(std::
move(SendResult)) {}
642 void operator()(Expected<SymbolMap>
Result) {
644 assert(
Result->size() == 1 &&
"Unexpected result map count");
645 SendResult(
Result->begin()->second.getAddress());
647 SendResult(
Result.takeError());
652 SendSymbolAddressFn SendResult;
661Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineStart(
662 jitlink::LinkGraph &
G) {
664 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
665 ++MP.Bootstrap.load()->ActiveGraphs;
669Error ELFNixPlatform::ELFNixPlatformPlugin::
670 bootstrapPipelineRecordRuntimeFunctions(jitlink::LinkGraph &
G) {
672 std::pair<StringRef, ExecutorAddr *> RuntimeSymbols[] = {
673 {*MP.DSOHandleSymbol, &MP.Bootstrap.load()->ELFNixHeaderAddr},
674 {*MP.PlatformBootstrap.Name, &MP.PlatformBootstrap.Addr},
675 {*MP.PlatformShutdown.Name, &MP.PlatformShutdown.Addr},
676 {*MP.RegisterJITDylib.Name, &MP.RegisterJITDylib.Addr},
677 {*MP.DeregisterJITDylib.Name, &MP.DeregisterJITDylib.Addr},
678 {*MP.RegisterObjectSections.Name, &MP.RegisterObjectSections.Addr},
679 {*MP.DeregisterObjectSections.Name, &MP.DeregisterObjectSections.Addr},
680 {*MP.RegisterInitSections.Name, &MP.RegisterInitSections.Addr},
681 {*MP.DeregisterInitSections.Name, &MP.DeregisterInitSections.Addr},
682 {*MP.RegisterFiniSections.Name, &MP.RegisterFiniSections.Addr},
683 {*MP.DeregisterFiniSections.Name, &MP.DeregisterFiniSections.Addr},
684 {*MP.CreatePThreadKey.Name, &MP.CreatePThreadKey.Addr}};
686 bool RegisterELFNixHeader =
false;
688 for (
auto *Sym :
G.defined_symbols()) {
689 for (
auto &RTSym : RuntimeSymbols) {
690 if (Sym->hasName() && *Sym->getName() == RTSym.first) {
693 "Duplicate " + RTSym.first +
694 " detected during ELFNixPlatform bootstrap",
697 if (*Sym->getName() == *MP.DSOHandleSymbol)
698 RegisterELFNixHeader =
true;
700 *RTSym.second = Sym->getAddress();
705 if (RegisterELFNixHeader) {
708 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
709 MP.JITDylibToHandleAddr[&MP.PlatformJD] =
710 MP.Bootstrap.load()->ELFNixHeaderAddr;
711 MP.HandleAddrToJITDylib[MP.Bootstrap.load()->ELFNixHeaderAddr] =
718Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineEnd(
719 jitlink::LinkGraph &
G) {
720 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
721 assert(MP.Bootstrap &&
"DeferredAAs reset before bootstrap completed");
722 --MP.Bootstrap.load()->ActiveGraphs;
725 if (MP.Bootstrap.load()->ActiveGraphs == 0)
726 MP.Bootstrap.load()->CV.notify_all();
730Error ELFNixPlatform::registerPerObjectSections(
731 jitlink::LinkGraph &
G,
const ELFPerObjectSectionsToRegister &POSR,
732 bool IsBootstrapping) {
733 using SPSRegisterPerObjSectionsArgs =
734 SPSArgList<SPSELFPerObjectSectionsToRegister>;
737 Bootstrap.load()->addArgumentsToRTFnMap(
738 &RegisterObjectSections, &DeregisterObjectSections,
739 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR),
740 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR));
744 G.allocActions().push_back(
746 RegisterObjectSections.Addr, POSR)),
748 DeregisterObjectSections.Addr, POSR))});
753Expected<uint64_t> ELFNixPlatform::createPThreadKey() {
754 if (!CreatePThreadKey.Addr)
756 "Attempting to create pthread key in target, but runtime support has "
757 "not been loaded yet",
760 using CreatePThreadKeyProxy = Proxy<Expected<uint64_t>()>;
761 CreatePThreadKeyProxy CreateKey(
762 sps::ProxySpec<CreatePThreadKeyProxy,
763 elfnix_sps_ci::CreatePThreadKey>::dispatch,
764 CreatePThreadKey.Addr);
765 return CreateKey(ES);
768void ELFNixPlatform::ELFNixPlatformPlugin::modifyPassConfig(
769 MaterializationResponsibility &MR, jitlink::LinkGraph &LG,
770 jitlink::PassConfiguration &Config) {
771 using namespace jitlink;
773 bool InBootstrapPhase =
777 if (InBootstrapPhase) {
779 [
this](LinkGraph &
G) {
return bootstrapPipelineStart(
G); });
781 return bootstrapPipelineRecordRuntimeFunctions(
G);
788 if (InitSymbol == MP.DSOHandleSymbol && !InBootstrapPhase) {
789 addDSOHandleSupportPasses(MR, Config);
797 [
this, &MR](jitlink::LinkGraph &
G) ->
Error {
798 if (
auto Err = preserveInitSections(
G, MR))
805 addEHAndTLVSupportPasses(MR, Config, InBootstrapPhase);
809 InBootstrapPhase](jitlink::LinkGraph &
G) {
810 return registerInitSections(G, JD, InBootstrapPhase);
815 InBootstrapPhase](jitlink::LinkGraph &
G) {
816 return registerFiniSections(G, JD, InBootstrapPhase);
821 if (InBootstrapPhase)
823 [
this](LinkGraph &
G) {
return bootstrapPipelineEnd(
G); });
826void ELFNixPlatform::ELFNixPlatformPlugin::addDSOHandleSupportPasses(
827 MaterializationResponsibility &MR, jitlink::PassConfiguration &Config) {
830 jitlink::LinkGraph &
G) ->
Error {
831 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
832 return Sym->getName() == MP.DSOHandleSymbol;
834 assert(
I !=
G.defined_symbols().end() &&
"Missing DSO handle symbol");
836 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
837 auto HandleAddr = (*I)->getAddress();
838 MP.HandleAddrToJITDylib[HandleAddr] = &JD;
839 MP.JITDylibToHandleAddr[&JD] = HandleAddr;
841 G.allocActions().push_back(
843 SPSArgList<SPSString, SPSExecutorAddr>>(
844 MP.RegisterJITDylib.Addr, JD.getName(), HandleAddr)),
846 MP.DeregisterJITDylib.Addr, HandleAddr))});
852void ELFNixPlatform::ELFNixPlatformPlugin::addEHAndTLVSupportPasses(
854 bool IsBootstrapping) {
863 return fixTLVSectionsAndEdges(G, JD);
869 jitlink::LinkGraph &
G) ->
Error {
870 ELFPerObjectSectionsToRegister POSR;
873 jitlink::SectionRange
R(*EHFrameSection);
880 jitlink::Section *ThreadDataSection =
888 if (ThreadDataSection)
889 G.mergeSections(*ThreadDataSection, *ThreadBSSSection);
891 ThreadDataSection = ThreadBSSSection;
896 if (ThreadDataSection) {
897 jitlink::SectionRange
R(*ThreadDataSection);
903 if (
auto Err = MP.registerPerObjectSections(
G, POSR, IsBootstrapping))
911Error ELFNixPlatform::ELFNixPlatformPlugin::preserveInitSections(
912 jitlink::LinkGraph &
G, MaterializationResponsibility &MR) {
916 jitlink::Symbol *InitSym =
nullptr;
918 for (
auto &InitSection :
G.sections()) {
927 auto &
B = **InitSection.blocks().begin();
928 InitSym = &
G.addDefinedSymbol(
934 for (
auto *
B : InitSection.blocks()) {
938 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
944 for (
auto &FiniSection :
G.sections()) {
952 auto &
B = **FiniSection.blocks().begin();
953 InitSym = &
G.addDefinedSymbol(
959 for (
auto *
B : FiniSection.blocks()) {
963 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
972Error ELFNixPlatform::ELFNixPlatformPlugin::registerInitSections(
973 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
978 for (
auto &Sec :
G.sections())
985 auto getInitSectionInfo =
986 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
987 StringRef
Name = Sec->getName();
988 if (
Name.starts_with(
".init_array")) {
989 StringRef PrioStr =
Name;
993 return {0, Prio, HasPrio};
995 if (
Name.starts_with(
".init"))
996 return {1, 0,
false};
997 if (
Name.starts_with(
".ctors")) {
998 StringRef PrioStr =
Name;
1002 return {2, Prio, HasPrio};
1004 return {3, 0,
false};
1013 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
1014 auto [LType, LPrio, LHasPrio] = getInitSectionInfo(
LHS);
1015 auto [RType, RPrio, RHasPrio] = getInitSectionInfo(
RHS);
1018 return LType < RType;
1024 if (LHasPrio && RHasPrio)
1025 return LPrio < RPrio;
1030 }
else if (LType == 2) {
1033 if (LHasPrio && RHasPrio)
1034 return LPrio > RPrio;
1043 for (
auto &Sec : OrderedInitSections)
1044 ELFNixPlatformSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1048 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" init sections:\n";
1049 for (
auto &Sec :
G.sections()) {
1050 jitlink::SectionRange
R(Sec);
1051 dbgs() <<
" " << Sec.getName() <<
": " <<
R.getRange() <<
"\n";
1055 ExecutorAddr HeaderAddr;
1057 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1058 auto I = MP.JITDylibToHandleAddr.find(&JD);
1059 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1060 assert(
I->second &&
"Null header registered for JD");
1061 HeaderAddr =
I->second;
1064 using SPSRegisterInitSectionsArgs =
1065 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1068 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1069 &MP.RegisterInitSections, &MP.DeregisterInitSections,
1070 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1071 ELFNixPlatformSecs),
1072 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1073 ELFNixPlatformSecs));
1077 G.allocActions().push_back(
1079 MP.RegisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs)),
1081 MP.DeregisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs))});
1086Error ELFNixPlatform::ELFNixPlatformPlugin::registerFiniSections(
1087 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
1092 for (
auto &Sec :
G.sections())
1099 auto getFiniSectionInfo =
1100 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
1101 StringRef
Name = Sec->getName();
1102 if (
Name.starts_with(
".dtors")) {
1103 StringRef PrioStr =
Name;
1107 return {0, Prio, HasPrio};
1109 if (
Name.starts_with(
".fini"))
1110 if (!
Name.starts_with(
".fini_array"))
1111 return {1, 0,
false};
1112 if (
Name.starts_with(
".fini_array")) {
1113 StringRef PrioStr =
Name;
1117 return {2, Prio, HasPrio};
1119 return {3, 0,
false};
1127 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
1128 auto [LType, LPrio, LHasPrio] = getFiniSectionInfo(
LHS);
1129 auto [RType, RPrio, RHasPrio] = getFiniSectionInfo(
RHS);
1132 return LType < RType;
1138 if (LHasPrio && RHasPrio)
1139 return LPrio < RPrio;
1144 }
else if (LType == 2) {
1147 if (LHasPrio && RHasPrio)
1148 return LPrio > RPrio;
1157 for (
auto *Sec : OrderedFiniSections)
1158 ELFNixFiniSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1160 if (ELFNixFiniSecs.
empty())
1165 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" fini sections:\n";
1166 for (
auto *Sec : OrderedFiniSections) {
1167 jitlink::SectionRange
R(*Sec);
1168 dbgs() <<
" " << Sec->getName() <<
": " <<
R.getRange() <<
"\n";
1172 ExecutorAddr HeaderAddr;
1174 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1175 auto I = MP.JITDylibToHandleAddr.find(&JD);
1176 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1177 assert(
I->second &&
"Null header registered for JD");
1178 HeaderAddr =
I->second;
1181 using SPSRegisterFiniSectionsArgs =
1182 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1185 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1186 &MP.RegisterFiniSections, &MP.DeregisterFiniSections,
1187 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1189 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1194 G.allocActions().push_back(
1196 MP.RegisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs)),
1198 MP.DeregisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs))});
1203Error ELFNixPlatform::ELFNixPlatformPlugin::fixTLVSectionsAndEdges(
1204 jitlink::LinkGraph &
G, JITDylib &JD) {
1205 auto TLSGetAddrSymbolName =
G.intern(
"__tls_get_addr");
1206 auto TLSDescResolveSymbolName =
G.intern(
"__tlsdesc_resolver");
1207 auto TLSGetOffsetSymbolName =
G.intern(
"__tls_get_offset");
1208 for (
auto *Sym :
G.external_symbols()) {
1209 if (Sym->getName() == TLSGetAddrSymbolName) {
1211 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_addr");
1212 Sym->setName(std::move(TLSGetAddr));
1213 }
else if (Sym->getName() == TLSDescResolveSymbolName) {
1215 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tlsdesc_resolver");
1216 Sym->setName(std::move(TLSGetAddr));
1217 }
else if (Sym->getName() == TLSGetOffsetSymbolName) {
1219 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_offset");
1220 Sym->setName(std::move(TLSGetAddr));
1224 auto *TLSInfoEntrySection =
G.findSectionByName(
"$__TLSINFO");
1226 if (TLSInfoEntrySection) {
1227 std::optional<uint64_t>
Key;
1229 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1230 auto I = MP.JITDylibToPThreadKey.find(&JD);
1231 if (
I != MP.JITDylibToPThreadKey.end())
1235 if (
auto KeyOrErr = MP.createPThreadKey())
1238 return KeyOrErr.takeError();
1241 for (
auto *
B : TLSInfoEntrySection->blocks()) {
1244 assert(
B->getSize() == (
G.getPointerSize() * 2) &&
1245 "TLS descriptor must be 2 words length");
1246 auto TLSInfoEntryContent =
B->getMutableContent(
G);
1247 if (
G.getPointerSize() == 4)
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),...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
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().
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.
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.
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.
A symbol name together with the naming level (SymbolNameKind) it is expressed in, so that a Mangler /...
static constexpr SymbolNameSpec c(StringRef Name)
SPS tag type for expecteds, which are either a T or a string representing an error.
Output char buffer with overflow check.
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.
constexpr uint64_t PointerSize
aarch64 pointer size.
@ Pointer64
A plain 64-bit pointer value relocation.
@ Pointer64
A plain 64-bit pointer value relocation.
@ Pointer64
Fixup <- Target + Addend : uint64.
@ Pointer32
Fixup <- Target + Addend, checked as an unsigned 32-bit pointer.
@ 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
ExecutionSession::CallControllerHandlerBinding bindCallControllerHandlerSPS(SymbolNameSpec Name, HandlerT &&Handler, SymbolLookupFlags LF=SymbolLookupFlags::RequiredSymbol)
Bind a call-controller handler that takes concrete argument types (and a sender for a concrete return...
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.
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular 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
SPSExpected< uint64_t >() SPSSig
static constexpr SymbolNameSpec Name