LLVM 20.0.0git
COFFPlatform.cpp
Go to the documentation of this file.
1//===------- COFFPlatform.cpp - Utilities for executing COFF 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
15
16#include "llvm/Object/COFF.h"
17
19
21
22#define DEBUG_TYPE "orc"
23
24using namespace llvm;
25using namespace llvm::orc;
26using namespace llvm::orc::shared;
27
28namespace llvm {
29namespace orc {
30namespace shared {
31
41
42} // namespace shared
43} // namespace orc
44} // namespace llvm
45namespace {
46
47class COFFHeaderMaterializationUnit : public MaterializationUnit {
48public:
49 COFFHeaderMaterializationUnit(COFFPlatform &CP,
50 const SymbolStringPtr &HeaderStartSymbol)
51 : MaterializationUnit(createHeaderInterface(CP, HeaderStartSymbol)),
52 CP(CP) {}
53
54 StringRef getName() const override { return "COFFHeaderMU"; }
55
56 void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
57 auto G = std::make_unique<jitlink::LinkGraph>(
58 "<COFFHeaderMU>", CP.getExecutionSession().getSymbolStringPool(),
59 CP.getExecutionSession().getTargetTriple(), SubtargetFeatures(),
61 auto &HeaderSection = G->createSection("__header", MemProt::Read);
62 auto &HeaderBlock = createHeaderBlock(*G, HeaderSection);
63
64 // Init symbol is __ImageBase symbol.
65 auto &ImageBaseSymbol = G->addDefinedSymbol(
66 HeaderBlock, 0, *R->getInitializerSymbol(), HeaderBlock.getSize(),
67 jitlink::Linkage::Strong, jitlink::Scope::Default, false, true);
68
69 addImageBaseRelocationEdge(HeaderBlock, ImageBaseSymbol);
70
71 CP.getObjectLinkingLayer().emit(std::move(R), std::move(G));
72 }
73
74 void discard(const JITDylib &JD, const SymbolStringPtr &Sym) override {}
75
76private:
77 struct HeaderSymbol {
78 const char *Name;
80 };
81
82 struct NTHeader {
84 object::coff_file_header FileHeader;
85 struct PEHeader {
88 } OptionalHeader;
89 };
90
91 struct HeaderBlockContent {
92 object::dos_header DOSHeader;
93 COFFHeaderMaterializationUnit::NTHeader NTHeader;
94 };
95
97 jitlink::Section &HeaderSection) {
98 HeaderBlockContent Hdr = {};
99
100 // Set up magic
101 Hdr.DOSHeader.Magic[0] = 'M';
102 Hdr.DOSHeader.Magic[1] = 'Z';
103 Hdr.DOSHeader.AddressOfNewExeHeader =
104 offsetof(HeaderBlockContent, NTHeader);
105 uint32_t PEMagic = *reinterpret_cast<const uint32_t *>(COFF::PEMagic);
106 Hdr.NTHeader.PEMagic = PEMagic;
107 Hdr.NTHeader.OptionalHeader.Header.Magic = COFF::PE32Header::PE32_PLUS;
108
109 switch (G.getTargetTriple().getArch()) {
110 case Triple::x86_64:
111 Hdr.NTHeader.FileHeader.Machine = COFF::IMAGE_FILE_MACHINE_AMD64;
112 break;
113 default:
114 llvm_unreachable("Unrecognized architecture");
115 }
116
117 auto HeaderContent = G.allocateContent(
118 ArrayRef<char>(reinterpret_cast<const char *>(&Hdr), sizeof(Hdr)));
119
120 return G.createContentBlock(HeaderSection, HeaderContent, ExecutorAddr(), 8,
121 0);
122 }
123
124 static void addImageBaseRelocationEdge(jitlink::Block &B,
125 jitlink::Symbol &ImageBase) {
126 auto ImageBaseOffset = offsetof(HeaderBlockContent, NTHeader) +
127 offsetof(NTHeader, OptionalHeader) +
129 B.addEdge(jitlink::x86_64::Pointer64, ImageBaseOffset, ImageBase, 0);
130 }
131
133 createHeaderInterface(COFFPlatform &MOP,
134 const SymbolStringPtr &HeaderStartSymbol) {
135 SymbolFlagsMap HeaderSymbolFlags;
136
137 HeaderSymbolFlags[HeaderStartSymbol] = JITSymbolFlags::Exported;
138
139 return MaterializationUnit::Interface(std::move(HeaderSymbolFlags),
140 HeaderStartSymbol);
141 }
142
144};
145
146} // end anonymous namespace
147
148namespace llvm {
149namespace orc {
150
153 std::unique_ptr<MemoryBuffer> OrcRuntimeArchiveBuffer,
154 LoadDynamicLibrary LoadDynLibrary, bool StaticVCRuntime,
155 const char *VCRuntimePath,
156 std::optional<SymbolAliasMap> RuntimeAliases) {
157
158 auto &ES = ObjLinkingLayer.getExecutionSession();
159
160 // If the target is not supported then bail out immediately.
161 if (!supportedTarget(ES.getTargetTriple()))
162 return make_error<StringError>("Unsupported COFFPlatform triple: " +
163 ES.getTargetTriple().str(),
165
166 auto &EPC = ES.getExecutorProcessControl();
167
168 auto GeneratorArchive =
169 object::Archive::create(OrcRuntimeArchiveBuffer->getMemBufferRef());
170 if (!GeneratorArchive)
171 return GeneratorArchive.takeError();
172
173 auto OrcRuntimeArchiveGenerator = StaticLibraryDefinitionGenerator::Create(
174 ObjLinkingLayer, nullptr, std::move(*GeneratorArchive));
175 if (!OrcRuntimeArchiveGenerator)
176 return OrcRuntimeArchiveGenerator.takeError();
177
178 // We need a second instance of the archive (for now) for the Platform. We
179 // can `cantFail` this call, since if it were going to fail it would have
180 // failed above.
181 auto RuntimeArchive = cantFail(
182 object::Archive::create(OrcRuntimeArchiveBuffer->getMemBufferRef()));
183
184 // Create default aliases if the caller didn't supply any.
185 if (!RuntimeAliases)
186 RuntimeAliases = standardPlatformAliases(ES);
187
188 // Define the aliases.
189 if (auto Err = PlatformJD.define(symbolAliases(std::move(*RuntimeAliases))))
190 return std::move(Err);
191
192 auto &HostFuncJD = ES.createBareJITDylib("$<PlatformRuntimeHostFuncJD>");
193
194 // Add JIT-dispatch function support symbols.
195 if (auto Err = HostFuncJD.define(
196 absoluteSymbols({{ES.intern("__orc_rt_jit_dispatch"),
197 {EPC.getJITDispatchInfo().JITDispatchFunction,
199 {ES.intern("__orc_rt_jit_dispatch_ctx"),
200 {EPC.getJITDispatchInfo().JITDispatchContext,
202 return std::move(Err);
203
204 PlatformJD.addToLinkOrder(HostFuncJD);
205
206 // Create the instance.
207 Error Err = Error::success();
208 auto P = std::unique_ptr<COFFPlatform>(new COFFPlatform(
209 ObjLinkingLayer, PlatformJD, std::move(*OrcRuntimeArchiveGenerator),
210 std::move(OrcRuntimeArchiveBuffer), std::move(RuntimeArchive),
211 std::move(LoadDynLibrary), StaticVCRuntime, VCRuntimePath, Err));
212 if (Err)
213 return std::move(Err);
214 return std::move(P);
215}
216
219 const char *OrcRuntimePath,
220 LoadDynamicLibrary LoadDynLibrary, bool StaticVCRuntime,
221 const char *VCRuntimePath,
222 std::optional<SymbolAliasMap> RuntimeAliases) {
223
224 auto ArchiveBuffer = MemoryBuffer::getFile(OrcRuntimePath);
225 if (!ArchiveBuffer)
226 return createFileError(OrcRuntimePath, ArchiveBuffer.getError());
227
228 return Create(ObjLinkingLayer, PlatformJD, std::move(*ArchiveBuffer),
229 std::move(LoadDynLibrary), StaticVCRuntime, VCRuntimePath,
230 std::move(RuntimeAliases));
231}
232
233Expected<MemoryBufferRef> COFFPlatform::getPerJDObjectFile() {
234 auto PerJDObj = OrcRuntimeArchive->findSym("__orc_rt_coff_per_jd_marker");
235 if (!PerJDObj)
236 return PerJDObj.takeError();
237
238 if (!*PerJDObj)
239 return make_error<StringError>("Could not find per jd object file",
241
242 auto Buffer = (*PerJDObj)->getAsBinary();
243 if (!Buffer)
244 return Buffer.takeError();
245
246 return (*Buffer)->getMemoryBufferRef();
247}
248
250 ArrayRef<std::pair<const char *, const char *>> AL) {
251 for (auto &KV : AL) {
252 auto AliasName = ES.intern(KV.first);
253 assert(!Aliases.count(AliasName) && "Duplicate symbol name in alias map");
254 Aliases[std::move(AliasName)] = {ES.intern(KV.second),
256 }
257}
258
260 if (auto Err = JD.define(std::make_unique<COFFHeaderMaterializationUnit>(
261 *this, COFFHeaderStartSymbol)))
262 return Err;
263
264 if (auto Err = ES.lookup({&JD}, COFFHeaderStartSymbol).takeError())
265 return Err;
266
267 // Define the CXX aliases.
268 SymbolAliasMap CXXAliases;
269 addAliases(ES, CXXAliases, requiredCXXAliases());
270 if (auto Err = JD.define(symbolAliases(std::move(CXXAliases))))
271 return Err;
272
273 auto PerJDObj = getPerJDObjectFile();
274 if (!PerJDObj)
275 return PerJDObj.takeError();
276
277 auto I = getObjectFileInterface(ES, *PerJDObj);
278 if (!I)
279 return I.takeError();
280
281 if (auto Err = ObjLinkingLayer.add(
282 JD, MemoryBuffer::getMemBuffer(*PerJDObj, false), std::move(*I)))
283 return Err;
284
285 if (!Bootstrapping) {
286 auto ImportedLibs = StaticVCRuntime
287 ? VCRuntimeBootstrap->loadStaticVCRuntime(JD)
288 : VCRuntimeBootstrap->loadDynamicVCRuntime(JD);
289 if (!ImportedLibs)
290 return ImportedLibs.takeError();
291 for (auto &Lib : *ImportedLibs)
292 if (auto Err = LoadDynLibrary(JD, Lib))
293 return Err;
294 if (StaticVCRuntime)
295 if (auto Err = VCRuntimeBootstrap->initializeStaticVCRuntime(JD))
296 return Err;
297 }
298
299 JD.addGenerator(DLLImportDefinitionGenerator::Create(ES, ObjLinkingLayer));
300 return Error::success();
301}
302
304 std::lock_guard<std::mutex> Lock(PlatformMutex);
305 auto I = JITDylibToHeaderAddr.find(&JD);
306 if (I != JITDylibToHeaderAddr.end()) {
307 assert(HeaderAddrToJITDylib.count(I->second) &&
308 "HeaderAddrToJITDylib missing entry");
309 HeaderAddrToJITDylib.erase(I->second);
310 JITDylibToHeaderAddr.erase(I);
311 }
312 return Error::success();
313}
314
316 const MaterializationUnit &MU) {
317 auto &JD = RT.getJITDylib();
318 const auto &InitSym = MU.getInitializerSymbol();
319 if (!InitSym)
320 return Error::success();
321
322 RegisteredInitSymbols[&JD].add(InitSym,
324
325 LLVM_DEBUG({
326 dbgs() << "COFFPlatform: Registered init symbol " << *InitSym << " for MU "
327 << MU.getName() << "\n";
328 });
329 return Error::success();
330}
331
333 llvm_unreachable("Not supported yet");
334}
335
337 SymbolAliasMap Aliases;
339 return Aliases;
340}
341
344 static const std::pair<const char *, const char *> RequiredCXXAliases[] = {
345 {"_CxxThrowException", "__orc_rt_coff_cxx_throw_exception"},
346 {"_onexit", "__orc_rt_coff_onexit_per_jd"},
347 {"atexit", "__orc_rt_coff_atexit_per_jd"}};
348
349 return ArrayRef<std::pair<const char *, const char *>>(RequiredCXXAliases);
350}
351
354 static const std::pair<const char *, const char *>
355 StandardRuntimeUtilityAliases[] = {
356 {"__orc_rt_run_program", "__orc_rt_coff_run_program"},
357 {"__orc_rt_jit_dlerror", "__orc_rt_coff_jit_dlerror"},
358 {"__orc_rt_jit_dlopen", "__orc_rt_coff_jit_dlopen"},
359 {"__orc_rt_jit_dlclose", "__orc_rt_coff_jit_dlclose"},
360 {"__orc_rt_jit_dlsym", "__orc_rt_coff_jit_dlsym"},
361 {"__orc_rt_log_error", "__orc_rt_log_error_to_stderr"}};
362
364 StandardRuntimeUtilityAliases);
365}
366
367bool COFFPlatform::supportedTarget(const Triple &TT) {
368 switch (TT.getArch()) {
369 case Triple::x86_64:
370 return true;
371 default:
372 return false;
373 }
374}
375
376COFFPlatform::COFFPlatform(
377 ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD,
378 std::unique_ptr<StaticLibraryDefinitionGenerator> OrcRuntimeGenerator,
379 std::unique_ptr<MemoryBuffer> OrcRuntimeArchiveBuffer,
380 std::unique_ptr<object::Archive> OrcRuntimeArchive,
381 LoadDynamicLibrary LoadDynLibrary, bool StaticVCRuntime,
382 const char *VCRuntimePath, Error &Err)
383 : ES(ObjLinkingLayer.getExecutionSession()),
384 ObjLinkingLayer(ObjLinkingLayer),
385 LoadDynLibrary(std::move(LoadDynLibrary)),
386 OrcRuntimeArchiveBuffer(std::move(OrcRuntimeArchiveBuffer)),
387 OrcRuntimeArchive(std::move(OrcRuntimeArchive)),
388 StaticVCRuntime(StaticVCRuntime),
389 COFFHeaderStartSymbol(ES.intern("__ImageBase")) {
391
392 Bootstrapping.store(true);
393 ObjLinkingLayer.addPlugin(std::make_unique<COFFPlatformPlugin>(*this));
394
395 // Load vc runtime
396 auto VCRT =
397 COFFVCRuntimeBootstrapper::Create(ES, ObjLinkingLayer, VCRuntimePath);
398 if (!VCRT) {
399 Err = VCRT.takeError();
400 return;
401 }
402 VCRuntimeBootstrap = std::move(*VCRT);
403
404 for (auto &Lib : OrcRuntimeGenerator->getImportedDynamicLibraries())
405 DylibsToPreload.insert(Lib);
406
407 auto ImportedLibs =
408 StaticVCRuntime ? VCRuntimeBootstrap->loadStaticVCRuntime(PlatformJD)
409 : VCRuntimeBootstrap->loadDynamicVCRuntime(PlatformJD);
410 if (!ImportedLibs) {
411 Err = ImportedLibs.takeError();
412 return;
413 }
414
415 for (auto &Lib : *ImportedLibs)
416 DylibsToPreload.insert(Lib);
417
418 PlatformJD.addGenerator(std::move(OrcRuntimeGenerator));
419
420 // PlatformJD hasn't been set up by the platform yet (since we're creating
421 // the platform now), so set it up.
422 if (auto E2 = setupJITDylib(PlatformJD)) {
423 Err = std::move(E2);
424 return;
425 }
426
427 for (auto& Lib : DylibsToPreload)
428 if (auto E2 = this->LoadDynLibrary(PlatformJD, Lib)) {
429 Err = std::move(E2);
430 return;
431 }
432
433 if (StaticVCRuntime)
434 if (auto E2 = VCRuntimeBootstrap->initializeStaticVCRuntime(PlatformJD)) {
435 Err = std::move(E2);
436 return;
437 }
438
439 // Associate wrapper function tags with JIT-side function implementations.
440 if (auto E2 = associateRuntimeSupportFunctions(PlatformJD)) {
441 Err = std::move(E2);
442 return;
443 }
444
445 // Lookup addresses of runtime functions callable by the platform,
446 // call the platform bootstrap function to initialize the platform-state
447 // object in the executor.
448 if (auto E2 = bootstrapCOFFRuntime(PlatformJD)) {
449 Err = std::move(E2);
450 return;
451 }
452
453 Bootstrapping.store(false);
454 JDBootstrapStates.clear();
455}
456
458COFFPlatform::buildJDDepMap(JITDylib &JD) {
459 return ES.runSessionLocked([&]() -> Expected<JITDylibDepMap> {
460 JITDylibDepMap JDDepMap;
461
462 SmallVector<JITDylib *, 16> Worklist({&JD});
463 while (!Worklist.empty()) {
464 auto CurJD = Worklist.back();
465 Worklist.pop_back();
466
467 auto &DM = JDDepMap[CurJD];
468 CurJD->withLinkOrderDo([&](const JITDylibSearchOrder &O) {
469 DM.reserve(O.size());
470 for (auto &KV : O) {
471 if (KV.first == CurJD)
472 continue;
473 {
474 // Bare jitdylibs not known to the platform
475 std::lock_guard<std::mutex> Lock(PlatformMutex);
476 if (!JITDylibToHeaderAddr.count(KV.first)) {
477 LLVM_DEBUG({
478 dbgs() << "JITDylib unregistered to COFFPlatform detected in "
479 "LinkOrder: "
480 << CurJD->getName() << "\n";
481 });
482 continue;
483 }
484 }
485 DM.push_back(KV.first);
486 // Push unvisited entry.
487 if (!JDDepMap.count(KV.first)) {
488 Worklist.push_back(KV.first);
489 JDDepMap[KV.first] = {};
490 }
491 }
492 });
493 }
494 return std::move(JDDepMap);
495 });
496}
497
498void COFFPlatform::pushInitializersLoop(PushInitializersSendResultFn SendResult,
499 JITDylibSP JD,
500 JITDylibDepMap &JDDepMap) {
501 SmallVector<JITDylib *, 16> Worklist({JD.get()});
502 DenseSet<JITDylib *> Visited({JD.get()});
504 ES.runSessionLocked([&]() {
505 while (!Worklist.empty()) {
506 auto CurJD = Worklist.back();
507 Worklist.pop_back();
508
509 auto RISItr = RegisteredInitSymbols.find(CurJD);
510 if (RISItr != RegisteredInitSymbols.end()) {
511 NewInitSymbols[CurJD] = std::move(RISItr->second);
512 RegisteredInitSymbols.erase(RISItr);
513 }
514
515 for (auto *DepJD : JDDepMap[CurJD])
516 if (Visited.insert(DepJD).second)
517 Worklist.push_back(DepJD);
518 }
519 });
520
521 // If there are no further init symbols to look up then send the link order
522 // (as a list of header addresses) to the caller.
523 if (NewInitSymbols.empty()) {
524 // Build the dep info map to return.
525 COFFJITDylibDepInfoMap DIM;
526 DIM.reserve(JDDepMap.size());
527 for (auto &KV : JDDepMap) {
528 std::lock_guard<std::mutex> Lock(PlatformMutex);
529 COFFJITDylibDepInfo DepInfo;
530 DepInfo.reserve(KV.second.size());
531 for (auto &Dep : KV.second) {
532 DepInfo.push_back(JITDylibToHeaderAddr[Dep]);
533 }
534 auto H = JITDylibToHeaderAddr[KV.first];
535 DIM.push_back(std::make_pair(H, std::move(DepInfo)));
536 }
537 SendResult(DIM);
538 return;
539 }
540
541 // Otherwise issue a lookup and re-run this phase when it completes.
542 lookupInitSymbolsAsync(
543 [this, SendResult = std::move(SendResult), &JD,
544 JDDepMap = std::move(JDDepMap)](Error Err) mutable {
545 if (Err)
546 SendResult(std::move(Err));
547 else
548 pushInitializersLoop(std::move(SendResult), JD, JDDepMap);
549 },
550 ES, std::move(NewInitSymbols));
551}
552
553void COFFPlatform::rt_pushInitializers(PushInitializersSendResultFn SendResult,
554 ExecutorAddr JDHeaderAddr) {
555 JITDylibSP JD;
556 {
557 std::lock_guard<std::mutex> Lock(PlatformMutex);
558 auto I = HeaderAddrToJITDylib.find(JDHeaderAddr);
559 if (I != HeaderAddrToJITDylib.end())
560 JD = I->second;
561 }
562
563 LLVM_DEBUG({
564 dbgs() << "COFFPlatform::rt_pushInitializers(" << JDHeaderAddr << ") ";
565 if (JD)
566 dbgs() << "pushing initializers for " << JD->getName() << "\n";
567 else
568 dbgs() << "No JITDylib for header address.\n";
569 });
570
571 if (!JD) {
572 SendResult(make_error<StringError>("No JITDylib with header addr " +
573 formatv("{0:x}", JDHeaderAddr),
575 return;
576 }
577
578 auto JDDepMap = buildJDDepMap(*JD);
579 if (!JDDepMap) {
580 SendResult(JDDepMap.takeError());
581 return;
582 }
583
584 pushInitializersLoop(std::move(SendResult), JD, *JDDepMap);
585}
586
587void COFFPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult,
588 ExecutorAddr Handle, StringRef SymbolName) {
589 LLVM_DEBUG(dbgs() << "COFFPlatform::rt_lookupSymbol(\"" << Handle << "\")\n");
590
591 JITDylib *JD = nullptr;
592
593 {
594 std::lock_guard<std::mutex> Lock(PlatformMutex);
595 auto I = HeaderAddrToJITDylib.find(Handle);
596 if (I != HeaderAddrToJITDylib.end())
597 JD = I->second;
598 }
599
600 if (!JD) {
601 LLVM_DEBUG(dbgs() << " No JITDylib for handle " << Handle << "\n");
602 SendResult(make_error<StringError>("No JITDylib associated with handle " +
603 formatv("{0:x}", Handle),
605 return;
606 }
607
608 // Use functor class to work around XL build compiler issue on AIX.
609 class RtLookupNotifyComplete {
610 public:
611 RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult)
612 : SendResult(std::move(SendResult)) {}
613 void operator()(Expected<SymbolMap> Result) {
614 if (Result) {
615 assert(Result->size() == 1 && "Unexpected result map count");
616 SendResult(Result->begin()->second.getAddress());
617 } else {
618 SendResult(Result.takeError());
619 }
620 }
621
622 private:
623 SendSymbolAddressFn SendResult;
624 };
625
626 ES.lookup(
629 RtLookupNotifyComplete(std::move(SendResult)), NoDependenciesToRegister);
630}
631
632Error COFFPlatform::associateRuntimeSupportFunctions(JITDylib &PlatformJD) {
634
635 using LookupSymbolSPSSig =
637 WFs[ES.intern("__orc_rt_coff_symbol_lookup_tag")] =
638 ES.wrapAsyncWithSPS<LookupSymbolSPSSig>(this,
639 &COFFPlatform::rt_lookupSymbol);
640 using PushInitializersSPSSig =
642 WFs[ES.intern("__orc_rt_coff_push_initializers_tag")] =
643 ES.wrapAsyncWithSPS<PushInitializersSPSSig>(
644 this, &COFFPlatform::rt_pushInitializers);
645
646 return ES.registerJITDispatchHandlers(PlatformJD, std::move(WFs));
647}
648
649Error COFFPlatform::runBootstrapInitializers(JDBootstrapState &BState) {
650 llvm::sort(BState.Initializers);
651 if (auto Err =
652 runBootstrapSubsectionInitializers(BState, ".CRT$XIA", ".CRT$XIZ"))
653 return Err;
654
655 if (auto Err = runSymbolIfExists(*BState.JD, "__run_after_c_init"))
656 return Err;
657
658 if (auto Err =
659 runBootstrapSubsectionInitializers(BState, ".CRT$XCA", ".CRT$XCZ"))
660 return Err;
661 return Error::success();
662}
663
664Error COFFPlatform::runBootstrapSubsectionInitializers(JDBootstrapState &BState,
665 StringRef Start,
666 StringRef End) {
667 for (auto &Initializer : BState.Initializers)
668 if (Initializer.first >= Start && Initializer.first <= End &&
669 Initializer.second) {
670 auto Res =
671 ES.getExecutorProcessControl().runAsVoidFunction(Initializer.second);
672 if (!Res)
673 return Res.takeError();
674 }
675 return Error::success();
676}
677
678Error COFFPlatform::bootstrapCOFFRuntime(JITDylib &PlatformJD) {
679 // Lookup of runtime symbols causes the collection of initializers if
680 // it's static linking setting.
681 if (auto Err = lookupAndRecordAddrs(
683 {
684 {ES.intern("__orc_rt_coff_platform_bootstrap"),
685 &orc_rt_coff_platform_bootstrap},
686 {ES.intern("__orc_rt_coff_platform_shutdown"),
687 &orc_rt_coff_platform_shutdown},
688 {ES.intern("__orc_rt_coff_register_jitdylib"),
689 &orc_rt_coff_register_jitdylib},
690 {ES.intern("__orc_rt_coff_deregister_jitdylib"),
691 &orc_rt_coff_deregister_jitdylib},
692 {ES.intern("__orc_rt_coff_register_object_sections"),
693 &orc_rt_coff_register_object_sections},
694 {ES.intern("__orc_rt_coff_deregister_object_sections"),
695 &orc_rt_coff_deregister_object_sections},
696 }))
697 return Err;
698
699 // Call bootstrap functions
700 if (auto Err = ES.callSPSWrapper<void()>(orc_rt_coff_platform_bootstrap))
701 return Err;
702
703 // Do the pending jitdylib registration actions that we couldn't do
704 // because orc runtime was not linked fully.
705 for (auto KV : JDBootstrapStates) {
706 auto &JDBState = KV.second;
707 if (auto Err = ES.callSPSWrapper<void(SPSString, SPSExecutorAddr)>(
708 orc_rt_coff_register_jitdylib, JDBState.JDName,
709 JDBState.HeaderAddr))
710 return Err;
711
712 for (auto &ObjSectionMap : JDBState.ObjectSectionsMaps)
713 if (auto Err = ES.callSPSWrapper<void(SPSExecutorAddr,
715 orc_rt_coff_register_object_sections, JDBState.HeaderAddr,
716 ObjSectionMap, false))
717 return Err;
718 }
719
720 // Run static initializers collected in bootstrap stage.
721 for (auto KV : JDBootstrapStates) {
722 auto &JDBState = KV.second;
723 if (auto Err = runBootstrapInitializers(JDBState))
724 return Err;
725 }
726
727 return Error::success();
728}
729
730Error COFFPlatform::runSymbolIfExists(JITDylib &PlatformJD,
731 StringRef SymbolName) {
732 ExecutorAddr jit_function;
733 auto AfterCLookupErr = lookupAndRecordAddrs(
735 {{ES.intern(SymbolName), &jit_function}});
736 if (!AfterCLookupErr) {
737 auto Res = ES.getExecutorProcessControl().runAsVoidFunction(jit_function);
738 if (!Res)
739 return Res.takeError();
740 return Error::success();
741 }
742 if (!AfterCLookupErr.isA<SymbolsNotFound>())
743 return AfterCLookupErr;
744 consumeError(std::move(AfterCLookupErr));
745 return Error::success();
746}
747
748void COFFPlatform::COFFPlatformPlugin::modifyPassConfig(
751
752 bool IsBootstrapping = CP.Bootstrapping.load();
753
754 if (auto InitSymbol = MR.getInitializerSymbol()) {
755 if (InitSymbol == CP.COFFHeaderStartSymbol) {
756 Config.PostAllocationPasses.push_back(
757 [this, &MR, IsBootstrapping](jitlink::LinkGraph &G) {
758 return associateJITDylibHeaderSymbol(G, MR, IsBootstrapping);
759 });
760 return;
761 }
762 Config.PrePrunePasses.push_back([this, &MR](jitlink::LinkGraph &G) {
763 return preserveInitializerSections(G, MR);
764 });
765 }
766
767 if (!IsBootstrapping)
768 Config.PostFixupPasses.push_back(
769 [this, &JD = MR.getTargetJITDylib()](jitlink::LinkGraph &G) {
770 return registerObjectPlatformSections(G, JD);
771 });
772 else
773 Config.PostFixupPasses.push_back(
774 [this, &JD = MR.getTargetJITDylib()](jitlink::LinkGraph &G) {
775 return registerObjectPlatformSectionsInBootstrap(G, JD);
776 });
777}
778
779Error COFFPlatform::COFFPlatformPlugin::associateJITDylibHeaderSymbol(
781 bool IsBootstraping) {
782 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
783 return *Sym->getName() == *CP.COFFHeaderStartSymbol;
784 });
785 assert(I != G.defined_symbols().end() && "Missing COFF header start symbol");
786
787 auto &JD = MR.getTargetJITDylib();
788 std::lock_guard<std::mutex> Lock(CP.PlatformMutex);
789 auto HeaderAddr = (*I)->getAddress();
790 CP.JITDylibToHeaderAddr[&JD] = HeaderAddr;
791 CP.HeaderAddrToJITDylib[HeaderAddr] = &JD;
792 if (!IsBootstraping) {
793 G.allocActions().push_back(
796 CP.orc_rt_coff_register_jitdylib, JD.getName(), HeaderAddr)),
798 CP.orc_rt_coff_deregister_jitdylib, HeaderAddr))});
799 } else {
800 G.allocActions().push_back(
801 {{},
803 CP.orc_rt_coff_deregister_jitdylib, HeaderAddr))});
804 JDBootstrapState BState;
805 BState.JD = &JD;
806 BState.JDName = JD.getName();
807 BState.HeaderAddr = HeaderAddr;
808 CP.JDBootstrapStates.emplace(&JD, BState);
809 }
810
811 return Error::success();
812}
813
814Error COFFPlatform::COFFPlatformPlugin::registerObjectPlatformSections(
816 COFFObjectSectionsMap ObjSecs;
817 auto HeaderAddr = CP.JITDylibToHeaderAddr[&JD];
818 assert(HeaderAddr && "Must be registered jitdylib");
819 for (auto &S : G.sections()) {
821 if (Range.getSize())
822 ObjSecs.push_back(std::make_pair(S.getName().str(), Range.getRange()));
823 }
824
825 G.allocActions().push_back(
826 {cantFail(WrapperFunctionCall::Create<SPSCOFFRegisterObjectSectionsArgs>(
827 CP.orc_rt_coff_register_object_sections, HeaderAddr, ObjSecs, true)),
828 cantFail(
829 WrapperFunctionCall::Create<SPSCOFFDeregisterObjectSectionsArgs>(
830 CP.orc_rt_coff_deregister_object_sections, HeaderAddr,
831 ObjSecs))});
832
833 return Error::success();
834}
835
836Error COFFPlatform::COFFPlatformPlugin::preserveInitializerSections(
838
839 if (const auto &InitSymName = MR.getInitializerSymbol()) {
840
841 jitlink::Symbol *InitSym = nullptr;
842
843 for (auto &InitSection : G.sections()) {
844 // Skip non-init sections.
845 if (!isCOFFInitializerSection(InitSection.getName()) ||
846 InitSection.empty())
847 continue;
848
849 // Create the init symbol if it has not been created already and attach it
850 // to the first block.
851 if (!InitSym) {
852 auto &B = **InitSection.blocks().begin();
853 InitSym = &G.addDefinedSymbol(
854 B, 0, *InitSymName, B.getSize(), jitlink::Linkage::Strong,
856 }
857
858 // Add keep-alive edges to anonymous symbols in all other init blocks.
859 for (auto *B : InitSection.blocks()) {
860 if (B == &InitSym->getBlock())
861 continue;
862
863 auto &S = G.addAnonymousSymbol(*B, 0, B->getSize(), false, true);
864 InitSym->getBlock().addEdge(jitlink::Edge::KeepAlive, 0, S, 0);
865 }
866 }
867 }
868
869 return Error::success();
870}
871
872Error COFFPlatform::COFFPlatformPlugin::
873 registerObjectPlatformSectionsInBootstrap(jitlink::LinkGraph &G,
874 JITDylib &JD) {
875 std::lock_guard<std::mutex> Lock(CP.PlatformMutex);
876 auto HeaderAddr = CP.JITDylibToHeaderAddr[&JD];
877 COFFObjectSectionsMap ObjSecs;
878 for (auto &S : G.sections()) {
880 if (Range.getSize())
881 ObjSecs.push_back(std::make_pair(S.getName().str(), Range.getRange()));
882 }
883
884 G.allocActions().push_back(
885 {{},
886 cantFail(
887 WrapperFunctionCall::Create<SPSCOFFDeregisterObjectSectionsArgs>(
888 CP.orc_rt_coff_deregister_object_sections, HeaderAddr,
889 ObjSecs))});
890
891 auto &BState = CP.JDBootstrapStates[&JD];
892 BState.ObjectSectionsMaps.push_back(std::move(ObjSecs));
893
894 // Collect static initializers
895 for (auto &S : G.sections())
896 if (isCOFFInitializerSection(S.getName()))
897 for (auto *B : S.blocks()) {
898 if (B->edges_empty())
899 continue;
900 for (auto &E : B->edges())
901 BState.Initializers.push_back(std::make_pair(
902 S.getName().str(), E.getTarget().getAddress() + E.getAddend()));
903 }
904
905 return Error::success();
906}
907
908} // End namespace orc.
909} // End namespace llvm.
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
#define offsetof(TYPE, MEMBER)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DEBUG(...)
Definition: Debug.h:106
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
bool End
Definition: ELF_riscv.cpp:480
RelaxConfig Config
Definition: ELF_riscv.cpp:506
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define _
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
#define H(x, y, z)
Definition: MD5.cpp:57
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
if(PassOpts->AAPipeline)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
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:152
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
Helper for Errors used as out-parameters.
Definition: Error.h:1130
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
bool empty() const
Definition: SmallVector.h:81
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Manages the enabling and disabling of subtarget specific features.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
const std::string & str() const
Definition: Triple.h:450
static Expected< std::unique_ptr< Archive > > create(MemoryBufferRef Source)
Definition: Archive.cpp:668
Mediates between COFF initialization and ExecutionSession state.
Definition: COFFPlatform.h:34
Error setupJITDylib(JITDylib &JD) override
This method will be called outside the session lock each time a JITDylib is created (unless it is cre...
static Expected< std::unique_ptr< COFFPlatform > > Create(ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD, std::unique_ptr< MemoryBuffer > OrcRuntimeArchiveBuffer, LoadDynamicLibrary LoadDynLibrary, bool StaticVCRuntime=false, const char *VCRuntimePath=nullptr, std::optional< SymbolAliasMap > RuntimeAliases=std::nullopt)
Try to create a COFFPlatform instance, adding the ORC runtime to the given JITDylib.
static ArrayRef< std::pair< const char *, const char * > > standardRuntimeUtilityAliases()
Returns the array of standard runtime utility aliases for COFF.
Error teardownJITDylib(JITDylib &JD) override
This method will be called outside the session lock each time a JITDylib is removed to allow the Plat...
static SymbolAliasMap standardPlatformAliases(ExecutionSession &ES)
Returns an AliasMap containing the default aliases for the COFFPlatform.
Error notifyAdding(ResourceTracker &RT, const MaterializationUnit &MU) override
This method will be called under the ExecutionSession lock each time a MaterializationUnit is added t...
static ArrayRef< std::pair< const char *, const char * > > requiredCXXAliases()
Returns the array of required CXX aliases.
Error notifyRemoving(ResourceTracker &RT) override
This method will be called under the ExecutionSession lock when a ResourceTracker is removed.
static Expected< std::unique_ptr< COFFVCRuntimeBootstrapper > > Create(ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer, const char *RuntimePath=nullptr)
Try to create a COFFVCRuntimeBootstrapper instance.
static std::unique_ptr< DLLImportDefinitionGenerator > Create(ExecutionSession &ES, ObjectLinkingLayer &L)
Creates a DLLImportDefinitionGenerator instance.
An ExecutionSession represents a running JIT program.
Definition: Core.h:1340
ExecutorProcessControl & getExecutorProcessControl()
Get the ExecutorProcessControl object associated with this ExecutionSession.
Definition: Core.h:1380
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition: Core.h:1383
Error callSPSWrapper(ExecutorAddr WrapperFnAddr, WrapperCallArgTs &&...WrapperCallArgs)
Run a wrapper function using SPS to serialize the arguments and deserialize the results.
Definition: Core.h:1594
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1394
JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition: Core.cpp:1660
static JITDispatchHandlerFunction wrapAsyncWithSPS(HandlerT &&H)
Wrap a handler that takes concrete argument types (and a sender for a concrete return type) to produc...
Definition: Core.h:1608
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition: Core.cpp:1798
Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition: Core.cpp:1893
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition: Core.h:1404
Represents an address in the executor process.
virtual Expected< int32_t > runAsVoidFunction(ExecutorAddr VoidFnAddr)=0
Run function with a int (*)(void) signature.
Represents a JIT'd dynamic library.
Definition: Core.h:897
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:1823
void addToLinkOrder(const JITDylibSearchOrder &NewLinks)
Append the given JITDylibSearchOrder to the link order for this JITDylib (discarding any elements alr...
Definition: Core.cpp:1019
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition: Core.h:1806
ExecutionSession & getExecutionSession()
LinkGraphLinkingLayer & addPlugin(std::shared_ptr< Plugin > P)
Add a plugin.
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:571
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
Definition: Core.h:610
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition: Core.h:596
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.
virtual void materialize(std::unique_ptr< MaterializationResponsibility > R)=0
Implementations of this method should materialize all symbols in the materialzation unit,...
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization symbol for this MaterializationUnit (if any).
An ObjectLayer implementation built on JITLink.
virtual Error add(ResourceTrackerSP RT, std::unique_ptr< MemoryBuffer > O, MaterializationUnit::Interface I)
Adds a MaterializationUnit for the object file in the given memory buffer to the JITDylib for the giv...
Definition: Layer.cpp:170
API to remove / transfer ownership of JIT resources.
Definition: Core.h:77
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition: Core.h:92
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Create(ObjectLayer &L, std::unique_ptr< MemoryBuffer > ArchiveBuffer, std::unique_ptr< object::Archive > Archive, VisitMembersFunction VisitMembers=VisitMembersFunction(), GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibrarySearchGenerator from the given memory buffer and Archive object.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:194
Pointer to a pooled string representing a symbol name.
Used to notify clients when symbols can not be found during a lookup.
Definition: Core.h:477
A utility class for serializing to a blob from a variadic list.
SPS tag type for expecteds, which are either a T or a string representing an error.
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.
@ IMAGE_FILE_MACHINE_AMD64
Definition: COFF.h:97
@ NUM_DATA_DIRECTORIES
Definition: COFF.h:646
static const char PEMagic[]
Definition: COFF.h:35
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:177
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:173
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition: Core.h:745
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
void lookupAndRecordAddrs(unique_function< void(Error)> OnRecorded, ExecutionSession &ES, LookupKind K, const JITDylibSearchOrder &SearchOrder, std::vector< std::pair< SymbolStringPtr, ExecutorAddr * > > Pairs, SymbolLookupFlags LookupFlags=SymbolLookupFlags::RequiredSymbol)
Record addresses of the given symbols in the given ExecutorAddrs.
static void addAliases(ExecutionSession &ES, SymbolAliasMap &Aliases, ArrayRef< std::pair< const char *, const char * > > AL)
Expected< MaterializationUnit::Interface > getObjectFileInterface(ExecutionSession &ES, MemoryBufferRef ObjBuffer)
Returns a MaterializationUnit::Interface for the object file contained in the given buffer,...
jitlink::Block & createHeaderBlock(MachOPlatform &MOP, const MachOPlatform::HeaderOptions &Opts, JITDylib &JD, jitlink::LinkGraph &G, jitlink::Section &HeaderSection)
RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition: Core.cpp:38
bool isCOFFInitializerSection(StringRef Name)
@ Ready
Emitted to memory, but waiting on transitive dependencies.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition: Error.h:1385
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:756
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:1873
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1766
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
The DOS compatible header at the front of all PE/COFF executables.
Definition: COFF.h:57
The 64-bit PE header that follows the COFF header.
Definition: COFF.h:144