28#define DEBUG_TYPE "orc"
54 SPSExecutorAddr, SPSString)> {
62template <
typename SPSSerializer,
typename... ArgTs>
64getArgDataBufferType(
const ArgTs &...Args) {
66 ArgData.
resize(SPSSerializer::size(Args...));
69 if (SPSSerializer::serialize(OB, Args...))
74std::unique_ptr<jitlink::LinkGraph> createPlatformGraph(
ELFNixPlatform &MOP,
77 return std::make_unique<jitlink::LinkGraph>(
78 std::move(Name), ES.getSymbolStringPool(), ES.getTargetTriple(),
84class ELFNixPlatformCompleteBootstrapMaterializationUnit
87 ELFNixPlatformCompleteBootstrapMaterializationUnit(
88 ELFNixPlatform &MOP, StringRef PlatformJDName,
90 ExecutorAddr ELFNixHeaderAddr, ExecutorAddr PlatformBootstrap,
91 ExecutorAddr PlatformShutdown, ExecutorAddr RegisterJITDylib,
92 ExecutorAddr DeregisterJITDylib)
93 : MaterializationUnit(
95 MOP(MOP), PlatformJDName(PlatformJDName),
96 CompleteBootstrapSymbol(std::move(CompleteBootstrapSymbol)),
97 DeferredAAsMap(std::move(DeferredAAs)),
98 ELFNixHeaderAddr(ELFNixHeaderAddr),
99 PlatformBootstrap(PlatformBootstrap),
100 PlatformShutdown(PlatformShutdown), RegisterJITDylib(RegisterJITDylib),
101 DeregisterJITDylib(DeregisterJITDylib) {}
103 StringRef
getName()
const override {
104 return "ELFNixPlatformCompleteBootstrap";
107 void materialize(std::unique_ptr<MaterializationResponsibility> R)
override {
108 using namespace jitlink;
109 auto G = createPlatformGraph(MOP,
"<OrcRTCompleteBootstrap>");
110 auto &PlaceholderSection =
111 G->createSection(
"__orc_rt_cplt_bs", MemProt::Read);
112 auto &PlaceholderBlock =
113 G->createZeroFillBlock(PlaceholderSection, 1, ExecutorAddr(), 1, 0);
114 G->addDefinedSymbol(PlaceholderBlock, 0, *CompleteBootstrapSymbol, 1,
115 Linkage::Strong, Scope::Hidden,
false,
true);
118 G->allocActions().push_back(
120 PlatformBootstrap, ELFNixHeaderAddr)),
125 G->allocActions().push_back(
127 SPSArgList<SPSString, SPSExecutorAddr>>(
128 RegisterJITDylib, PlatformJDName, ELFNixHeaderAddr)),
130 DeregisterJITDylib, ELFNixHeaderAddr))});
133 for (
auto &[Fn, CallDatas] : DeferredAAsMap) {
134 for (
auto &CallData : CallDatas) {
135 G->allocActions().push_back(
136 {WrapperFunctionCall(Fn.first->Addr, std::move(CallData.first)),
137 WrapperFunctionCall(Fn.second->Addr, std::move(CallData.second))});
141 MOP.getObjectLinkingLayer().emit(std::move(R), std::move(
G));
144 void discard(
const JITDylib &JD,
const SymbolStringPtr &Sym)
override {}
148 StringRef PlatformJDName;
149 SymbolStringPtr CompleteBootstrapSymbol;
151 ExecutorAddr ELFNixHeaderAddr;
152 ExecutorAddr PlatformBootstrap;
153 ExecutorAddr PlatformShutdown;
154 ExecutorAddr RegisterJITDylib;
155 ExecutorAddr DeregisterJITDylib;
160 DSOHandleMaterializationUnit(ELFNixPlatform &ENP,
161 const SymbolStringPtr &DSOHandleSymbol)
162 : MaterializationUnit(
163 createDSOHandleSectionInterface(ENP, DSOHandleSymbol)),
166 StringRef
getName()
const override {
return "DSOHandleMU"; }
168 void materialize(std::unique_ptr<MaterializationResponsibility> R)
override {
170 auto &ES = ENP.getExecutionSession();
172 jitlink::Edge::Kind EdgeKind;
173 unsigned PointerSize = ES.getTargetTriple().getArchPointerBitWidth() / 8;
175 switch (ES.getTargetTriple().getArch()) {
197 if (ES.getTargetTriple().isABIN32()) {
211 auto G = std::make_unique<jitlink::LinkGraph>(
212 "<DSOHandleMU>", ES.getSymbolStringPool(), ES.getTargetTriple(),
214 auto &DSOHandleSection =
215 G->createSection(
".data.__dso_handle", MemProt::Read);
216 auto &DSOHandleBlock =
G->createContentBlock(
217 DSOHandleSection, getDSOHandleContent(
G->getPointerSize()),
218 orc::ExecutorAddr(), 8, 0);
219 auto &DSOHandleSymbol =
G->addDefinedSymbol(
220 DSOHandleBlock, 0, *
R->getInitializerSymbol(), DSOHandleBlock.getSize(),
221 jitlink::Linkage::Strong, jitlink::Scope::Default,
false,
true);
222 DSOHandleBlock.addEdge(EdgeKind, 0, DSOHandleSymbol, 0);
224 ENP.getObjectLinkingLayer().emit(std::move(R), std::move(
G));
227 void discard(
const JITDylib &JD,
const SymbolStringPtr &Sym)
override {}
230 static MaterializationUnit::Interface
231 createDSOHandleSectionInterface(ELFNixPlatform &ENP,
232 const SymbolStringPtr &DSOHandleSymbol) {
235 return MaterializationUnit::Interface(std::move(SymbolFlags),
239 ArrayRef<char> getDSOHandleContent(
size_t PointerSize) {
240 static const char Content[8] = {0};
241 assert(PointerSize <=
sizeof Content);
253Expected<std::unique_ptr<ELFNixPlatform>>
256 std::unique_ptr<DefinitionGenerator> OrcRuntime,
257 std::optional<SymbolAliasMap> RuntimeAliases) {
259 auto &ES = ObjLinkingLayer.getExecutionSession();
262 if (!supportedTarget(ES.getTargetTriple()))
264 ES.getTargetTriple().str(),
268 if (!RuntimeAliases) {
270 if (!StandardRuntimeAliases)
271 return StandardRuntimeAliases.takeError();
272 RuntimeAliases = std::move(*StandardRuntimeAliases);
276 if (
auto Err = PlatformJD.define(
symbolAliases(std::move(*RuntimeAliases))))
277 return std::move(Err);
283 ES.getBootstrapJITDylib(),
284 {{Mangle(rt::DispatchName), Mangle(rt::DispatchCtxName)}});
286 return Exports.takeError();
288 PlatformJD.define(
reexports(ES.getBootstrapJITDylib(), *Exports)))
295 ObjLinkingLayer, PlatformJD, std::move(OrcRuntime), Err));
297 return std::move(Err);
303 JITDylib &PlatformJD,
const char *OrcRuntimePath,
304 std::optional<SymbolAliasMap> RuntimeAliases) {
307 auto OrcRuntimeArchiveGenerator =
309 if (!OrcRuntimeArchiveGenerator)
310 return OrcRuntimeArchiveGenerator.takeError();
312 return Create(ObjLinkingLayer, PlatformJD,
313 std::move(*OrcRuntimeArchiveGenerator),
314 std::move(RuntimeAliases));
318 if (
auto Err = JD.
define(std::make_unique<DSOHandleMaterializationUnit>(
319 *
this, DSOHandleSymbol)))
322 return ES.lookup({&JD}, DSOHandleSymbol).takeError();
326 std::lock_guard<std::mutex> Lock(PlatformMutex);
327 auto I = JITDylibToHandleAddr.find(&JD);
328 if (
I != JITDylibToHandleAddr.end()) {
329 assert(HandleAddrToJITDylib.count(
I->second) &&
330 "HandleAddrToJITDylib missing entry");
331 HandleAddrToJITDylib.erase(
I->second);
332 JITDylibToHandleAddr.erase(
I);
345 RegisteredInitSymbols[&JD].add(InitSym,
348 dbgs() <<
"ELFNixPlatform: Registered init symbol " << *InitSym
349 <<
" for MU " << MU.
getName() <<
"\n";
359 ArrayRef<std::pair<const char *, const char *>> AL) {
360 for (
auto &KV : AL) {
361 auto AliasName = ES.
intern(KV.first);
362 assert(!Aliases.
count(AliasName) &&
"Duplicate symbol name in alias map");
363 Aliases[std::move(AliasName)] = {ES.
intern(KV.second),
380 static const std::pair<const char *, const char *> RequiredCXXAliases[] = {
381 {
"__cxa_atexit",
"__orc_rt_elfnix_cxa_atexit"},
382 {
"atexit",
"__orc_rt_elfnix_atexit"}};
389 static const std::pair<const char *, const char *>
390 StandardRuntimeUtilityAliases[] = {
391 {
"__orc_rt_run_program",
"__orc_rt_elfnix_run_program"},
392 {
"__orc_rt_jit_dlerror",
"__orc_rt_elfnix_jit_dlerror"},
393 {
"__orc_rt_jit_dlopen",
"__orc_rt_elfnix_jit_dlopen"},
394 {
"__orc_rt_jit_dlupdate",
"__orc_rt_elfnix_jit_dlupdate"},
395 {
"__orc_rt_jit_dlclose",
"__orc_rt_elfnix_jit_dlclose"},
396 {
"__orc_rt_jit_dlsym",
"__orc_rt_elfnix_jit_dlsym"},
397 {
"__orc_rt_log_error",
"__orc_rt_log_error_to_stderr"}};
400 StandardRuntimeUtilityAliases);
405 static const std::pair<const char *, const char *>
406 StandardLazyCompilationAliases[] = {
407 {
"__orc_rt_reenter",
"__orc_rt_sysv_reenter"}};
410 StandardLazyCompilationAliases);
413bool ELFNixPlatform::supportedTarget(
const Triple &TT) {
414 switch (TT.getArch()) {
432ELFNixPlatform::ELFNixPlatform(
434 std::unique_ptr<DefinitionGenerator> OrcRuntimeGenerator,
Error &Err)
435 : ES(ObjLinkingLayer.getExecutionSession()), PlatformJD(PlatformJD),
436 ObjLinkingLayer(ObjLinkingLayer),
437 DSOHandleSymbol(ES.intern(
"__dso_handle")) {
439 ObjLinkingLayer.
addPlugin(std::make_unique<ELFNixPlatformPlugin>(*
this));
441 PlatformJD.
addGenerator(std::move(OrcRuntimeGenerator));
455 if ((Err = ES.lookup(
458 {PlatformBootstrap.Name, PlatformShutdown.Name,
459 RegisterJITDylib.Name, DeregisterJITDylib.Name,
460 RegisterInitSections.Name, DeregisterInitSections.Name,
461 RegisterFiniSections.Name, DeregisterFiniSections.Name,
462 RegisterObjectSections.Name,
463 DeregisterObjectSections.Name, CreatePThreadKey.Name}))
469 std::unique_lock<std::mutex> Lock(BI.Mutex);
470 BI.CV.wait(Lock, [&]() {
return BI.ActiveGraphs == 0; });
475 auto BootstrapCompleteSymbol =
476 ES.intern(
"__orc_rt_elfnix_complete_bootstrap");
477 if ((Err = PlatformJD.define(
478 std::make_unique<ELFNixPlatformCompleteBootstrapMaterializationUnit>(
479 *
this, PlatformJD.getName(), BootstrapCompleteSymbol,
480 std::move(BI.DeferredRTFnMap), BI.ELFNixHeaderAddr,
481 PlatformBootstrap.Addr, PlatformShutdown.Addr,
482 RegisterJITDylib.Addr, DeregisterJITDylib.Addr))))
486 std::move(BootstrapCompleteSymbol))
491 if (
auto E2 = associateRuntimeSupportFunctions(PlatformJD)) {
497Error ELFNixPlatform::associateRuntimeSupportFunctions(
JITDylib &PlatformJD) {
498 return ES.registerCallControllerHandlers(
501 this, &ELFNixPlatform::rt_recordInitializers),
503 this, &ELFNixPlatform::rt_lookupSymbol));
506void ELFNixPlatform::pushInitializersLoop(
507 PushInitializersSendResultFn SendResult,
JITDylibSP JD) {
508 DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols;
509 DenseMap<JITDylib *, SmallVector<JITDylib *>> JDDepMap;
512 ES.runSessionLocked([&]() {
513 while (!Worklist.empty()) {
516 auto DepJD = Worklist.back();
525 auto &
DM = It->second;
528 if (KV.first == DepJD)
530 DM.push_back(KV.first);
531 Worklist.push_back(KV.first);
536 auto RISItr = RegisteredInitSymbols.find(DepJD);
537 if (RISItr != RegisteredInitSymbols.end()) {
538 NewInitSymbols[DepJD] = std::move(RISItr->second);
539 RegisteredInitSymbols.erase(RISItr);
546 if (NewInitSymbols.
empty()) {
552 DenseMap<JITDylib *, ExecutorAddr> HeaderAddrs;
555 std::lock_guard<std::mutex> Lock(PlatformMutex);
556 for (
auto &KV : JDDepMap) {
557 auto I = JITDylibToHandleAddr.find(KV.first);
558 if (
I != JITDylibToHandleAddr.end())
559 HeaderAddrs[KV.first] =
I->second;
565 DIM.reserve(JDDepMap.size());
566 for (
auto &KV : JDDepMap) {
567 auto HI = HeaderAddrs.
find(KV.first);
569 if (HI == HeaderAddrs.
end())
573 for (
auto &Dep : KV.second) {
574 auto HJ = HeaderAddrs.
find(Dep);
575 if (HJ != HeaderAddrs.
end())
576 DepInfo.push_back(HJ->second);
578 DIM.push_back(std::make_pair(
H, std::move(DepInfo)));
586 [
this, SendResult = std::move(SendResult), JD](
Error Err)
mutable {
588 SendResult(std::move(Err));
590 pushInitializersLoop(std::move(SendResult), JD);
592 ES, std::move(NewInitSymbols));
595void ELFNixPlatform::rt_recordInitializers(
596 PushInitializersSendResultFn SendResult,
ExecutorAddr JDHeaderAddr) {
599 std::lock_guard<std::mutex> Lock(PlatformMutex);
600 auto I = HandleAddrToJITDylib.find(JDHeaderAddr);
601 if (
I != HandleAddrToJITDylib.end())
606 dbgs() <<
"ELFNixPlatform::rt_recordInitializers(" << JDHeaderAddr <<
") ";
608 dbgs() <<
"pushing initializers for " << JD->
getName() <<
"\n";
610 dbgs() <<
"No JITDylib for header address.\n";
615 formatv(
"{0:x}", JDHeaderAddr),
620 pushInitializersLoop(std::move(SendResult), JD);
623void ELFNixPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult,
625 StringRef SymbolName) {
627 dbgs() <<
"ELFNixPlatform::rt_lookupSymbol(\"" << Handle <<
"\")\n";
630 JITDylib *JD =
nullptr;
633 std::lock_guard<std::mutex> Lock(PlatformMutex);
634 auto I = HandleAddrToJITDylib.find(Handle);
635 if (
I != HandleAddrToJITDylib.end())
640 LLVM_DEBUG(
dbgs() <<
" No JITDylib for handle " << Handle <<
"\n");
648 class RtLookupNotifyComplete {
650 RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult)
651 : SendResult(std::
move(SendResult)) {}
652 void operator()(Expected<SymbolMap>
Result) {
654 assert(
Result->size() == 1 &&
"Unexpected result map count");
655 SendResult(
Result->begin()->second.getAddress());
657 SendResult(
Result.takeError());
662 SendSymbolAddressFn SendResult;
671Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineStart(
672 jitlink::LinkGraph &
G) {
674 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
675 ++MP.Bootstrap.load()->ActiveGraphs;
679Error ELFNixPlatform::ELFNixPlatformPlugin::
680 bootstrapPipelineRecordRuntimeFunctions(jitlink::LinkGraph &
G) {
682 std::pair<StringRef, ExecutorAddr *> RuntimeSymbols[] = {
683 {*MP.DSOHandleSymbol, &MP.Bootstrap.load()->ELFNixHeaderAddr},
684 {*MP.PlatformBootstrap.Name, &MP.PlatformBootstrap.Addr},
685 {*MP.PlatformShutdown.Name, &MP.PlatformShutdown.Addr},
686 {*MP.RegisterJITDylib.Name, &MP.RegisterJITDylib.Addr},
687 {*MP.DeregisterJITDylib.Name, &MP.DeregisterJITDylib.Addr},
688 {*MP.RegisterObjectSections.Name, &MP.RegisterObjectSections.Addr},
689 {*MP.DeregisterObjectSections.Name, &MP.DeregisterObjectSections.Addr},
690 {*MP.RegisterInitSections.Name, &MP.RegisterInitSections.Addr},
691 {*MP.DeregisterInitSections.Name, &MP.DeregisterInitSections.Addr},
692 {*MP.RegisterFiniSections.Name, &MP.RegisterFiniSections.Addr},
693 {*MP.DeregisterFiniSections.Name, &MP.DeregisterFiniSections.Addr},
694 {*MP.CreatePThreadKey.Name, &MP.CreatePThreadKey.Addr}};
696 bool RegisterELFNixHeader =
false;
698 for (
auto *Sym :
G.defined_symbols()) {
699 for (
auto &RTSym : RuntimeSymbols) {
700 if (Sym->hasName() && *Sym->getName() == RTSym.first) {
703 "Duplicate " + RTSym.first +
704 " detected during ELFNixPlatform bootstrap",
707 if (*Sym->getName() == *MP.DSOHandleSymbol)
708 RegisterELFNixHeader =
true;
710 *RTSym.second = Sym->getAddress();
715 if (RegisterELFNixHeader) {
718 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
719 MP.JITDylibToHandleAddr[&MP.PlatformJD] =
720 MP.Bootstrap.load()->ELFNixHeaderAddr;
721 MP.HandleAddrToJITDylib[MP.Bootstrap.load()->ELFNixHeaderAddr] =
728Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineEnd(
729 jitlink::LinkGraph &
G) {
730 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
731 assert(MP.Bootstrap &&
"DeferredAAs reset before bootstrap completed");
732 --MP.Bootstrap.load()->ActiveGraphs;
735 if (MP.Bootstrap.load()->ActiveGraphs == 0)
736 MP.Bootstrap.load()->CV.notify_all();
740Error ELFNixPlatform::registerPerObjectSections(
741 jitlink::LinkGraph &
G,
const ELFPerObjectSectionsToRegister &POSR,
742 bool IsBootstrapping) {
743 using SPSRegisterPerObjSectionsArgs =
744 SPSArgList<SPSELFPerObjectSectionsToRegister>;
747 Bootstrap.load()->addArgumentsToRTFnMap(
748 &RegisterObjectSections, &DeregisterObjectSections,
749 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR),
750 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR));
754 G.allocActions().push_back(
756 RegisterObjectSections.Addr, POSR)),
758 DeregisterObjectSections.Addr, POSR))});
763Expected<uint64_t> ELFNixPlatform::createPThreadKey() {
764 if (!CreatePThreadKey.Addr)
766 "Attempting to create pthread key in target, but runtime support has "
767 "not been loaded yet",
770 using CreatePThreadKeyProxy = Proxy<Expected<uint64_t>()>;
771 CreatePThreadKeyProxy CreateKey(
772 sps::ProxySpec<elfnix_sps_ci::CreatePThreadKey>::dispatch,
773 CreatePThreadKey.Addr);
774 return CreateKey(ES);
777void ELFNixPlatform::ELFNixPlatformPlugin::modifyPassConfig(
778 MaterializationResponsibility &MR, jitlink::LinkGraph &LG,
779 jitlink::PassConfiguration &Config) {
780 using namespace jitlink;
782 bool InBootstrapPhase =
786 if (InBootstrapPhase) {
788 [
this](LinkGraph &
G) {
return bootstrapPipelineStart(
G); });
790 return bootstrapPipelineRecordRuntimeFunctions(
G);
797 if (InitSymbol == MP.DSOHandleSymbol && !InBootstrapPhase) {
798 addDSOHandleSupportPasses(MR, Config);
806 [
this, &MR](jitlink::LinkGraph &
G) ->
Error {
807 if (
auto Err = preserveInitSections(
G, MR))
814 addEHAndTLVSupportPasses(MR, Config, InBootstrapPhase);
818 InBootstrapPhase](jitlink::LinkGraph &
G) {
819 return registerInitSections(G, JD, InBootstrapPhase);
824 InBootstrapPhase](jitlink::LinkGraph &
G) {
825 return registerFiniSections(G, JD, InBootstrapPhase);
830 if (InBootstrapPhase)
832 [
this](LinkGraph &
G) {
return bootstrapPipelineEnd(
G); });
835void ELFNixPlatform::ELFNixPlatformPlugin::addDSOHandleSupportPasses(
836 MaterializationResponsibility &MR, jitlink::PassConfiguration &Config) {
839 jitlink::LinkGraph &
G) ->
Error {
840 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
841 return Sym->getName() == MP.DSOHandleSymbol;
843 assert(
I !=
G.defined_symbols().end() &&
"Missing DSO handle symbol");
845 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
846 auto HandleAddr = (*I)->getAddress();
847 MP.HandleAddrToJITDylib[HandleAddr] = &JD;
848 MP.JITDylibToHandleAddr[&JD] = HandleAddr;
850 G.allocActions().push_back(
852 SPSArgList<SPSString, SPSExecutorAddr>>(
853 MP.RegisterJITDylib.Addr, JD.getName(), HandleAddr)),
855 MP.DeregisterJITDylib.Addr, HandleAddr))});
861void ELFNixPlatform::ELFNixPlatformPlugin::addEHAndTLVSupportPasses(
863 bool IsBootstrapping) {
872 return fixTLVSectionsAndEdges(G, JD);
878 jitlink::LinkGraph &
G) ->
Error {
879 ELFPerObjectSectionsToRegister POSR;
882 jitlink::SectionRange
R(*EHFrameSection);
889 jitlink::Section *ThreadDataSection =
897 if (ThreadDataSection)
898 G.mergeSections(*ThreadDataSection, *ThreadBSSSection);
900 ThreadDataSection = ThreadBSSSection;
905 if (ThreadDataSection) {
906 jitlink::SectionRange
R(*ThreadDataSection);
912 if (
auto Err = MP.registerPerObjectSections(
G, POSR, IsBootstrapping))
920Error ELFNixPlatform::ELFNixPlatformPlugin::preserveInitSections(
921 jitlink::LinkGraph &
G, MaterializationResponsibility &MR) {
925 jitlink::Symbol *InitSym =
nullptr;
927 for (
auto &InitSection :
G.sections()) {
936 auto &
B = **InitSection.blocks().begin();
937 InitSym = &
G.addDefinedSymbol(
943 for (
auto *
B : InitSection.blocks()) {
947 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
953 for (
auto &FiniSection :
G.sections()) {
961 auto &
B = **FiniSection.blocks().begin();
962 InitSym = &
G.addDefinedSymbol(
968 for (
auto *
B : FiniSection.blocks()) {
972 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
981Error ELFNixPlatform::ELFNixPlatformPlugin::registerInitSections(
982 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
987 for (
auto &Sec :
G.sections())
994 auto getInitSectionInfo =
995 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
996 StringRef
Name = Sec->getName();
997 if (
Name.starts_with(
".init_array")) {
998 StringRef PrioStr =
Name;
1002 return {0, Prio, HasPrio};
1004 if (
Name.starts_with(
".init"))
1005 return {1, 0,
false};
1006 if (
Name.starts_with(
".ctors")) {
1007 StringRef PrioStr =
Name;
1011 return {2, Prio, HasPrio};
1013 return {3, 0,
false};
1022 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
1023 auto [LType, LPrio, LHasPrio] = getInitSectionInfo(
LHS);
1024 auto [RType, RPrio, RHasPrio] = getInitSectionInfo(
RHS);
1027 return LType < RType;
1033 if (LHasPrio && RHasPrio)
1034 return LPrio < RPrio;
1039 }
else if (LType == 2) {
1042 if (LHasPrio && RHasPrio)
1043 return LPrio > RPrio;
1052 for (
auto &Sec : OrderedInitSections)
1053 ELFNixPlatformSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1057 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" init sections:\n";
1058 for (
auto &Sec :
G.sections()) {
1059 jitlink::SectionRange
R(Sec);
1060 dbgs() <<
" " << Sec.getName() <<
": " <<
R.getRange() <<
"\n";
1064 ExecutorAddr HeaderAddr;
1066 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1067 auto I = MP.JITDylibToHandleAddr.find(&JD);
1068 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1069 assert(
I->second &&
"Null header registered for JD");
1070 HeaderAddr =
I->second;
1073 using SPSRegisterInitSectionsArgs =
1074 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1077 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1078 &MP.RegisterInitSections, &MP.DeregisterInitSections,
1079 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1080 ELFNixPlatformSecs),
1081 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1082 ELFNixPlatformSecs));
1086 G.allocActions().push_back(
1088 MP.RegisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs)),
1090 MP.DeregisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs))});
1095Error ELFNixPlatform::ELFNixPlatformPlugin::registerFiniSections(
1096 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
1101 for (
auto &Sec :
G.sections())
1108 auto getFiniSectionInfo =
1109 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
1110 StringRef
Name = Sec->getName();
1111 if (
Name.starts_with(
".dtors")) {
1112 StringRef PrioStr =
Name;
1116 return {0, Prio, HasPrio};
1118 if (
Name.starts_with(
".fini"))
1119 if (!
Name.starts_with(
".fini_array"))
1120 return {1, 0,
false};
1121 if (
Name.starts_with(
".fini_array")) {
1122 StringRef PrioStr =
Name;
1126 return {2, Prio, HasPrio};
1128 return {3, 0,
false};
1136 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
1137 auto [LType, LPrio, LHasPrio] = getFiniSectionInfo(
LHS);
1138 auto [RType, RPrio, RHasPrio] = getFiniSectionInfo(
RHS);
1141 return LType < RType;
1147 if (LHasPrio && RHasPrio)
1148 return LPrio < RPrio;
1153 }
else if (LType == 2) {
1156 if (LHasPrio && RHasPrio)
1157 return LPrio > RPrio;
1166 for (
auto *Sec : OrderedFiniSections)
1167 ELFNixFiniSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1169 if (ELFNixFiniSecs.
empty())
1174 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" fini sections:\n";
1175 for (
auto *Sec : OrderedFiniSections) {
1176 jitlink::SectionRange
R(*Sec);
1177 dbgs() <<
" " << Sec->getName() <<
": " <<
R.getRange() <<
"\n";
1181 ExecutorAddr HeaderAddr;
1183 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1184 auto I = MP.JITDylibToHandleAddr.find(&JD);
1185 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1186 assert(
I->second &&
"Null header registered for JD");
1187 HeaderAddr =
I->second;
1190 using SPSRegisterFiniSectionsArgs =
1191 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1194 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1195 &MP.RegisterFiniSections, &MP.DeregisterFiniSections,
1196 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1198 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1203 G.allocActions().push_back(
1205 MP.RegisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs)),
1207 MP.DeregisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs))});
1212Error ELFNixPlatform::ELFNixPlatformPlugin::fixTLVSectionsAndEdges(
1213 jitlink::LinkGraph &
G, JITDylib &JD) {
1214 auto TLSGetAddrSymbolName =
G.intern(
"__tls_get_addr");
1215 auto TLSDescResolveSymbolName =
G.intern(
"__tlsdesc_resolver");
1216 auto TLSGetOffsetSymbolName =
G.intern(
"__tls_get_offset");
1217 for (
auto *Sym :
G.external_symbols()) {
1218 if (Sym->getName() == TLSGetAddrSymbolName) {
1220 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_addr");
1221 Sym->setName(std::move(TLSGetAddr));
1222 }
else if (Sym->getName() == TLSDescResolveSymbolName) {
1224 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tlsdesc_resolver");
1225 Sym->setName(std::move(TLSGetAddr));
1226 }
else if (Sym->getName() == TLSGetOffsetSymbolName) {
1228 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_offset");
1229 Sym->setName(std::move(TLSGetAddr));
1233 auto *TLSInfoEntrySection =
G.findSectionByName(
"$__TLSINFO");
1235 if (TLSInfoEntrySection) {
1236 std::optional<uint64_t>
Key;
1238 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1239 auto I = MP.JITDylibToPThreadKey.find(&JD);
1240 if (
I != MP.JITDylibToPThreadKey.end())
1244 if (
auto KeyOrErr = MP.createPThreadKey())
1247 return KeyOrErr.takeError();
1250 for (
auto *
B : TLSInfoEntrySection->blocks()) {
1253 assert(
B->getSize() == (
G.getPointerSize() * 2) &&
1254 "TLS descriptor must be 2 words length");
1255 auto TLSInfoEntryContent =
B->getMutableContent(
G);
1256 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.
Base class for specs that bind handlers for calls with the SPS signature SPSSigT.
#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.
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
ExecutionSession::CallControllerHandlerBinding bindCallControllerHandler(HandlerT &&H, SymbolLookupFlags LF=SymbolLookupFlags::RequiredSymbol)
Bind H, using the given spec, to the tag with the spec's default name.
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
static constexpr SymbolNameSpec Name
static constexpr SymbolNameSpec Name