LLVM 24.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
10
19#include "llvm/Object/COFF.h"
20
22
23#define DEBUG_TYPE "orc"
24
25using namespace llvm;
26using namespace llvm::orc;
27using namespace llvm::orc::shared;
28
29namespace llvm {
30namespace orc {
31namespace shared {
32
42
43} // namespace shared
44} // namespace orc
45} // namespace llvm
46namespace {
47
48class COFFHeaderMaterializationUnit : public MaterializationUnit {
49public:
50 COFFHeaderMaterializationUnit(COFFPlatform &CP,
51 const SymbolStringPtr &HeaderStartSymbol)
52 : MaterializationUnit(createHeaderInterface(CP, HeaderStartSymbol)),
53 CP(CP) {}
54
55 StringRef getName() const override { return "COFFHeaderMU"; }
56
57 void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
58 auto G = std::make_unique<jitlink::LinkGraph>(
59 "<COFFHeaderMU>", CP.getExecutionSession().getSymbolStringPool(),
60 CP.getExecutionSession().getTargetTriple(), SubtargetFeatures(),
62 auto &HeaderSection = G->createSection("__header", MemProt::Read);
63 auto &HeaderBlock = createHeaderBlock(*G, HeaderSection);
64
65 // Init symbol is __ImageBase symbol.
66 auto &ImageBaseSymbol = G->addDefinedSymbol(
67 HeaderBlock, 0, *R->getInitializerSymbol(), HeaderBlock.getSize(),
68 jitlink::Linkage::Strong, jitlink::Scope::Default, false, true);
69
70 addImageBaseRelocationEdge(HeaderBlock, ImageBaseSymbol);
71
72 CP.getObjectLinkingLayer().emit(std::move(R), std::move(G));
73 }
74
75 void discard(const JITDylib &JD, const SymbolStringPtr &Sym) override {}
76
77private:
78 struct HeaderSymbol {
79 const char *Name;
80 uint64_t Offset;
81 };
82
83 struct NTHeader {
85 object::coff_file_header FileHeader;
86 struct PEHeader {
87 object::pe32plus_header Header;
88 object::data_directory DataDirectory[COFF::NUM_DATA_DIRECTORIES + 1];
89 } OptionalHeader;
90 };
91
92 struct HeaderBlockContent {
93 object::dos_header DOSHeader;
94 COFFHeaderMaterializationUnit::NTHeader NTHeader;
95 };
96
97 static jitlink::Block &createHeaderBlock(jitlink::LinkGraph &G,
98 jitlink::Section &HeaderSection) {
99 HeaderBlockContent Hdr = {};
100
101 // Set up magic
102 Hdr.DOSHeader.Magic[0] = 'M';
103 Hdr.DOSHeader.Magic[1] = 'Z';
104 Hdr.DOSHeader.AddressOfNewExeHeader =
105 offsetof(HeaderBlockContent, NTHeader);
106 uint32_t PEMagic = *reinterpret_cast<const uint32_t *>(COFF::PEMagic);
107 Hdr.NTHeader.PEMagic = PEMagic;
108 Hdr.NTHeader.OptionalHeader.Header.Magic = COFF::PE32Header::PE32_PLUS;
109
110 switch (G.getTargetTriple().getArch()) {
111 case Triple::x86_64:
112 Hdr.NTHeader.FileHeader.Machine = COFF::IMAGE_FILE_MACHINE_AMD64;
113 break;
114 default:
115 llvm_unreachable("Unrecognized architecture");
116 }
117
118 auto HeaderContent = G.allocateContent(
119 ArrayRef<char>(reinterpret_cast<const char *>(&Hdr), sizeof(Hdr)));
120
121 return G.createContentBlock(HeaderSection, HeaderContent, ExecutorAddr(), 8,
122 0);
123 }
124
125 static void addImageBaseRelocationEdge(jitlink::Block &B,
126 jitlink::Symbol &ImageBase) {
127 auto ImageBaseOffset = offsetof(HeaderBlockContent, NTHeader) +
128 offsetof(NTHeader, OptionalHeader) +
129 offsetof(object::pe32plus_header, ImageBase);
130 B.addEdge(jitlink::x86_64::Pointer64, ImageBaseOffset, ImageBase, 0);
131 }
132
133 static MaterializationUnit::Interface
134 createHeaderInterface(COFFPlatform &MOP,
135 const SymbolStringPtr &HeaderStartSymbol) {
136 SymbolFlagsMap HeaderSymbolFlags;
137
138 HeaderSymbolFlags[HeaderStartSymbol] = JITSymbolFlags::Exported;
139
140 return MaterializationUnit::Interface(std::move(HeaderSymbolFlags),
141 HeaderStartSymbol);
142 }
143
144 COFFPlatform &CP;
145};
146
147} // end anonymous namespace
148
149namespace llvm {
150namespace orc {
151
152Expected<std::unique_ptr<COFFPlatform>>
154 std::unique_ptr<MemoryBuffer> OrcRuntimeArchiveBuffer,
155 LoadDynamicLibrary LoadDynLibrary, bool StaticVCRuntime,
156 const char *VCRuntimePath,
157 std::optional<SymbolAliasMap> RuntimeAliases) {
158
159 auto &ES = ObjLinkingLayer.getExecutionSession();
160
161 // If the target is not supported then bail out immediately.
162 if (!supportedTarget(ES.getTargetTriple()))
163 return make_error<StringError>("Unsupported COFFPlatform triple: " +
164 ES.getTargetTriple().str(),
166
167 auto GeneratorArchive =
168 object::Archive::create(OrcRuntimeArchiveBuffer->getMemBufferRef());
169 if (!GeneratorArchive)
170 return GeneratorArchive.takeError();
171
172 std::set<std::string> DylibsToPreload;
173 auto OrcRuntimeArchiveGenerator = StaticLibraryDefinitionGenerator::Create(
174 ObjLinkingLayer, nullptr, std::move(*GeneratorArchive),
175 COFFImportFileScanner(DylibsToPreload));
176 if (!OrcRuntimeArchiveGenerator)
177 return OrcRuntimeArchiveGenerator.takeError();
178
179 // We need a second instance of the archive (for now) for the Platform. We
180 // can `cantFail` this call, since if it were going to fail it would have
181 // failed above.
182 auto RuntimeArchive = cantFail(
183 object::Archive::create(OrcRuntimeArchiveBuffer->getMemBufferRef()));
184
185 // Create default aliases if the caller didn't supply any.
186 if (!RuntimeAliases)
187 RuntimeAliases = standardPlatformAliases(ES);
188
189 // Define the aliases.
190 if (auto Err = PlatformJD.define(symbolAliases(std::move(*RuntimeAliases))))
191 return std::move(Err);
192
193 {
194 // Add JIT dispatch reexports from bootstrap JITDylib.
195 auto Exports = buildSimpleReexportsAliasMap(
196 ES.getBootstrapJITDylib(),
197 {{ES.intern(rt::DispatchName), ES.intern(rt::DispatchCtxName)}});
198 if (!Exports)
199 return Exports.takeError();
200 if (auto Err =
201 PlatformJD.define(reexports(ES.getBootstrapJITDylib(), *Exports)))
202 return Err;
203 }
204
205 // Create the instance.
206 Error Err = Error::success();
207 auto P = std::unique_ptr<COFFPlatform>(new COFFPlatform(
208 ObjLinkingLayer, PlatformJD, std::move(*OrcRuntimeArchiveGenerator),
209 std::move(DylibsToPreload), std::move(OrcRuntimeArchiveBuffer),
210 std::move(RuntimeArchive), std::move(LoadDynLibrary), StaticVCRuntime,
211 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
335
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_dlupdate", "__orc_rt_coff_jit_dlupdate"},
360 {"__orc_rt_jit_dlclose", "__orc_rt_coff_jit_dlclose"},
361 {"__orc_rt_jit_dlsym", "__orc_rt_coff_jit_dlsym"},
362 {"__orc_rt_log_error", "__orc_rt_log_error_to_stderr"}};
363
365 StandardRuntimeUtilityAliases);
366}
367
368bool COFFPlatform::supportedTarget(const Triple &TT) {
369 switch (TT.getArch()) {
370 case Triple::x86_64:
371 return true;
372 default:
373 return false;
374 }
375}
376
377COFFPlatform::COFFPlatform(
378 ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD,
379 std::unique_ptr<StaticLibraryDefinitionGenerator> OrcRuntimeGenerator,
380 std::set<std::string> DylibsToPreload,
381 std::unique_ptr<MemoryBuffer> OrcRuntimeArchiveBuffer,
382 std::unique_ptr<object::Archive> OrcRuntimeArchive,
383 LoadDynamicLibrary LoadDynLibrary, bool StaticVCRuntime,
384 const char *VCRuntimePath, Error &Err)
385 : ES(ObjLinkingLayer.getExecutionSession()),
386 ObjLinkingLayer(ObjLinkingLayer),
387 LoadDynLibrary(std::move(LoadDynLibrary)),
388 OrcRuntimeArchiveBuffer(std::move(OrcRuntimeArchiveBuffer)),
389 OrcRuntimeArchive(std::move(OrcRuntimeArchive)),
390 StaticVCRuntime(StaticVCRuntime),
391 COFFHeaderStartSymbol(ES.intern("__ImageBase")) {
393
394 Bootstrapping.store(true);
395 ObjLinkingLayer.addPlugin(std::make_unique<COFFPlatformPlugin>(*this));
396
397 // Load vc runtime
398 auto VCRT =
399 COFFVCRuntimeBootstrapper::Create(ES, ObjLinkingLayer, VCRuntimePath);
400 if (!VCRT) {
401 Err = VCRT.takeError();
402 return;
403 }
404 VCRuntimeBootstrap = std::move(*VCRT);
405
406 auto ImportedLibs =
407 StaticVCRuntime ? VCRuntimeBootstrap->loadStaticVCRuntime(PlatformJD)
408 : VCRuntimeBootstrap->loadDynamicVCRuntime(PlatformJD);
409 if (!ImportedLibs) {
410 Err = ImportedLibs.takeError();
411 return;
412 }
413
414 for (auto &Lib : *ImportedLibs)
415 DylibsToPreload.insert(Lib);
416
417 PlatformJD.addGenerator(std::move(OrcRuntimeGenerator));
418
419 // PlatformJD hasn't been set up by the platform yet (since we're creating
420 // the platform now), so set it up.
421 if (auto E2 = setupJITDylib(PlatformJD)) {
422 Err = std::move(E2);
423 return;
424 }
425
426 for (auto& Lib : DylibsToPreload)
427 if (auto E2 = this->LoadDynLibrary(PlatformJD, Lib)) {
428 Err = std::move(E2);
429 return;
430 }
431
432 if (StaticVCRuntime)
433 if (auto E2 = VCRuntimeBootstrap->initializeStaticVCRuntime(PlatformJD)) {
434 Err = std::move(E2);
435 return;
436 }
437
438 // Associate wrapper function tags with JIT-side function implementations.
439 if (auto E2 = associateRuntimeSupportFunctions(PlatformJD)) {
440 Err = std::move(E2);
441 return;
442 }
443
444 // Lookup addresses of runtime functions callable by the platform,
445 // call the platform bootstrap function to initialize the platform-state
446 // object in the executor.
447 if (auto E2 = bootstrapCOFFRuntime(PlatformJD)) {
448 Err = std::move(E2);
449 return;
450 }
451
452 Bootstrapping.store(false);
453 JDBootstrapStates.clear();
454}
455
456Expected<COFFPlatform::JITDylibDepMap>
457COFFPlatform::buildJDDepMap(JITDylib &JD) {
458 return ES.runSessionLocked([&]() -> Expected<JITDylibDepMap> {
459 JITDylibDepMap JDDepMap;
460
461 SmallVector<JITDylib *, 16> Worklist({&JD});
462 while (!Worklist.empty()) {
463 auto CurJD = Worklist.back();
464 Worklist.pop_back();
465
466 auto &DM = JDDepMap[CurJD];
467 CurJD->withLinkOrderDo([&](const JITDylibSearchOrder &O) {
468 DM.reserve(O.size());
469 for (auto &KV : O) {
470 if (KV.first == CurJD)
471 continue;
472 {
473 // Bare jitdylibs not known to the platform
474 std::lock_guard<std::mutex> Lock(PlatformMutex);
475 if (!JITDylibToHeaderAddr.count(KV.first)) {
476 LLVM_DEBUG({
477 dbgs() << "JITDylib unregistered to COFFPlatform detected in "
478 "LinkOrder: "
479 << CurJD->getName() << "\n";
480 });
481 continue;
482 }
483 }
484 DM.push_back(KV.first);
485 // Push unvisited entry.
486 if (JDDepMap.try_emplace(KV.first).second)
487 Worklist.push_back(KV.first);
488 }
489 });
490 }
491 return std::move(JDDepMap);
492 });
493}
494
495void COFFPlatform::pushInitializersLoop(PushInitializersSendResultFn SendResult,
496 JITDylibSP JD,
497 JITDylibDepMap &JDDepMap) {
498 SmallVector<JITDylib *, 16> Worklist({JD.get()});
499 DenseSet<JITDylib *> Visited({JD.get()});
500 DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols;
501 ES.runSessionLocked([&]() {
502 while (!Worklist.empty()) {
503 auto CurJD = Worklist.back();
504 Worklist.pop_back();
505
506 auto RISItr = RegisteredInitSymbols.find(CurJD);
507 if (RISItr != RegisteredInitSymbols.end()) {
508 NewInitSymbols[CurJD] = std::move(RISItr->second);
509 RegisteredInitSymbols.erase(RISItr);
510 }
511
512 for (auto *DepJD : JDDepMap[CurJD])
513 if (Visited.insert(DepJD).second)
514 Worklist.push_back(DepJD);
515 }
516 });
517
518 // If there are no further init symbols to look up then send the link order
519 // (as a list of header addresses) to the caller.
520 if (NewInitSymbols.empty()) {
521 // Build the dep info map to return.
522 COFFJITDylibDepInfoMap DIM;
523 DIM.reserve(JDDepMap.size());
524 for (auto &KV : JDDepMap) {
525 std::lock_guard<std::mutex> Lock(PlatformMutex);
526 COFFJITDylibDepInfo DepInfo;
527 DepInfo.reserve(KV.second.size());
528 for (auto &Dep : KV.second) {
529 DepInfo.push_back(JITDylibToHeaderAddr[Dep]);
530 }
531 auto H = JITDylibToHeaderAddr[KV.first];
532 DIM.push_back(std::make_pair(H, std::move(DepInfo)));
533 }
534 SendResult(DIM);
535 return;
536 }
537
538 // Otherwise issue a lookup and re-run this phase when it completes.
540 [this, SendResult = std::move(SendResult), &JD,
541 JDDepMap = std::move(JDDepMap)](Error Err) mutable {
542 if (Err)
543 SendResult(std::move(Err));
544 else
545 pushInitializersLoop(std::move(SendResult), JD, JDDepMap);
546 },
547 ES, std::move(NewInitSymbols));
548}
549
550void COFFPlatform::rt_pushInitializers(PushInitializersSendResultFn SendResult,
551 ExecutorAddr JDHeaderAddr) {
552 JITDylibSP JD;
553 {
554 std::lock_guard<std::mutex> Lock(PlatformMutex);
555 auto I = HeaderAddrToJITDylib.find(JDHeaderAddr);
556 if (I != HeaderAddrToJITDylib.end())
557 JD = I->second;
558 }
559
560 LLVM_DEBUG({
561 dbgs() << "COFFPlatform::rt_pushInitializers(" << JDHeaderAddr << ") ";
562 if (JD)
563 dbgs() << "pushing initializers for " << JD->getName() << "\n";
564 else
565 dbgs() << "No JITDylib for header address.\n";
566 });
567
568 if (!JD) {
569 SendResult(make_error<StringError>("No JITDylib with header addr " +
570 formatv("{0:x}", JDHeaderAddr),
572 return;
573 }
574
575 auto JDDepMap = buildJDDepMap(*JD);
576 if (!JDDepMap) {
577 SendResult(JDDepMap.takeError());
578 return;
579 }
580
581 pushInitializersLoop(std::move(SendResult), JD, *JDDepMap);
582}
583
584void COFFPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult,
585 ExecutorAddr Handle, StringRef SymbolName) {
586 LLVM_DEBUG(dbgs() << "COFFPlatform::rt_lookupSymbol(\"" << Handle << "\")\n");
587
588 JITDylib *JD = nullptr;
589
590 {
591 std::lock_guard<std::mutex> Lock(PlatformMutex);
592 auto I = HeaderAddrToJITDylib.find(Handle);
593 if (I != HeaderAddrToJITDylib.end())
594 JD = I->second;
595 }
596
597 if (!JD) {
598 LLVM_DEBUG(dbgs() << " No JITDylib for handle " << Handle << "\n");
599 SendResult(make_error<StringError>("No JITDylib associated with handle " +
600 formatv("{0:x}", Handle),
602 return;
603 }
604
605 // Use functor class to work around XL build compiler issue on AIX.
606 class RtLookupNotifyComplete {
607 public:
608 RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult)
609 : SendResult(std::move(SendResult)) {}
610 void operator()(Expected<SymbolMap> Result) {
611 if (Result) {
612 assert(Result->size() == 1 && "Unexpected result map count");
613 SendResult(Result->begin()->second.getAddress());
614 } else {
615 SendResult(Result.takeError());
616 }
617 }
618
619 private:
620 SendSymbolAddressFn SendResult;
621 };
622
623 ES.lookup(
625 SymbolLookupSet(ES.intern(SymbolName)), SymbolState::Ready,
626 RtLookupNotifyComplete(std::move(SendResult)), NoDependenciesToRegister);
627}
628
629Error COFFPlatform::associateRuntimeSupportFunctions(JITDylib &PlatformJD) {
631
632 using LookupSymbolSPSSig =
633 SPSExpected<SPSExecutorAddr>(SPSExecutorAddr, SPSString);
634 WFs[ES.intern("__orc_rt_coff_symbol_lookup_tag")] =
635 ES.wrapAsyncWithSPS<LookupSymbolSPSSig>(this,
636 &COFFPlatform::rt_lookupSymbol);
637 using PushInitializersSPSSig =
638 SPSExpected<SPSCOFFJITDylibDepInfoMap>(SPSExecutorAddr);
639 WFs[ES.intern("__orc_rt_coff_push_initializers_tag")] =
640 ES.wrapAsyncWithSPS<PushInitializersSPSSig>(
641 this, &COFFPlatform::rt_pushInitializers);
642
643 return ES.registerJITDispatchHandlers(PlatformJD, std::move(WFs));
644}
645
646Error COFFPlatform::runBootstrapInitializers(JDBootstrapState &BState) {
647 llvm::sort(BState.Initializers);
648 if (auto Err =
649 runBootstrapSubsectionInitializers(BState, ".CRT$XIA", ".CRT$XIZ"))
650 return Err;
651
652 if (auto Err = runSymbolIfExists(*BState.JD, "__run_after_c_init"))
653 return Err;
654
655 if (auto Err =
656 runBootstrapSubsectionInitializers(BState, ".CRT$XCA", ".CRT$XCZ"))
657 return Err;
658 return Error::success();
659}
660
661Error COFFPlatform::runBootstrapSubsectionInitializers(JDBootstrapState &BState,
662 StringRef Start,
663 StringRef End) {
664 CallInt32VoidProxy CallInitializer;
665 if (auto Err = lookupAndApply(
666 ES.getBootstrapJITDylib(),
667 {recordProxy<sps::CallInt32VoidProxySpec>(&CallInitializer)}))
668 return Err;
669 for (auto &Initializer : BState.Initializers)
670 if (Initializer.first >= Start && Initializer.first <= End &&
671 Initializer.second) {
672 auto Res = CallInitializer(ES, Initializer.second);
673 if (!Res)
674 return Res.takeError();
675 }
676 return Error::success();
677}
678
679Error COFFPlatform::bootstrapCOFFRuntime(JITDylib &PlatformJD) {
680 // Lookup of runtime symbols causes the collection of initializers if
681 // it's static linking setting.
682 if (auto Err = lookupAndApply(
683 PlatformJD, {recordAddr("__orc_rt_coff_platform_bootstrap",
684 &orc_rt_coff_platform_bootstrap),
685 recordAddr("__orc_rt_coff_platform_shutdown",
686 &orc_rt_coff_platform_shutdown),
687 recordAddr("__orc_rt_coff_register_jitdylib",
688 &orc_rt_coff_register_jitdylib),
689 recordAddr("__orc_rt_coff_deregister_jitdylib",
690 &orc_rt_coff_deregister_jitdylib),
691 recordAddr("__orc_rt_coff_register_object_sections",
692 &orc_rt_coff_register_object_sections),
693 recordAddr("__orc_rt_coff_deregister_object_sections",
694 &orc_rt_coff_deregister_object_sections)}))
695 return Err;
696
697 // Call bootstrap functions
698 if (auto Err = ES.callSPSWrapper<void()>(orc_rt_coff_platform_bootstrap))
699 return Err;
700
701 // Do the pending jitdylib registration actions that we couldn't do
702 // because orc runtime was not linked fully.
703 for (auto KV : JDBootstrapStates) {
704 auto &JDBState = KV.second;
705 if (auto Err = ES.callSPSWrapper<void(SPSString, SPSExecutorAddr)>(
706 orc_rt_coff_register_jitdylib, JDBState.JDName,
707 JDBState.HeaderAddr))
708 return Err;
709
710 for (auto &ObjSectionMap : JDBState.ObjectSectionsMaps)
711 if (auto Err = ES.callSPSWrapper<void(SPSExecutorAddr,
713 orc_rt_coff_register_object_sections, JDBState.HeaderAddr,
714 ObjSectionMap, false))
715 return Err;
716 }
717
718 // Run static initializers collected in bootstrap stage.
719 for (auto KV : JDBootstrapStates) {
720 auto &JDBState = KV.second;
721 if (auto Err = runBootstrapInitializers(JDBState))
722 return Err;
723 }
724
725 return Error::success();
726}
727
728Error COFFPlatform::runSymbolIfExists(JITDylib &PlatformJD,
729 StringRef SymbolName) {
730 ExecutorAddr TargetFn;
731 if (auto Err = lookupAndApply(
732 PlatformJD, {recordAddr(SymbolName, &TargetFn,
734 return Err;
735 if (!TargetFn)
736 return Error::success(); // No target function.
737
738 CallInt32VoidProxy CallFn;
739 if (auto Err =
740 lookupAndApply(ES.getBootstrapJITDylib(),
741 {recordProxy<sps::CallInt32VoidProxySpec>(&CallFn)}))
742 return Err;
743
744 return CallFn(ES, TargetFn).takeError();
745}
746
747void COFFPlatform::COFFPlatformPlugin::modifyPassConfig(
748 MaterializationResponsibility &MR, jitlink::LinkGraph &LG,
749 jitlink::PassConfiguration &Config) {
750
751 bool IsBootstrapping = CP.Bootstrapping.load();
752
753 if (auto InitSymbol = MR.getInitializerSymbol()) {
754 if (InitSymbol == CP.COFFHeaderStartSymbol) {
755 Config.PostAllocationPasses.push_back(
756 [this, &MR, IsBootstrapping](jitlink::LinkGraph &G) {
757 return associateJITDylibHeaderSymbol(G, MR, IsBootstrapping);
758 });
759 return;
760 }
761 Config.PrePrunePasses.push_back([this, &MR](jitlink::LinkGraph &G) {
762 return preserveInitializerSections(G, MR);
763 });
764 }
765
766 if (!IsBootstrapping)
767 Config.PostFixupPasses.push_back(
768 [this, &JD = MR.getTargetJITDylib()](jitlink::LinkGraph &G) {
769 return registerObjectPlatformSections(G, JD);
770 });
771 else
772 Config.PostFixupPasses.push_back(
773 [this, &JD = MR.getTargetJITDylib()](jitlink::LinkGraph &G) {
774 return registerObjectPlatformSectionsInBootstrap(G, JD);
775 });
776}
777
778Error COFFPlatform::COFFPlatformPlugin::associateJITDylibHeaderSymbol(
779 jitlink::LinkGraph &G, MaterializationResponsibility &MR,
780 bool IsBootstraping) {
781 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
782 return *Sym->getName() == *CP.COFFHeaderStartSymbol;
783 });
784 assert(I != G.defined_symbols().end() && "Missing COFF header start symbol");
785
786 auto &JD = MR.getTargetJITDylib();
787 std::lock_guard<std::mutex> Lock(CP.PlatformMutex);
788 auto HeaderAddr = (*I)->getAddress();
789 CP.JITDylibToHeaderAddr[&JD] = HeaderAddr;
790 CP.HeaderAddrToJITDylib[HeaderAddr] = &JD;
791 if (!IsBootstraping) {
792 G.allocActions().push_back(
794 SPSArgList<SPSString, SPSExecutorAddr>>(
795 CP.orc_rt_coff_register_jitdylib, JD.getName(), HeaderAddr)),
796 cantFail(WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>(
797 CP.orc_rt_coff_deregister_jitdylib, HeaderAddr))});
798 } else {
799 G.allocActions().push_back(
800 {{},
801 cantFail(WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>(
802 CP.orc_rt_coff_deregister_jitdylib, HeaderAddr))});
803 JDBootstrapState BState;
804 BState.JD = &JD;
805 BState.JDName = JD.getName();
806 BState.HeaderAddr = HeaderAddr;
807 CP.JDBootstrapStates.emplace(&JD, BState);
808 }
809
810 return Error::success();
811}
812
813Error COFFPlatform::COFFPlatformPlugin::registerObjectPlatformSections(
814 jitlink::LinkGraph &G, JITDylib &JD) {
815 COFFObjectSectionsMap ObjSecs;
816 auto HeaderAddr = CP.JITDylibToHeaderAddr[&JD];
817 assert(HeaderAddr && "Must be registered jitdylib");
818 for (auto &S : G.sections()) {
819 jitlink::SectionRange Range(S);
820 if (Range.getSize())
821 ObjSecs.push_back(std::make_pair(S.getName().str(), Range.getRange()));
822 }
823
824 G.allocActions().push_back(
826 CP.orc_rt_coff_register_object_sections, HeaderAddr, ObjSecs, true)),
827 cantFail(
829 CP.orc_rt_coff_deregister_object_sections, HeaderAddr,
830 ObjSecs))});
831
832 return Error::success();
833}
834
835Error COFFPlatform::COFFPlatformPlugin::preserveInitializerSections(
836 jitlink::LinkGraph &G, MaterializationResponsibility &MR) {
837
838 if (const auto &InitSymName = MR.getInitializerSymbol()) {
839
840 jitlink::Symbol *InitSym = nullptr;
841
842 for (auto &InitSection : G.sections()) {
843 // Skip non-init sections.
844 if (!isCOFFInitializerSection(InitSection.getName()) ||
845 InitSection.empty())
846 continue;
847
848 // Create the init symbol if it has not been created already and attach it
849 // to the first block.
850 if (!InitSym) {
851 auto &B = **InitSection.blocks().begin();
852 InitSym = &G.addDefinedSymbol(
853 B, 0, *InitSymName, B.getSize(), jitlink::Linkage::Strong,
855 }
856
857 // Add keep-alive edges to anonymous symbols in all other init blocks.
858 for (auto *B : InitSection.blocks()) {
859 if (B == &InitSym->getBlock())
860 continue;
861
862 auto &S = G.addAnonymousSymbol(*B, 0, B->getSize(), false, true);
863 InitSym->getBlock().addEdge(jitlink::Edge::KeepAlive, 0, S, 0);
864 }
865 }
866 }
867
868 return Error::success();
869}
870
871Error COFFPlatform::COFFPlatformPlugin::
872 registerObjectPlatformSectionsInBootstrap(jitlink::LinkGraph &G,
873 JITDylib &JD) {
874 std::lock_guard<std::mutex> Lock(CP.PlatformMutex);
875 auto HeaderAddr = CP.JITDylibToHeaderAddr[&JD];
876 COFFObjectSectionsMap ObjSecs;
877 for (auto &S : G.sections()) {
878 jitlink::SectionRange Range(S);
879 if (Range.getSize())
880 ObjSecs.push_back(std::make_pair(S.getName().str(), Range.getRange()));
881 }
882
883 G.allocActions().push_back(
884 {{},
885 cantFail(
887 CP.orc_rt_coff_deregister_object_sections, HeaderAddr,
888 ObjSecs))});
889
890 auto &BState = CP.JDBootstrapStates[&JD];
891 BState.ObjectSectionsMaps.push_back(std::move(ObjSecs));
892
893 // Collect static initializers
894 for (auto &S : G.sections())
895 if (isCOFFInitializerSection(S.getName()))
896 for (auto *B : S.blocks()) {
897 if (B->edges_empty())
898 continue;
899 for (auto &E : B->edges())
900 BState.Initializers.push_back(std::make_pair(
901 S.getName().str(), E.getTarget().getAddress() + E.getAddend()));
902 }
903
904 return Error::success();
905}
906
907} // End namespace orc.
908} // End namespace llvm.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
#define _
#define offsetof(TYPE, MEMBER)
#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
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
static StringRef getName(Value *V)
#define LLVM_DEBUG(...)
Definition Debug.h:119
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:219
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
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
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,...
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
static Expected< std::unique_ptr< Archive > > create(MemoryBufferRef Source)
Definition Archive.cpp:785
Mediates between COFF initialization and ExecutionSession state.
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.
unique_function< Error(JITDylib &JD, StringRef DLLFileName)> LoadDynamicLibrary
A function that will be called with the name of dll file that must be loaded.
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 LLVM_ABI 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:1111
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1170
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Definition Core.h:1134
Represents an address in the executor process.
Represents a JIT'd dynamic library.
Definition Core.h:675
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:1654
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition Core.h:1637
LinkGraphLinkingLayer & addPlugin(std::shared_ptr< Plugin > P)
Add a plugin.
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:349
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
Definition Core.h:388
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition Core.h:374
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:63
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition Core.h:78
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.
Pointer to a pooled string representing a symbol name.
A utility class for serializing to a blob from a variadic list.
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:98
@ NUM_DATA_DIRECTORIES
Definition COFF.h:647
static const char PEMagic[]
Definition COFF.h:36
SPSSequence< SPSExecutorAddr > SPSCOFFJITDylibDepInfo
SPSSequence< char > SPSString
SPS tag type for strings, which are equivalent to sequences of chars.
SPSArgList< SPSExecutorAddr, SPSCOFFObjectSectionsMap, bool > SPSCOFFRegisterObjectSectionsArgs
SPSSequence< SPSTuple< SPSString, SPSExecutorAddrRange > > SPSCOFFObjectSectionsMap
SPSSequence< SPSTuple< SPSExecutorAddr, SPSCOFFJITDylibDepInfo > > SPSCOFFJITDylibDepInfoMap
SPSArgList< SPSExecutorAddr, SPSCOFFObjectSectionsMap > SPSCOFFDeregisterObjectSectionsArgs
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:148
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition Core.h:58
Proxy< int32_t(ExecutorAddr)> CallInt32VoidProxy
Protocol-agnostic interface for running an int32_t() function in the executor.
Definition CallProxies.h:45
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition Core.h:523
LLVM_ABI void lookupAndApply(unique_function< void(Error)> OnApplied, LookupKind K, const JITDylibSearchOrder &SearchOrder, ArrayRef< LookupPrepareFn > PrepareFns)
Resolve the symbols contributed by every prepare function with a single lookup, then let each of thei...
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:532
static void addAliases(ExecutionSession &ES, SymbolAliasMap &Aliases, ArrayRef< std::pair< const char *, const char * > > AL)
LLVM_ABI 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)
LookupPrepareFn recordAddr(StringRef Name, ExecutorAddr *A, SymbolLookupFlags LF=SymbolLookupFlags::RequiredSymbol)
Records the address of the symbol with the given name.
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition Core.cpp:40
LLVM_ABI bool isCOFFInitializerSection(StringRef Name)
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:551
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition Core.h:173
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:482
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
detail::packed_endian_specific_integral< uint32_t, llvm::endianness::little, unaligned > ulittle32_t
Definition Endian.h:270
This is an optimization pass for GlobalISel generic memory operations.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
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:1636
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...
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:1917
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:1772
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878