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);
237 ES.getBootstrapJITDylib(),
238 {{ES.intern(rt::DispatchName), ES.intern(rt::DispatchCtxName)}});
240 return Exports.takeError();
242 PlatformJD.define(
reexports(ES.getBootstrapJITDylib(), *Exports)))
249 ObjLinkingLayer, PlatformJD, std::move(OrcRuntime), Err));
251 return std::move(Err);
257 JITDylib &PlatformJD,
const char *OrcRuntimePath,
258 std::optional<SymbolAliasMap> RuntimeAliases) {
261 auto OrcRuntimeArchiveGenerator =
263 if (!OrcRuntimeArchiveGenerator)
264 return OrcRuntimeArchiveGenerator.takeError();
266 return Create(ObjLinkingLayer, PlatformJD,
267 std::move(*OrcRuntimeArchiveGenerator),
268 std::move(RuntimeAliases));
272 if (
auto Err = JD.
define(std::make_unique<DSOHandleMaterializationUnit>(
273 *
this, DSOHandleSymbol)))
276 return ES.lookup({&JD}, DSOHandleSymbol).takeError();
280 std::lock_guard<std::mutex> Lock(PlatformMutex);
281 auto I = JITDylibToHandleAddr.find(&JD);
282 if (
I != JITDylibToHandleAddr.end()) {
283 assert(HandleAddrToJITDylib.count(
I->second) &&
284 "HandleAddrToJITDylib missing entry");
285 HandleAddrToJITDylib.erase(
I->second);
286 JITDylibToHandleAddr.erase(
I);
299 RegisteredInitSymbols[&JD].add(InitSym,
302 dbgs() <<
"ELFNixPlatform: Registered init symbol " << *InitSym
303 <<
" for MU " << MU.
getName() <<
"\n";
313 ArrayRef<std::pair<const char *, const char *>> AL) {
314 for (
auto &KV : AL) {
315 auto AliasName = ES.
intern(KV.first);
316 assert(!Aliases.
count(AliasName) &&
"Duplicate symbol name in alias map");
317 Aliases[std::move(AliasName)] = {ES.
intern(KV.second),
334 static const std::pair<const char *, const char *> RequiredCXXAliases[] = {
335 {
"__cxa_atexit",
"__orc_rt_elfnix_cxa_atexit"},
336 {
"atexit",
"__orc_rt_elfnix_atexit"}};
343 static const std::pair<const char *, const char *>
344 StandardRuntimeUtilityAliases[] = {
345 {
"__orc_rt_run_program",
"__orc_rt_elfnix_run_program"},
346 {
"__orc_rt_jit_dlerror",
"__orc_rt_elfnix_jit_dlerror"},
347 {
"__orc_rt_jit_dlopen",
"__orc_rt_elfnix_jit_dlopen"},
348 {
"__orc_rt_jit_dlupdate",
"__orc_rt_elfnix_jit_dlupdate"},
349 {
"__orc_rt_jit_dlclose",
"__orc_rt_elfnix_jit_dlclose"},
350 {
"__orc_rt_jit_dlsym",
"__orc_rt_elfnix_jit_dlsym"},
351 {
"__orc_rt_log_error",
"__orc_rt_log_error_to_stderr"}};
354 StandardRuntimeUtilityAliases);
359 static const std::pair<const char *, const char *>
360 StandardLazyCompilationAliases[] = {
361 {
"__orc_rt_reenter",
"__orc_rt_sysv_reenter"}};
364 StandardLazyCompilationAliases);
367bool ELFNixPlatform::supportedTarget(
const Triple &TT) {
368 switch (TT.getArch()) {
382ELFNixPlatform::ELFNixPlatform(
384 std::unique_ptr<DefinitionGenerator> OrcRuntimeGenerator,
Error &Err)
385 : ES(ObjLinkingLayer.getExecutionSession()), PlatformJD(PlatformJD),
386 ObjLinkingLayer(ObjLinkingLayer),
387 DSOHandleSymbol(ES.intern(
"__dso_handle")) {
389 ObjLinkingLayer.
addPlugin(std::make_unique<ELFNixPlatformPlugin>(*
this));
391 PlatformJD.
addGenerator(std::move(OrcRuntimeGenerator));
405 if ((Err = ES.lookup(
408 {PlatformBootstrap.Name, PlatformShutdown.Name,
409 RegisterJITDylib.Name, DeregisterJITDylib.Name,
410 RegisterInitSections.Name, DeregisterInitSections.Name,
411 RegisterFiniSections.Name, DeregisterFiniSections.Name,
412 RegisterObjectSections.Name,
413 DeregisterObjectSections.Name, CreatePThreadKey.Name}))
419 std::unique_lock<std::mutex> Lock(BI.Mutex);
420 BI.CV.wait(Lock, [&]() {
return BI.ActiveGraphs == 0; });
425 auto BootstrapCompleteSymbol =
426 ES.intern(
"__orc_rt_elfnix_complete_bootstrap");
427 if ((Err = PlatformJD.define(
428 std::make_unique<ELFNixPlatformCompleteBootstrapMaterializationUnit>(
429 *
this, PlatformJD.getName(), BootstrapCompleteSymbol,
430 std::move(BI.DeferredRTFnMap), BI.ELFNixHeaderAddr,
431 PlatformBootstrap.Addr, PlatformShutdown.Addr,
432 RegisterJITDylib.Addr, DeregisterJITDylib.Addr))))
436 std::move(BootstrapCompleteSymbol))
441 if (
auto E2 = associateRuntimeSupportFunctions(PlatformJD)) {
447Error ELFNixPlatform::associateRuntimeSupportFunctions(
JITDylib &PlatformJD) {
450 using RecordInitializersSPSSig =
451 SPSExpected<SPSELFNixJITDylibDepInfoMap>(SPSExecutorAddr);
452 WFs[ES.intern(
"__orc_rt_elfnix_push_initializers_tag")] =
453 ES.wrapAsyncWithSPS<RecordInitializersSPSSig>(
454 this, &ELFNixPlatform::rt_recordInitializers);
456 using LookupSymbolSPSSig =
457 SPSExpected<SPSExecutorAddr>(SPSExecutorAddr,
SPSString);
458 WFs[ES.intern(
"__orc_rt_elfnix_symbol_lookup_tag")] =
459 ES.wrapAsyncWithSPS<LookupSymbolSPSSig>(
this,
460 &ELFNixPlatform::rt_lookupSymbol);
462 return ES.registerJITDispatchHandlers(PlatformJD, std::move(WFs));
465void ELFNixPlatform::pushInitializersLoop(
466 PushInitializersSendResultFn SendResult,
JITDylibSP JD) {
467 DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols;
468 DenseMap<JITDylib *, SmallVector<JITDylib *>> JDDepMap;
471 ES.runSessionLocked([&]() {
472 while (!Worklist.empty()) {
475 auto DepJD = Worklist.back();
484 auto &
DM = It->second;
487 if (KV.first == DepJD)
489 DM.push_back(KV.first);
490 Worklist.push_back(KV.first);
495 auto RISItr = RegisteredInitSymbols.find(DepJD);
496 if (RISItr != RegisteredInitSymbols.end()) {
497 NewInitSymbols[DepJD] = std::move(RISItr->second);
498 RegisteredInitSymbols.erase(RISItr);
505 if (NewInitSymbols.
empty()) {
511 DenseMap<JITDylib *, ExecutorAddr> HeaderAddrs;
514 std::lock_guard<std::mutex> Lock(PlatformMutex);
515 for (
auto &KV : JDDepMap) {
516 auto I = JITDylibToHandleAddr.find(KV.first);
517 if (
I != JITDylibToHandleAddr.end())
518 HeaderAddrs[KV.first] =
I->second;
524 DIM.reserve(JDDepMap.size());
525 for (
auto &KV : JDDepMap) {
526 auto HI = HeaderAddrs.
find(KV.first);
528 if (HI == HeaderAddrs.
end())
532 for (
auto &Dep : KV.second) {
533 auto HJ = HeaderAddrs.
find(Dep);
534 if (HJ != HeaderAddrs.
end())
535 DepInfo.push_back(HJ->second);
537 DIM.push_back(std::make_pair(
H, std::move(DepInfo)));
545 [
this, SendResult = std::move(SendResult), JD](
Error Err)
mutable {
547 SendResult(std::move(Err));
549 pushInitializersLoop(std::move(SendResult), JD);
551 ES, std::move(NewInitSymbols));
554void ELFNixPlatform::rt_recordInitializers(
555 PushInitializersSendResultFn SendResult,
ExecutorAddr JDHeaderAddr) {
558 std::lock_guard<std::mutex> Lock(PlatformMutex);
559 auto I = HandleAddrToJITDylib.find(JDHeaderAddr);
560 if (
I != HandleAddrToJITDylib.end())
565 dbgs() <<
"ELFNixPlatform::rt_recordInitializers(" << JDHeaderAddr <<
") ";
567 dbgs() <<
"pushing initializers for " << JD->
getName() <<
"\n";
569 dbgs() <<
"No JITDylib for header address.\n";
574 formatv(
"{0:x}", JDHeaderAddr),
579 pushInitializersLoop(std::move(SendResult), JD);
582void ELFNixPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult,
584 StringRef SymbolName) {
586 dbgs() <<
"ELFNixPlatform::rt_lookupSymbol(\"" << Handle <<
"\")\n";
589 JITDylib *JD =
nullptr;
592 std::lock_guard<std::mutex> Lock(PlatformMutex);
593 auto I = HandleAddrToJITDylib.find(Handle);
594 if (
I != HandleAddrToJITDylib.end())
599 LLVM_DEBUG(
dbgs() <<
" No JITDylib for handle " << Handle <<
"\n");
607 class RtLookupNotifyComplete {
609 RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult)
610 : SendResult(std::
move(SendResult)) {}
611 void operator()(Expected<SymbolMap>
Result) {
613 assert(
Result->size() == 1 &&
"Unexpected result map count");
614 SendResult(
Result->begin()->second.getAddress());
616 SendResult(
Result.takeError());
621 SendSymbolAddressFn SendResult;
630Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineStart(
631 jitlink::LinkGraph &
G) {
633 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
634 ++MP.Bootstrap.load()->ActiveGraphs;
638Error ELFNixPlatform::ELFNixPlatformPlugin::
639 bootstrapPipelineRecordRuntimeFunctions(jitlink::LinkGraph &
G) {
641 std::pair<StringRef, ExecutorAddr *> RuntimeSymbols[] = {
642 {*MP.DSOHandleSymbol, &MP.Bootstrap.load()->ELFNixHeaderAddr},
643 {*MP.PlatformBootstrap.Name, &MP.PlatformBootstrap.Addr},
644 {*MP.PlatformShutdown.Name, &MP.PlatformShutdown.Addr},
645 {*MP.RegisterJITDylib.Name, &MP.RegisterJITDylib.Addr},
646 {*MP.DeregisterJITDylib.Name, &MP.DeregisterJITDylib.Addr},
647 {*MP.RegisterObjectSections.Name, &MP.RegisterObjectSections.Addr},
648 {*MP.DeregisterObjectSections.Name, &MP.DeregisterObjectSections.Addr},
649 {*MP.RegisterInitSections.Name, &MP.RegisterInitSections.Addr},
650 {*MP.DeregisterInitSections.Name, &MP.DeregisterInitSections.Addr},
651 {*MP.RegisterFiniSections.Name, &MP.RegisterFiniSections.Addr},
652 {*MP.DeregisterFiniSections.Name, &MP.DeregisterFiniSections.Addr},
653 {*MP.CreatePThreadKey.Name, &MP.CreatePThreadKey.Addr}};
655 bool RegisterELFNixHeader =
false;
657 for (
auto *Sym :
G.defined_symbols()) {
658 for (
auto &RTSym : RuntimeSymbols) {
659 if (Sym->hasName() && *Sym->getName() == RTSym.first) {
662 "Duplicate " + RTSym.first +
663 " detected during ELFNixPlatform bootstrap",
666 if (*Sym->getName() == *MP.DSOHandleSymbol)
667 RegisterELFNixHeader =
true;
669 *RTSym.second = Sym->getAddress();
674 if (RegisterELFNixHeader) {
677 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
678 MP.JITDylibToHandleAddr[&MP.PlatformJD] =
679 MP.Bootstrap.load()->ELFNixHeaderAddr;
680 MP.HandleAddrToJITDylib[MP.Bootstrap.load()->ELFNixHeaderAddr] =
687Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineEnd(
688 jitlink::LinkGraph &
G) {
689 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
690 assert(MP.Bootstrap &&
"DeferredAAs reset before bootstrap completed");
691 --MP.Bootstrap.load()->ActiveGraphs;
694 if (MP.Bootstrap.load()->ActiveGraphs == 0)
695 MP.Bootstrap.load()->CV.notify_all();
699Error ELFNixPlatform::registerPerObjectSections(
700 jitlink::LinkGraph &
G,
const ELFPerObjectSectionsToRegister &POSR,
701 bool IsBootstrapping) {
702 using SPSRegisterPerObjSectionsArgs =
703 SPSArgList<SPSELFPerObjectSectionsToRegister>;
706 Bootstrap.load()->addArgumentsToRTFnMap(
707 &RegisterObjectSections, &DeregisterObjectSections,
708 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR),
709 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR));
713 G.allocActions().push_back(
715 RegisterObjectSections.Addr, POSR)),
717 DeregisterObjectSections.Addr, POSR))});
722Expected<uint64_t> ELFNixPlatform::createPThreadKey() {
723 if (!CreatePThreadKey.Addr)
725 "Attempting to create pthread key in target, but runtime support has "
726 "not been loaded yet",
729 Expected<uint64_t>
Result(0);
730 if (
auto Err = ES.callSPSWrapper<SPSExpected<uint64_t>(
void)>(
731 CreatePThreadKey.Addr,
Result))
732 return std::move(Err);
736void ELFNixPlatform::ELFNixPlatformPlugin::modifyPassConfig(
737 MaterializationResponsibility &MR, jitlink::LinkGraph &LG,
738 jitlink::PassConfiguration &Config) {
739 using namespace jitlink;
741 bool InBootstrapPhase =
745 if (InBootstrapPhase) {
747 [
this](LinkGraph &
G) {
return bootstrapPipelineStart(
G); });
749 return bootstrapPipelineRecordRuntimeFunctions(
G);
756 if (InitSymbol == MP.DSOHandleSymbol && !InBootstrapPhase) {
757 addDSOHandleSupportPasses(MR, Config);
765 [
this, &MR](jitlink::LinkGraph &
G) ->
Error {
766 if (
auto Err = preserveInitSections(
G, MR))
773 addEHAndTLVSupportPasses(MR, Config, InBootstrapPhase);
777 InBootstrapPhase](jitlink::LinkGraph &
G) {
778 return registerInitSections(G, JD, InBootstrapPhase);
783 InBootstrapPhase](jitlink::LinkGraph &
G) {
784 return registerFiniSections(G, JD, InBootstrapPhase);
789 if (InBootstrapPhase)
791 [
this](LinkGraph &
G) {
return bootstrapPipelineEnd(
G); });
794void ELFNixPlatform::ELFNixPlatformPlugin::addDSOHandleSupportPasses(
795 MaterializationResponsibility &MR, jitlink::PassConfiguration &Config) {
798 jitlink::LinkGraph &
G) ->
Error {
799 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
800 return Sym->getName() == MP.DSOHandleSymbol;
802 assert(
I !=
G.defined_symbols().end() &&
"Missing DSO handle symbol");
804 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
805 auto HandleAddr = (*I)->getAddress();
806 MP.HandleAddrToJITDylib[HandleAddr] = &JD;
807 MP.JITDylibToHandleAddr[&JD] = HandleAddr;
809 G.allocActions().push_back(
811 SPSArgList<SPSString, SPSExecutorAddr>>(
812 MP.RegisterJITDylib.Addr, JD.getName(), HandleAddr)),
814 MP.DeregisterJITDylib.Addr, HandleAddr))});
820void ELFNixPlatform::ELFNixPlatformPlugin::addEHAndTLVSupportPasses(
822 bool IsBootstrapping) {
831 return fixTLVSectionsAndEdges(G, JD);
837 jitlink::LinkGraph &
G) ->
Error {
838 ELFPerObjectSectionsToRegister POSR;
841 jitlink::SectionRange
R(*EHFrameSection);
848 jitlink::Section *ThreadDataSection =
856 if (ThreadDataSection)
857 G.mergeSections(*ThreadDataSection, *ThreadBSSSection);
859 ThreadDataSection = ThreadBSSSection;
864 if (ThreadDataSection) {
865 jitlink::SectionRange
R(*ThreadDataSection);
871 if (
auto Err = MP.registerPerObjectSections(
G, POSR, IsBootstrapping))
879Error ELFNixPlatform::ELFNixPlatformPlugin::preserveInitSections(
880 jitlink::LinkGraph &
G, MaterializationResponsibility &MR) {
884 jitlink::Symbol *InitSym =
nullptr;
886 for (
auto &InitSection :
G.sections()) {
895 auto &
B = **InitSection.blocks().begin();
896 InitSym = &
G.addDefinedSymbol(
902 for (
auto *
B : InitSection.blocks()) {
906 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
912 for (
auto &FiniSection :
G.sections()) {
920 auto &
B = **FiniSection.blocks().begin();
921 InitSym = &
G.addDefinedSymbol(
927 for (
auto *
B : FiniSection.blocks()) {
931 auto &S =
G.addAnonymousSymbol(*
B, 0,
B->getSize(),
false,
true);
940Error ELFNixPlatform::ELFNixPlatformPlugin::registerInitSections(
941 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
946 for (
auto &Sec :
G.sections())
953 auto getInitSectionInfo =
954 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
955 StringRef
Name = Sec->getName();
956 if (
Name.starts_with(
".init_array")) {
957 StringRef PrioStr =
Name;
961 return {0, Prio, HasPrio};
963 if (
Name.starts_with(
".init"))
964 return {1, 0,
false};
965 if (
Name.starts_with(
".ctors")) {
966 StringRef PrioStr =
Name;
970 return {2, Prio, HasPrio};
972 return {3, 0,
false};
981 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
982 auto [LType, LPrio, LHasPrio] = getInitSectionInfo(
LHS);
983 auto [RType, RPrio, RHasPrio] = getInitSectionInfo(
RHS);
986 return LType < RType;
992 if (LHasPrio && RHasPrio)
993 return LPrio < RPrio;
998 }
else if (LType == 2) {
1001 if (LHasPrio && RHasPrio)
1002 return LPrio > RPrio;
1011 for (
auto &Sec : OrderedInitSections)
1012 ELFNixPlatformSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1016 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" init sections:\n";
1017 for (
auto &Sec :
G.sections()) {
1018 jitlink::SectionRange
R(Sec);
1019 dbgs() <<
" " << Sec.getName() <<
": " <<
R.getRange() <<
"\n";
1023 ExecutorAddr HeaderAddr;
1025 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1026 auto I = MP.JITDylibToHandleAddr.find(&JD);
1027 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1028 assert(
I->second &&
"Null header registered for JD");
1029 HeaderAddr =
I->second;
1032 using SPSRegisterInitSectionsArgs =
1033 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1036 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1037 &MP.RegisterInitSections, &MP.DeregisterInitSections,
1038 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1039 ELFNixPlatformSecs),
1040 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1041 ELFNixPlatformSecs));
1045 G.allocActions().push_back(
1047 MP.RegisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs)),
1049 MP.DeregisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs))});
1054Error ELFNixPlatform::ELFNixPlatformPlugin::registerFiniSections(
1055 jitlink::LinkGraph &
G, JITDylib &JD,
bool IsBootstrapping) {
1060 for (
auto &Sec :
G.sections())
1067 auto getFiniSectionInfo =
1068 [](
const jitlink::Section *Sec) -> std::tuple<int, uint64_t, bool> {
1069 StringRef
Name = Sec->getName();
1070 if (
Name.starts_with(
".dtors")) {
1071 StringRef PrioStr =
Name;
1075 return {0, Prio, HasPrio};
1077 if (
Name.starts_with(
".fini"))
1078 if (!
Name.starts_with(
".fini_array"))
1079 return {1, 0,
false};
1080 if (
Name.starts_with(
".fini_array")) {
1081 StringRef PrioStr =
Name;
1085 return {2, Prio, HasPrio};
1087 return {3, 0,
false};
1095 [&](
const jitlink::Section *
LHS,
const jitlink::Section *
RHS) {
1096 auto [LType, LPrio, LHasPrio] = getFiniSectionInfo(
LHS);
1097 auto [RType, RPrio, RHasPrio] = getFiniSectionInfo(
RHS);
1100 return LType < RType;
1106 if (LHasPrio && RHasPrio)
1107 return LPrio < RPrio;
1112 }
else if (LType == 2) {
1115 if (LHasPrio && RHasPrio)
1116 return LPrio > RPrio;
1125 for (
auto *Sec : OrderedFiniSections)
1126 ELFNixFiniSecs.
push_back(jitlink::SectionRange(*Sec).getRange());
1128 if (ELFNixFiniSecs.
empty())
1133 dbgs() <<
"ELFNixPlatform: Scraped " <<
G.getName() <<
" fini sections:\n";
1134 for (
auto *Sec : OrderedFiniSections) {
1135 jitlink::SectionRange
R(*Sec);
1136 dbgs() <<
" " << Sec->getName() <<
": " <<
R.getRange() <<
"\n";
1140 ExecutorAddr HeaderAddr;
1142 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1143 auto I = MP.JITDylibToHandleAddr.find(&JD);
1144 assert(
I != MP.JITDylibToHandleAddr.end() &&
"No header registered for JD");
1145 assert(
I->second &&
"Null header registered for JD");
1146 HeaderAddr =
I->second;
1149 using SPSRegisterFiniSectionsArgs =
1150 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1153 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1154 &MP.RegisterFiniSections, &MP.DeregisterFiniSections,
1155 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1157 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1162 G.allocActions().push_back(
1164 MP.RegisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs)),
1166 MP.DeregisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs))});
1171Error ELFNixPlatform::ELFNixPlatformPlugin::fixTLVSectionsAndEdges(
1172 jitlink::LinkGraph &
G, JITDylib &JD) {
1173 auto TLSGetAddrSymbolName =
G.intern(
"__tls_get_addr");
1174 auto TLSDescResolveSymbolName =
G.intern(
"__tlsdesc_resolver");
1175 auto TLSGetOffsetSymbolName =
G.intern(
"__tls_get_offset");
1176 for (
auto *Sym :
G.external_symbols()) {
1177 if (Sym->getName() == TLSGetAddrSymbolName) {
1179 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_addr");
1180 Sym->setName(std::move(TLSGetAddr));
1181 }
else if (Sym->getName() == TLSDescResolveSymbolName) {
1183 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tlsdesc_resolver");
1184 Sym->setName(std::move(TLSGetAddr));
1185 }
else if (Sym->getName() == TLSGetOffsetSymbolName) {
1187 MP.getExecutionSession().intern(
"___orc_rt_elfnix_tls_get_offset");
1188 Sym->setName(std::move(TLSGetAddr));
1192 auto *TLSInfoEntrySection =
G.findSectionByName(
"$__TLSINFO");
1194 if (TLSInfoEntrySection) {
1195 std::optional<uint64_t>
Key;
1197 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1198 auto I = MP.JITDylibToPThreadKey.find(&JD);
1199 if (
I != MP.JITDylibToPThreadKey.end())
1203 if (
auto KeyOrErr = MP.createPThreadKey())
1206 return KeyOrErr.takeError();
1209 uint64_t PlatformKeyBits =
1212 for (
auto *
B : TLSInfoEntrySection->blocks()) {
1215 assert(
B->getSize() == (
G.getPointerSize() * 2) &&
1216 "TLS descriptor must be 2 words length");
1217 auto TLSInfoEntryContent =
B->getMutableContent(
G);
1218 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.
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)
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