LLVM 24.0.0git
ELFNixPlatform.cpp
Go to the documentation of this file.
1//===----- ELFNixPlatform.cpp - Utilities for executing ELFNix in Orc -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/Endian.h"
25#include <optional>
26
27#define DEBUG_TYPE "orc"
28
29using namespace llvm;
30using namespace llvm::orc;
31using namespace llvm::orc::shared;
32
33// Controller-interface descriptors for the ELFNix platform runtime's SPS
34// wrapper calls.
37 static constexpr SymbolNameSpec Name =
38 SymbolNameSpec::c("__orc_rt_elfnix_create_pthread_key");
40};
41} // namespace llvm::orc::elfnix_sps_ci
42
43namespace {
44
45template <typename SPSSerializer, typename... ArgTs>
47getArgDataBufferType(const ArgTs &...Args) {
49 ArgData.resize(SPSSerializer::size(Args...));
50 SPSOutputBuffer OB(ArgData.empty() ? nullptr : ArgData.data(),
51 ArgData.size());
52 if (SPSSerializer::serialize(OB, Args...))
53 return ArgData;
54 return {};
55}
56
57std::unique_ptr<jitlink::LinkGraph> createPlatformGraph(ELFNixPlatform &MOP,
58 std::string Name) {
59 auto &ES = MOP.getExecutionSession();
60 return std::make_unique<jitlink::LinkGraph>(
61 std::move(Name), ES.getSymbolStringPool(), ES.getTargetTriple(),
62 ES.getTargetTriple().getArchPointerBitWidth() / 8, SubtargetFeatures(),
64}
65
66// Creates a Bootstrap-Complete LinkGraph to run deferred actions.
67class ELFNixPlatformCompleteBootstrapMaterializationUnit
68 : public MaterializationUnit {
69public:
70 ELFNixPlatformCompleteBootstrapMaterializationUnit(
71 ELFNixPlatform &MOP, StringRef PlatformJDName,
72 SymbolStringPtr CompleteBootstrapSymbol, DeferredRuntimeFnMap DeferredAAs,
73 ExecutorAddr ELFNixHeaderAddr, ExecutorAddr PlatformBootstrap,
74 ExecutorAddr PlatformShutdown, ExecutorAddr RegisterJITDylib,
75 ExecutorAddr DeregisterJITDylib)
76 : MaterializationUnit(
77 {{{CompleteBootstrapSymbol, JITSymbolFlags::None}}, nullptr}),
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) {}
85
86 StringRef getName() const override {
87 return "ELFNixPlatformCompleteBootstrap";
88 }
89
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);
99
100 // 1. Bootstrap the platform support code.
101 G->allocActions().push_back(
102 {cantFail(WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>(
103 PlatformBootstrap, ELFNixHeaderAddr)),
104 cantFail(
105 WrapperFunctionCall::Create<SPSArgList<>>(PlatformShutdown))});
106
107 // 2. Register the platform JITDylib.
108 G->allocActions().push_back(
110 SPSArgList<SPSString, SPSExecutorAddr>>(
111 RegisterJITDylib, PlatformJDName, ELFNixHeaderAddr)),
112 cantFail(WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>(
113 DeregisterJITDylib, ELFNixHeaderAddr))});
114
115 // 4. Add the deferred actions to the graph.
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))});
121 }
122 }
123
124 MOP.getObjectLinkingLayer().emit(std::move(R), std::move(G));
125 }
126
127 void discard(const JITDylib &JD, const SymbolStringPtr &Sym) override {}
128
129private:
130 ELFNixPlatform &MOP;
131 StringRef PlatformJDName;
132 SymbolStringPtr CompleteBootstrapSymbol;
133 DeferredRuntimeFnMap DeferredAAsMap;
134 ExecutorAddr ELFNixHeaderAddr;
135 ExecutorAddr PlatformBootstrap;
136 ExecutorAddr PlatformShutdown;
137 ExecutorAddr RegisterJITDylib;
138 ExecutorAddr DeregisterJITDylib;
139};
140
141class DSOHandleMaterializationUnit : public MaterializationUnit {
142public:
143 DSOHandleMaterializationUnit(ELFNixPlatform &ENP,
144 const SymbolStringPtr &DSOHandleSymbol)
145 : MaterializationUnit(
146 createDSOHandleSectionInterface(ENP, DSOHandleSymbol)),
147 ENP(ENP) {}
148
149 StringRef getName() const override { return "DSOHandleMU"; }
150
151 void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
152
153 auto &ES = ENP.getExecutionSession();
154
155 jitlink::Edge::Kind EdgeKind;
156 unsigned PointerSize = ES.getTargetTriple().getArchPointerBitWidth() / 8;
157
158 switch (ES.getTargetTriple().getArch()) {
159 case Triple::x86_64:
161 break;
162 case Triple::aarch64:
164 break;
165 case Triple::ppc64:
166 EdgeKind = jitlink::ppc64::Pointer64;
167 break;
168 case Triple::ppc64le:
169 EdgeKind = jitlink::ppc64::Pointer64;
170 break;
173 break;
174 case Triple::mips:
175 case Triple::mipsel:
176 EdgeKind = jitlink::mips::Pointer32;
177 break;
178 case Triple::mips64:
179 case Triple::mips64el:
180 if (ES.getTargetTriple().isABIN32()) {
181 EdgeKind = jitlink::mips::Pointer32;
182 PointerSize = 4;
183 } else
184 EdgeKind = jitlink::mips::Pointer64;
185 break;
186 case Triple::systemz:
188 break;
189 default:
190 llvm_unreachable("Unrecognized architecture");
191 }
192
193 // void *__dso_handle = &__dso_handle;
194 auto G = std::make_unique<jitlink::LinkGraph>(
195 "<DSOHandleMU>", ES.getSymbolStringPool(), ES.getTargetTriple(),
196 PointerSize, SubtargetFeatures(), jitlink::getGenericEdgeKindName);
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);
206
207 ENP.getObjectLinkingLayer().emit(std::move(R), std::move(G));
208 }
209
210 void discard(const JITDylib &JD, const SymbolStringPtr &Sym) override {}
211
212private:
213 static MaterializationUnit::Interface
214 createDSOHandleSectionInterface(ELFNixPlatform &ENP,
215 const SymbolStringPtr &DSOHandleSymbol) {
217 SymbolFlags[DSOHandleSymbol] = JITSymbolFlags::Exported;
218 return MaterializationUnit::Interface(std::move(SymbolFlags),
219 DSOHandleSymbol);
220 }
221
222 ArrayRef<char> getDSOHandleContent(size_t PointerSize) {
223 static const char Content[8] = {0};
224 assert(PointerSize <= sizeof Content);
225 return {Content, PointerSize};
226 }
227
228 ELFNixPlatform &ENP;
229};
230
231} // end anonymous namespace
232
233namespace llvm {
234namespace orc {
235
236Expected<std::unique_ptr<ELFNixPlatform>>
238 JITDylib &PlatformJD,
239 std::unique_ptr<DefinitionGenerator> OrcRuntime,
240 std::optional<SymbolAliasMap> RuntimeAliases) {
241
242 auto &ES = ObjLinkingLayer.getExecutionSession();
243
244 // If the target is not supported then bail out immediately.
245 if (!supportedTarget(ES.getTargetTriple()))
246 return make_error<StringError>("Unsupported ELFNixPlatform triple: " +
247 ES.getTargetTriple().str(),
249
250 // Create default aliases if the caller didn't supply any.
251 if (!RuntimeAliases) {
252 auto StandardRuntimeAliases = standardPlatformAliases(ES, PlatformJD);
253 if (!StandardRuntimeAliases)
254 return StandardRuntimeAliases.takeError();
255 RuntimeAliases = std::move(*StandardRuntimeAliases);
256 }
257
258 // Define the aliases.
259 if (auto Err = PlatformJD.define(symbolAliases(std::move(*RuntimeAliases))))
260 return std::move(Err);
261
262 {
263 // Add JIT dispatch reexports from bootstrap JITDylib.
264 MangleAndInterner Mangle(ES);
265 auto Exports = buildSimpleReexportsAliasMap(
266 ES.getBootstrapJITDylib(),
267 {{Mangle(rt::DispatchName), Mangle(rt::DispatchCtxName)}});
268 if (!Exports)
269 return Exports.takeError();
270 if (auto Err =
271 PlatformJD.define(reexports(ES.getBootstrapJITDylib(), *Exports)))
272 return Err;
273 }
274
275 // Create the instance.
276 Error Err = Error::success();
277 auto P = std::unique_ptr<ELFNixPlatform>(new ELFNixPlatform(
278 ObjLinkingLayer, PlatformJD, std::move(OrcRuntime), Err));
279 if (Err)
280 return std::move(Err);
281 return std::move(P);
282}
283
286 JITDylib &PlatformJD, const char *OrcRuntimePath,
287 std::optional<SymbolAliasMap> RuntimeAliases) {
288
289 // Create a generator for the ORC runtime archive.
290 auto OrcRuntimeArchiveGenerator =
291 StaticLibraryDefinitionGenerator::Load(ObjLinkingLayer, OrcRuntimePath);
292 if (!OrcRuntimeArchiveGenerator)
293 return OrcRuntimeArchiveGenerator.takeError();
294
295 return Create(ObjLinkingLayer, PlatformJD,
296 std::move(*OrcRuntimeArchiveGenerator),
297 std::move(RuntimeAliases));
298}
299
301 if (auto Err = JD.define(std::make_unique<DSOHandleMaterializationUnit>(
302 *this, DSOHandleSymbol)))
303 return Err;
304
305 return ES.lookup({&JD}, DSOHandleSymbol).takeError();
306}
307
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);
316 }
317 return Error::success();
318}
319
321 const MaterializationUnit &MU) {
322
323 auto &JD = RT.getJITDylib();
324 const auto &InitSym = MU.getInitializerSymbol();
325 if (!InitSym)
326 return Error::success();
327
328 RegisteredInitSymbols[&JD].add(InitSym,
330 LLVM_DEBUG({
331 dbgs() << "ELFNixPlatform: Registered init symbol " << *InitSym
332 << " for MU " << MU.getName() << "\n";
333 });
334 return Error::success();
335}
336
340
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),
348 }
349}
350
353 JITDylib &PlatformJD) {
354 SymbolAliasMap Aliases;
355 addAliases(ES, Aliases, requiredCXXAliases());
358 return Aliases;
359}
360
363 static const std::pair<const char *, const char *> RequiredCXXAliases[] = {
364 {"__cxa_atexit", "__orc_rt_elfnix_cxa_atexit"},
365 {"atexit", "__orc_rt_elfnix_atexit"}};
366
367 return ArrayRef<std::pair<const char *, const char *>>(RequiredCXXAliases);
368}
369
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"}};
381
383 StandardRuntimeUtilityAliases);
384}
385
388 static const std::pair<const char *, const char *>
389 StandardLazyCompilationAliases[] = {
390 {"__orc_rt_reenter", "__orc_rt_sysv_reenter"}};
391
393 StandardLazyCompilationAliases);
394}
395
396bool ELFNixPlatform::supportedTarget(const Triple &TT) {
397 switch (TT.getArch()) {
398 case Triple::x86_64:
399 case Triple::aarch64:
400 // FIXME: jitlink for ppc64 hasn't been well tested, leave it unsupported
401 // right now.
402 case Triple::ppc64le:
404 case Triple::systemz:
405 case Triple::mips:
406 case Triple::mipsel:
407 case Triple::mips64:
408 case Triple::mips64el:
409 return true;
410 default:
411 return false;
412 }
413}
414
415ELFNixPlatform::ELFNixPlatform(
416 ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD,
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));
423
424 PlatformJD.addGenerator(std::move(OrcRuntimeGenerator));
425
426 BootstrapInfo BI;
427 Bootstrap = &BI;
428
429 // PlatformJD hasn't been 'set-up' by the platform yet (since we're creating
430 // the platform now), so set it up.
431 if (auto E2 = setupJITDylib(PlatformJD)) {
432 Err = std::move(E2);
433 return;
434 }
435
436 // Step (2) Request runtime registration functions to trigger
437 // materialization..
438 if ((Err = ES.lookup(
439 makeJITDylibSearchOrder(&PlatformJD),
440 SymbolLookupSet(
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}))
447 .takeError()))
448 return;
449
450 // Step (3) Wait for any incidental linker work to complete.
451 {
452 std::unique_lock<std::mutex> Lock(BI.Mutex);
453 BI.CV.wait(Lock, [&]() { return BI.ActiveGraphs == 0; });
454 Bootstrap = nullptr;
455 }
456
457 // Step (4) Add complete-bootstrap materialization unit and request.
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))))
466 return;
467 if ((Err = ES.lookup(makeJITDylibSearchOrder(
469 std::move(BootstrapCompleteSymbol))
470 .takeError()))
471 return;
472
473 // Associate wrapper function tags with JIT-side function implementations.
474 if (auto E2 = associateRuntimeSupportFunctions(PlatformJD)) {
475 Err = std::move(E2);
476 return;
477 }
478}
479
480Error ELFNixPlatform::associateRuntimeSupportFunctions(JITDylib &PlatformJD) {
481 using RecordInitializersSPSSig =
482 SPSExpected<SPSELFNixJITDylibDepInfoMap>(SPSExecutorAddr);
483 using LookupSymbolSPSSig =
484 SPSExpected<SPSExecutorAddr>(SPSExecutorAddr, SPSString);
485
486 return ES.registerCallControllerHandlers(
487 PlatformJD,
489 SymbolNameSpec::c("__orc_rt_elfnix_push_initializers_tag"), this,
490 &ELFNixPlatform::rt_recordInitializers),
492 SymbolNameSpec::c("__orc_rt_elfnix_symbol_lookup_tag"), this,
493 &ELFNixPlatform::rt_lookupSymbol));
494}
495
496void ELFNixPlatform::pushInitializersLoop(
497 PushInitializersSendResultFn SendResult, JITDylibSP JD) {
498 DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols;
499 DenseMap<JITDylib *, SmallVector<JITDylib *>> JDDepMap;
500 SmallVector<JITDylib *, 16> Worklist({JD.get()});
501
502 ES.runSessionLocked([&]() {
503 while (!Worklist.empty()) {
504 // FIXME: Check for defunct dylibs.
505
506 auto DepJD = Worklist.back();
507 Worklist.pop_back();
508
509 // If we've already visited this JITDylib on this iteration then continue.
510 auto [It, Inserted] = JDDepMap.try_emplace(DepJD);
511 if (!Inserted)
512 continue;
513
514 // Add dep info.
515 auto &DM = It->second;
516 DepJD->withLinkOrderDo([&](const JITDylibSearchOrder &O) {
517 for (auto &KV : O) {
518 if (KV.first == DepJD)
519 continue;
520 DM.push_back(KV.first);
521 Worklist.push_back(KV.first);
522 }
523 });
524
525 // Add any registered init symbols.
526 auto RISItr = RegisteredInitSymbols.find(DepJD);
527 if (RISItr != RegisteredInitSymbols.end()) {
528 NewInitSymbols[DepJD] = std::move(RISItr->second);
529 RegisteredInitSymbols.erase(RISItr);
530 }
531 }
532 });
533
534 // If there are no further init symbols to look up then send the link order
535 // (as a list of header addresses) to the caller.
536 if (NewInitSymbols.empty()) {
537
538 // To make the list intelligible to the runtime we need to convert all
539 // JITDylib pointers to their header addresses. Only include JITDylibs
540 // that appear in the JITDylibToHandleAddr map (i.e. those that have been
541 // through setupJITDylib) -- bare JITDylibs aren't managed by the platform.
542 DenseMap<JITDylib *, ExecutorAddr> HeaderAddrs;
543 HeaderAddrs.reserve(JDDepMap.size());
544 {
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;
550 }
551 }
552
553 // Build the dep info map to return.
555 DIM.reserve(JDDepMap.size());
556 for (auto &KV : JDDepMap) {
557 auto HI = HeaderAddrs.find(KV.first);
558 // Skip unmanaged JITDylibs.
559 if (HI == HeaderAddrs.end())
560 continue;
561 auto H = HI->second;
562 ELFNixJITDylibDepInfo DepInfo;
563 for (auto &Dep : KV.second) {
564 auto HJ = HeaderAddrs.find(Dep);
565 if (HJ != HeaderAddrs.end())
566 DepInfo.push_back(HJ->second);
567 }
568 DIM.push_back(std::make_pair(H, std::move(DepInfo)));
569 }
570 SendResult(DIM);
571 return;
572 }
573
574 // Otherwise issue a lookup and re-run this phase when it completes.
576 [this, SendResult = std::move(SendResult), JD](Error Err) mutable {
577 if (Err)
578 SendResult(std::move(Err));
579 else
580 pushInitializersLoop(std::move(SendResult), JD);
581 },
582 ES, std::move(NewInitSymbols));
583}
584
585void ELFNixPlatform::rt_recordInitializers(
586 PushInitializersSendResultFn SendResult, ExecutorAddr JDHeaderAddr) {
587 JITDylibSP JD;
588 {
589 std::lock_guard<std::mutex> Lock(PlatformMutex);
590 auto I = HandleAddrToJITDylib.find(JDHeaderAddr);
591 if (I != HandleAddrToJITDylib.end())
592 JD = I->second;
593 }
594
595 LLVM_DEBUG({
596 dbgs() << "ELFNixPlatform::rt_recordInitializers(" << JDHeaderAddr << ") ";
597 if (JD)
598 dbgs() << "pushing initializers for " << JD->getName() << "\n";
599 else
600 dbgs() << "No JITDylib for header address.\n";
601 });
602
603 if (!JD) {
604 SendResult(make_error<StringError>("No JITDylib with header addr " +
605 formatv("{0:x}", JDHeaderAddr),
607 return;
608 }
609
610 pushInitializersLoop(std::move(SendResult), JD);
611}
612
613void ELFNixPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult,
614 ExecutorAddr Handle,
615 StringRef SymbolName) {
616 LLVM_DEBUG({
617 dbgs() << "ELFNixPlatform::rt_lookupSymbol(\"" << Handle << "\")\n";
618 });
619
620 JITDylib *JD = nullptr;
621
622 {
623 std::lock_guard<std::mutex> Lock(PlatformMutex);
624 auto I = HandleAddrToJITDylib.find(Handle);
625 if (I != HandleAddrToJITDylib.end())
626 JD = I->second;
627 }
628
629 if (!JD) {
630 LLVM_DEBUG(dbgs() << " No JITDylib for handle " << Handle << "\n");
631 SendResult(make_error<StringError>("No JITDylib associated with handle " +
632 formatv("{0:x}", Handle),
634 return;
635 }
636
637 // Use functor class to work around XL build compiler issue on AIX.
638 class RtLookupNotifyComplete {
639 public:
640 RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult)
641 : SendResult(std::move(SendResult)) {}
642 void operator()(Expected<SymbolMap> Result) {
643 if (Result) {
644 assert(Result->size() == 1 && "Unexpected result map count");
645 SendResult(Result->begin()->second.getAddress());
646 } else {
647 SendResult(Result.takeError());
648 }
649 }
650
651 private:
652 SendSymbolAddressFn SendResult;
653 };
654
655 ES.lookup(
657 SymbolLookupSet(ES.intern(SymbolName)), SymbolState::Ready,
658 RtLookupNotifyComplete(std::move(SendResult)), NoDependenciesToRegister);
659}
660
661Error ELFNixPlatform::ELFNixPlatformPlugin::bootstrapPipelineStart(
662 jitlink::LinkGraph &G) {
663 // Increment the active graphs count in BootstrapInfo.
664 std::lock_guard<std::mutex> Lock(MP.Bootstrap.load()->Mutex);
665 ++MP.Bootstrap.load()->ActiveGraphs;
666 return Error::success();
667}
668
669Error ELFNixPlatform::ELFNixPlatformPlugin::
670 bootstrapPipelineRecordRuntimeFunctions(jitlink::LinkGraph &G) {
671 // Record bootstrap function names.
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}};
685
686 bool RegisterELFNixHeader = false;
687
688 for (auto *Sym : G.defined_symbols()) {
689 for (auto &RTSym : RuntimeSymbols) {
690 if (Sym->hasName() && *Sym->getName() == RTSym.first) {
691 if (*RTSym.second)
693 "Duplicate " + RTSym.first +
694 " detected during ELFNixPlatform bootstrap",
696
697 if (*Sym->getName() == *MP.DSOHandleSymbol)
698 RegisterELFNixHeader = true;
699
700 *RTSym.second = Sym->getAddress();
701 }
702 }
703 }
704
705 if (RegisterELFNixHeader) {
706 // If this graph defines the elfnix header symbol then create the internal
707 // mapping between it and PlatformJD.
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] =
712 &MP.PlatformJD;
713 }
714
715 return Error::success();
716}
717
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;
723 // Notify Bootstrap->CV while holding the mutex because the mutex is
724 // also keeping Bootstrap->CV alive.
725 if (MP.Bootstrap.load()->ActiveGraphs == 0)
726 MP.Bootstrap.load()->CV.notify_all();
727 return Error::success();
728}
729
730Error ELFNixPlatform::registerPerObjectSections(
731 jitlink::LinkGraph &G, const ELFPerObjectSectionsToRegister &POSR,
732 bool IsBootstrapping) {
733 using SPSRegisterPerObjSectionsArgs =
734 SPSArgList<SPSELFPerObjectSectionsToRegister>;
735
736 if (LLVM_UNLIKELY(IsBootstrapping)) {
737 Bootstrap.load()->addArgumentsToRTFnMap(
738 &RegisterObjectSections, &DeregisterObjectSections,
739 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR),
740 getArgDataBufferType<SPSRegisterPerObjSectionsArgs>(POSR));
741 return Error::success();
742 }
743
744 G.allocActions().push_back(
746 RegisterObjectSections.Addr, POSR)),
748 DeregisterObjectSections.Addr, POSR))});
749
750 return Error::success();
751}
752
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",
759
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);
766}
767
768void ELFNixPlatform::ELFNixPlatformPlugin::modifyPassConfig(
769 MaterializationResponsibility &MR, jitlink::LinkGraph &LG,
770 jitlink::PassConfiguration &Config) {
771 using namespace jitlink;
772
773 bool InBootstrapPhase =
774 &MR.getTargetJITDylib() == &MP.PlatformJD && MP.Bootstrap;
775
776 // If we're in the bootstrap phase then increment the active graphs.
777 if (InBootstrapPhase) {
778 Config.PrePrunePasses.push_back(
779 [this](LinkGraph &G) { return bootstrapPipelineStart(G); });
780 Config.PostAllocationPasses.push_back([this](LinkGraph &G) {
781 return bootstrapPipelineRecordRuntimeFunctions(G);
782 });
783 }
784
785 // If the initializer symbol is the __dso_handle symbol then just add
786 // the DSO handle support passes.
787 if (auto InitSymbol = MR.getInitializerSymbol()) {
788 if (InitSymbol == MP.DSOHandleSymbol && !InBootstrapPhase) {
789 addDSOHandleSupportPasses(MR, Config);
790 // The DSOHandle materialization unit doesn't require any other
791 // support, so we can bail out early.
792 return;
793 }
794
795 /// Preserve init sections.
796 Config.PrePrunePasses.push_back(
797 [this, &MR](jitlink::LinkGraph &G) -> Error {
798 if (auto Err = preserveInitSections(G, MR))
799 return Err;
800 return Error::success();
801 });
802 }
803
804 // Add passes for eh-frame and TLV support.
805 addEHAndTLVSupportPasses(MR, Config, InBootstrapPhase);
806
807 // If the object contains initializers then add passes to record them.
808 Config.PostFixupPasses.push_back([this, &JD = MR.getTargetJITDylib(),
809 InBootstrapPhase](jitlink::LinkGraph &G) {
810 return registerInitSections(G, JD, InBootstrapPhase);
811 });
812
813 // If the object contains finalizers then add passes to record them.
814 Config.PostFixupPasses.push_back([this, &JD = MR.getTargetJITDylib(),
815 InBootstrapPhase](jitlink::LinkGraph &G) {
816 return registerFiniSections(G, JD, InBootstrapPhase);
817 });
818
819 // If we're in the bootstrap phase then steal allocation actions and then
820 // decrement the active graphs.
821 if (InBootstrapPhase)
822 Config.PostFixupPasses.push_back(
823 [this](LinkGraph &G) { return bootstrapPipelineEnd(G); });
824}
825
826void ELFNixPlatform::ELFNixPlatformPlugin::addDSOHandleSupportPasses(
827 MaterializationResponsibility &MR, jitlink::PassConfiguration &Config) {
828
829 Config.PostAllocationPasses.push_back([this, &JD = MR.getTargetJITDylib()](
830 jitlink::LinkGraph &G) -> Error {
831 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
832 return Sym->getName() == MP.DSOHandleSymbol;
833 });
834 assert(I != G.defined_symbols().end() && "Missing DSO handle symbol");
835 {
836 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
837 auto HandleAddr = (*I)->getAddress();
838 MP.HandleAddrToJITDylib[HandleAddr] = &JD;
839 MP.JITDylibToHandleAddr[&JD] = HandleAddr;
840
841 G.allocActions().push_back(
843 SPSArgList<SPSString, SPSExecutorAddr>>(
844 MP.RegisterJITDylib.Addr, JD.getName(), HandleAddr)),
845 cantFail(WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>(
846 MP.DeregisterJITDylib.Addr, HandleAddr))});
847 }
848 return Error::success();
849 });
850}
851
852void ELFNixPlatform::ELFNixPlatformPlugin::addEHAndTLVSupportPasses(
853 MaterializationResponsibility &MR, jitlink::PassConfiguration &Config,
854 bool IsBootstrapping) {
855
856 // Insert TLV lowering at the start of the PostPrunePasses, since we want
857 // it to run before GOT/PLT lowering.
858
859 // TODO: Check that before the fixTLVSectionsAndEdges pass, the GOT/PLT build
860 // pass has done. Because the TLS descriptor need to be allocate in GOT.
861 Config.PostPrunePasses.push_back(
862 [this, &JD = MR.getTargetJITDylib()](jitlink::LinkGraph &G) {
863 return fixTLVSectionsAndEdges(G, JD);
864 });
865
866 // Add a pass to register the final addresses of the eh-frame and TLV sections
867 // with the runtime.
868 Config.PostFixupPasses.push_back([this, IsBootstrapping](
869 jitlink::LinkGraph &G) -> Error {
870 ELFPerObjectSectionsToRegister POSR;
871
872 if (auto *EHFrameSection = G.findSectionByName(ELFEHFrameSectionName)) {
873 jitlink::SectionRange R(*EHFrameSection);
874 if (!R.empty())
875 POSR.EHFrameSection = R.getRange();
876 }
877
878 // Get a pointer to the thread data section if there is one. It will be used
879 // below.
880 jitlink::Section *ThreadDataSection =
881 G.findSectionByName(ELFThreadDataSectionName);
882
883 // Handle thread BSS section if there is one.
884 if (auto *ThreadBSSSection = G.findSectionByName(ELFThreadBSSSectionName)) {
885 // If there's already a thread data section in this graph then merge the
886 // thread BSS section content into it, otherwise just treat the thread
887 // BSS section as the thread data section.
888 if (ThreadDataSection)
889 G.mergeSections(*ThreadDataSection, *ThreadBSSSection);
890 else
891 ThreadDataSection = ThreadBSSSection;
892 }
893
894 // Having merged thread BSS (if present) and thread data (if present),
895 // record the resulting section range.
896 if (ThreadDataSection) {
897 jitlink::SectionRange R(*ThreadDataSection);
898 if (!R.empty())
899 POSR.ThreadDataSection = R.getRange();
900 }
901
902 if (POSR.EHFrameSection.Start || POSR.ThreadDataSection.Start) {
903 if (auto Err = MP.registerPerObjectSections(G, POSR, IsBootstrapping))
904 return Err;
905 }
906
907 return Error::success();
908 });
909}
910
911Error ELFNixPlatform::ELFNixPlatformPlugin::preserveInitSections(
912 jitlink::LinkGraph &G, MaterializationResponsibility &MR) {
913
914 if (const auto &InitSymName = MR.getInitializerSymbol()) {
915
916 jitlink::Symbol *InitSym = nullptr;
917
918 for (auto &InitSection : G.sections()) {
919 // Skip non-init sections.
920 if (!isELFInitializerSection(InitSection.getName()) ||
921 InitSection.empty())
922 continue;
923
924 // Create the init symbol if it has not been created already and attach it
925 // to the first block.
926 if (!InitSym) {
927 auto &B = **InitSection.blocks().begin();
928 InitSym = &G.addDefinedSymbol(
929 B, 0, *InitSymName, B.getSize(), jitlink::Linkage::Strong,
931 }
932
933 // Add keep-alive edges to anonymous symbols in all other init blocks.
934 for (auto *B : InitSection.blocks()) {
935 if (B == &InitSym->getBlock())
936 continue;
937
938 auto &S = G.addAnonymousSymbol(*B, 0, B->getSize(), false, true);
939 InitSym->getBlock().addEdge(jitlink::Edge::KeepAlive, 0, S, 0);
940 }
941 }
942
943 // Also preserve fini sections (.fini_array, .fini, .dtors)
944 for (auto &FiniSection : G.sections()) {
945 // Skip non-fini sections.
946 if (!isELFFinalizerSection(FiniSection.getName()) || FiniSection.empty())
947 continue;
948
949 // Create the init symbol if it has not been created already and attach it
950 // to the first fini block.
951 if (!InitSym) {
952 auto &B = **FiniSection.blocks().begin();
953 InitSym = &G.addDefinedSymbol(
954 B, 0, *InitSymName, B.getSize(), jitlink::Linkage::Strong,
956 }
957
958 // Add keep-alive edges to anonymous symbols in all fini blocks.
959 for (auto *B : FiniSection.blocks()) {
960 if (B == &InitSym->getBlock())
961 continue;
962
963 auto &S = G.addAnonymousSymbol(*B, 0, B->getSize(), false, true);
964 InitSym->getBlock().addEdge(jitlink::Edge::KeepAlive, 0, S, 0);
965 }
966 }
967 }
968
969 return Error::success();
970}
971
972Error ELFNixPlatform::ELFNixPlatformPlugin::registerInitSections(
973 jitlink::LinkGraph &G, JITDylib &JD, bool IsBootstrapping) {
974 SmallVector<ExecutorAddrRange> ELFNixPlatformSecs;
975 LLVM_DEBUG(dbgs() << "ELFNixPlatform::registerInitSections\n");
976
977 SmallVector<jitlink::Section *> OrderedInitSections;
978 for (auto &Sec : G.sections())
979 if (isELFInitializerSection(Sec.getName()))
980 OrderedInitSections.push_back(&Sec);
981
982 // Helper to get section type and priority for sorting.
983 // Returns: {type_order, priority, has_priority}
984 // type_order: 0 = .init_array, 1 = .init, 2 = .ctors
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;
990 uint64_t Prio = 0;
991 bool HasPrio = PrioStr.consume_front(".init_array.") &&
992 !PrioStr.getAsInteger(10, Prio);
993 return {0, Prio, HasPrio};
994 }
995 if (Name.starts_with(".init"))
996 return {1, 0, false};
997 if (Name.starts_with(".ctors")) {
998 StringRef PrioStr = Name;
999 uint64_t Prio = 0;
1000 bool HasPrio =
1001 PrioStr.consume_front(".ctors.") && !PrioStr.getAsInteger(10, Prio);
1002 return {2, Prio, HasPrio};
1003 }
1004 return {3, 0, false};
1005 };
1006
1007 // Sort init sections:
1008 // 1. .init_array sections first (ascending priority - lower runs first)
1009 // 2. .init sections next
1010 // 3. .ctors sections last (descending priority - higher runs first, legacy
1011 // behavior)
1012 llvm::sort(OrderedInitSections,
1013 [&](const jitlink::Section *LHS, const jitlink::Section *RHS) {
1014 auto [LType, LPrio, LHasPrio] = getInitSectionInfo(LHS);
1015 auto [RType, RPrio, RHasPrio] = getInitSectionInfo(RHS);
1016
1017 if (LType != RType)
1018 return LType < RType;
1019
1020 // Same type - sort by priority
1021 if (LType == 0) {
1022 // .init_array: ascending priority (lower priority number runs
1023 // first)
1024 if (LHasPrio && RHasPrio)
1025 return LPrio < RPrio;
1026 if (LHasPrio)
1027 return true;
1028 if (RHasPrio)
1029 return false;
1030 } else if (LType == 2) {
1031 // .ctors: descending priority (higher priority number runs
1032 // first)
1033 if (LHasPrio && RHasPrio)
1034 return LPrio > RPrio;
1035 if (LHasPrio)
1036 return true;
1037 if (RHasPrio)
1038 return false;
1039 }
1040 return LHS->getName() < RHS->getName();
1041 });
1042
1043 for (auto &Sec : OrderedInitSections)
1044 ELFNixPlatformSecs.push_back(jitlink::SectionRange(*Sec).getRange());
1045
1046 // Dump the scraped inits.
1047 LLVM_DEBUG({
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";
1052 }
1053 });
1054
1055 ExecutorAddr HeaderAddr;
1056 {
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;
1062 }
1063
1064 using SPSRegisterInitSectionsArgs =
1065 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1066
1067 if (LLVM_UNLIKELY(IsBootstrapping)) {
1068 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1069 &MP.RegisterInitSections, &MP.DeregisterInitSections,
1070 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1071 ELFNixPlatformSecs),
1072 getArgDataBufferType<SPSRegisterInitSectionsArgs>(HeaderAddr,
1073 ELFNixPlatformSecs));
1074 return Error::success();
1075 }
1076
1077 G.allocActions().push_back(
1079 MP.RegisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs)),
1081 MP.DeregisterInitSections.Addr, HeaderAddr, ELFNixPlatformSecs))});
1082
1083 return Error::success();
1084}
1085
1086Error ELFNixPlatform::ELFNixPlatformPlugin::registerFiniSections(
1087 jitlink::LinkGraph &G, JITDylib &JD, bool IsBootstrapping) {
1088 SmallVector<ExecutorAddrRange> ELFNixFiniSecs;
1089 LLVM_DEBUG(dbgs() << "ELFNixPlatform::registerFiniSections\n");
1090
1091 SmallVector<jitlink::Section *> OrderedFiniSections;
1092 for (auto &Sec : G.sections())
1093 if (isELFFinalizerSection(Sec.getName()))
1094 OrderedFiniSections.push_back(&Sec);
1095
1096 // Helper to get section type and priority for sorting.
1097 // Returns: {type_order, priority, has_priority}
1098 // type_order: 0 = .dtors, 1 = .fini, 2 = .fini_array
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;
1104 uint64_t Prio = 0;
1105 bool HasPrio =
1106 PrioStr.consume_front(".dtors.") && !PrioStr.getAsInteger(10, Prio);
1107 return {0, Prio, HasPrio};
1108 }
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;
1114 uint64_t Prio = 0;
1115 bool HasPrio = PrioStr.consume_front(".fini_array.") &&
1116 !PrioStr.getAsInteger(10, Prio);
1117 return {2, Prio, HasPrio};
1118 }
1119 return {3, 0, false};
1120 };
1121
1122 // Sort fini sections:
1123 // 1. .dtors sections first (ascending priority, as they appear)
1124 // 2. .fini sections next
1125 // 3. .fini_array sections last (descending priority - higher runs first)
1126 llvm::sort(OrderedFiniSections,
1127 [&](const jitlink::Section *LHS, const jitlink::Section *RHS) {
1128 auto [LType, LPrio, LHasPrio] = getFiniSectionInfo(LHS);
1129 auto [RType, RPrio, RHasPrio] = getFiniSectionInfo(RHS);
1130
1131 if (LType != RType)
1132 return LType < RType;
1133
1134 // Same type - sort by priority
1135 if (LType == 0) {
1136 // .dtors: no-priority first, then ascending priority (lower
1137 // runs first)
1138 if (LHasPrio && RHasPrio)
1139 return LPrio < RPrio;
1140 if (LHasPrio)
1141 return false;
1142 if (RHasPrio)
1143 return true;
1144 } else if (LType == 2) {
1145 // .fini_array: no-priority first, then descending priority
1146 // (higher runs first)
1147 if (LHasPrio && RHasPrio)
1148 return LPrio > RPrio;
1149 if (LHasPrio)
1150 return false;
1151 if (RHasPrio)
1152 return true;
1153 }
1154 return LHS->getName() < RHS->getName();
1155 });
1156
1157 for (auto *Sec : OrderedFiniSections)
1158 ELFNixFiniSecs.push_back(jitlink::SectionRange(*Sec).getRange());
1159
1160 if (ELFNixFiniSecs.empty())
1161 return Error::success();
1162
1163 // Dump the scraped finis.
1164 LLVM_DEBUG({
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";
1169 }
1170 });
1171
1172 ExecutorAddr HeaderAddr;
1173 {
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;
1179 }
1180
1181 using SPSRegisterFiniSectionsArgs =
1182 SPSArgList<SPSExecutorAddr, SPSSequence<SPSExecutorAddrRange>>;
1183
1184 if (LLVM_UNLIKELY(IsBootstrapping)) {
1185 MP.Bootstrap.load()->addArgumentsToRTFnMap(
1186 &MP.RegisterFiniSections, &MP.DeregisterFiniSections,
1187 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1188 ELFNixFiniSecs),
1189 getArgDataBufferType<SPSRegisterFiniSectionsArgs>(HeaderAddr,
1190 ELFNixFiniSecs));
1191 return Error::success();
1192 }
1193
1194 G.allocActions().push_back(
1196 MP.RegisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs)),
1198 MP.DeregisterFiniSections.Addr, HeaderAddr, ELFNixFiniSecs))});
1199
1200 return Error::success();
1201}
1202
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) {
1210 auto TLSGetAddr =
1211 MP.getExecutionSession().intern("___orc_rt_elfnix_tls_get_addr");
1212 Sym->setName(std::move(TLSGetAddr));
1213 } else if (Sym->getName() == TLSDescResolveSymbolName) {
1214 auto TLSGetAddr =
1215 MP.getExecutionSession().intern("___orc_rt_elfnix_tlsdesc_resolver");
1216 Sym->setName(std::move(TLSGetAddr));
1217 } else if (Sym->getName() == TLSGetOffsetSymbolName) {
1218 auto TLSGetAddr =
1219 MP.getExecutionSession().intern("___orc_rt_elfnix_tls_get_offset");
1220 Sym->setName(std::move(TLSGetAddr));
1221 }
1222 }
1223
1224 auto *TLSInfoEntrySection = G.findSectionByName("$__TLSINFO");
1225
1226 if (TLSInfoEntrySection) {
1227 std::optional<uint64_t> Key;
1228 {
1229 std::lock_guard<std::mutex> Lock(MP.PlatformMutex);
1230 auto I = MP.JITDylibToPThreadKey.find(&JD);
1231 if (I != MP.JITDylibToPThreadKey.end())
1232 Key = I->second;
1233 }
1234 if (!Key) {
1235 if (auto KeyOrErr = MP.createPThreadKey())
1236 Key = *KeyOrErr;
1237 else
1238 return KeyOrErr.takeError();
1239 }
1240
1241 for (auto *B : TLSInfoEntrySection->blocks()) {
1242 // FIXME: The TLS descriptor byte length may different with different
1243 // ISA
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)
1248 support::endian::write<uint32_t>(TLSInfoEntryContent.data(), *Key,
1249 G.getEndianness());
1250 else
1251 support::endian::write<uint64_t>(TLSInfoEntryContent.data(), *Key,
1252 G.getEndianness());
1253 }
1254 }
1255
1256 return Error::success();
1257}
1258
1259} // End namespace orc.
1260} // End namespace llvm.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:352
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
#define _
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
#define P(N)
static StringRef getName(Value *V)
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:778
bool empty() const
Definition DenseMap.h:732
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:782
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:737
iterator end()
Definition DenseMap.h:702
unsigned size() const
Definition DenseMap.h:733
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:872
Helper for Errors used as out-parameters.
Definition Error.h:1160
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
void resize(size_type N)
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.
Definition StringRef.h:490
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:661
Manages the enabling and disabling of subtarget specific features.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
@ loongarch64
Definition Triple.h:66
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
Mediates between ELFNix initialization and ExecutionSession state.
static Expected< SymbolAliasMap > standardPlatformAliases(ExecutionSession &ES, JITDylib &PlatformJD)
Returns an AliasMap containing the default aliases for the ELFNixPlatform.
Error notifyAdding(ResourceTracker &RT, const MaterializationUnit &MU) override
This method will be called under the ExecutionSession lock each time a MaterializationUnit is added t...
Error notifyRemoving(ResourceTracker &RT) override
This method will be called under the ExecutionSession lock when a ResourceTracker is removed.
Error setupJITDylib(JITDylib &JD) override
This method will be called outside the session lock each time a JITDylib is created (unless it is cre...
ExecutionSession & getExecutionSession() const
static ArrayRef< std::pair< const char *, const char * > > standardRuntimeUtilityAliases()
Returns the array of standard runtime utility aliases for ELF.
static Expected< std::unique_ptr< ELFNixPlatform > > Create(ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD, std::unique_ptr< DefinitionGenerator > OrcRuntime, std::optional< SymbolAliasMap > RuntimeAliases=std::nullopt)
Try to create a ELFNixPlatform instance, adding the ORC runtime to the given JITDylib.
static ArrayRef< std::pair< const char *, const char * > > standardLazyCompilationAliases()
Returns a list of aliases required to enable lazy compilation via the ORC runtime.
static ArrayRef< std::pair< const char *, const char * > > requiredCXXAliases()
Returns the array of required CXX aliases.
Error teardownJITDylib(JITDylib &JD) override
This method will be called outside the session lock each time a JITDylib is removed to allow the Plat...
An ExecutionSession represents a running JIT program.
Definition Core.h:1112
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1193
Represents an address in the executor process.
Represents a JIT'd dynamic library.
Definition Core.h:676
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition Core.h:1629
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition Core.h:1612
LinkGraphLinkingLayer & addPlugin(std::shared_ptr< Plugin > P)
Add a plugin.
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition Mangling.h:28
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:350
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
Definition Core.h:389
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition Core.h:375
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.
static void lookupInitSymbolsAsync(unique_function< void(Error)> OnComplete, ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
Performs an async lookup for the given symbols in each of the given JITDylibs, calling the given hand...
Definition Core.cpp:1489
API to remove / transfer ownership of JIT resources.
Definition Core.h:64
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition Core.h:79
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.
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.
SymbolFlags
Symbol flags.
Definition Symbol.h:25
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...
Definition Core.h:154
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition Core.h:149
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition Core.h:59
std::vector< std::pair< ExecutorAddr, ELFNixJITDylibDepInfo > > ELFNixJITDylibDepInfoMap
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition Core.h:524
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...
Definition Core.h:533
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...
Definition Core.cpp:41
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:552
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition Core.h:174
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 ...
Definition Core.cpp:483
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.
Definition Endian.h:82
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...
Definition Error.cpp:94
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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.
Definition Error.h:340
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
static constexpr SymbolNameSpec Name