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
21#include "llvm/Object/COFF.h"
22
24
26
27#define DEBUG_TYPE "orc"
28
29using namespace llvm;
30using namespace llvm::orc;
31using namespace llvm::orc::shared;
32
33namespace llvm {
34namespace orc {
35namespace shared {
36
46
47} // namespace shared
48} // namespace orc
49} // namespace llvm
50namespace {
51
52class COFFHeaderMaterializationUnit : public MaterializationUnit {
53public:
54 COFFHeaderMaterializationUnit(COFFPlatform &CP,
55 const SymbolStringPtr &HeaderStartSymbol)
56 : MaterializationUnit(createHeaderInterface(CP, HeaderStartSymbol)),
57 CP(CP) {}
58
59 StringRef getName() const override { return "COFFHeaderMU"; }
60
61 void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
62 auto G = std::make_unique<jitlink::LinkGraph>(
63 "<COFFHeaderMU>", CP.getExecutionSession().getSymbolStringPool(),
64 CP.getExecutionSession().getTargetTriple(), SubtargetFeatures(),
66 auto &HeaderSection = G->createSection("__header", MemProt::Read);
67 auto &HeaderBlock = createHeaderBlock(*G, HeaderSection);
68
69 // Init symbol is __ImageBase symbol.
70 auto &ImageBaseSymbol = G->addDefinedSymbol(
71 HeaderBlock, 0, *R->getInitializerSymbol(), HeaderBlock.getSize(),
72 jitlink::Linkage::Strong, jitlink::Scope::Default, false, true);
73
74 addImageBaseRelocationEdge(HeaderBlock, ImageBaseSymbol);
75
76 CP.getObjectLinkingLayer().emit(std::move(R), std::move(G));
77 }
78
79 void discard(const JITDylib &JD, const SymbolStringPtr &Sym) override {}
80
81private:
82 struct HeaderSymbol {
83 const char *Name;
84 uint64_t Offset;
85 };
86
87 struct NTHeader {
89 object::coff_file_header FileHeader;
90 struct PEHeader {
91 object::pe32plus_header Header;
92 object::data_directory DataDirectory[COFF::NUM_DATA_DIRECTORIES + 1];
93 } OptionalHeader;
94 };
95
96 struct HeaderBlockContent {
97 object::dos_header DOSHeader;
98 COFFHeaderMaterializationUnit::NTHeader NTHeader;
99 };
100
101 static jitlink::Block &createHeaderBlock(jitlink::LinkGraph &G,
102 jitlink::Section &HeaderSection) {
103 HeaderBlockContent Hdr = {};
104
105 // Set up magic
106 Hdr.DOSHeader.Magic[0] = 'M';
107 Hdr.DOSHeader.Magic[1] = 'Z';
108 Hdr.DOSHeader.AddressOfNewExeHeader =
109 offsetof(HeaderBlockContent, NTHeader);
110 uint32_t PEMagic = *reinterpret_cast<const uint32_t *>(COFF::PEMagic);
111 Hdr.NTHeader.PEMagic = PEMagic;
112 Hdr.NTHeader.OptionalHeader.Header.Magic = COFF::PE32Header::PE32_PLUS;
113
114 switch (G.getTargetTriple().getArch()) {
115 case Triple::x86_64:
116 Hdr.NTHeader.FileHeader.Machine = COFF::IMAGE_FILE_MACHINE_AMD64;
117 break;
118 default:
119 llvm_unreachable("Unrecognized architecture");
120 }
121
122 auto HeaderContent = G.allocateContent(
123 ArrayRef<char>(reinterpret_cast<const char *>(&Hdr), sizeof(Hdr)));
124
125 return G.createContentBlock(HeaderSection, HeaderContent, ExecutorAddr(), 8,
126 0);
127 }
128
129 static void addImageBaseRelocationEdge(jitlink::Block &B,
130 jitlink::Symbol &ImageBase) {
131 auto ImageBaseOffset = offsetof(HeaderBlockContent, NTHeader) +
132 offsetof(NTHeader, OptionalHeader) +
133 offsetof(object::pe32plus_header, ImageBase);
134 B.addEdge(jitlink::x86_64::Pointer64, ImageBaseOffset, ImageBase, 0);
135 }
136
137 static MaterializationUnit::Interface
138 createHeaderInterface(COFFPlatform &MOP,
139 const SymbolStringPtr &HeaderStartSymbol) {
140 SymbolFlagsMap HeaderSymbolFlags;
141
142 HeaderSymbolFlags[HeaderStartSymbol] = JITSymbolFlags::Exported;
143
144 return MaterializationUnit::Interface(std::move(HeaderSymbolFlags),
145 HeaderStartSymbol);
146 }
147
148 COFFPlatform &CP;
149};
150
151} // end anonymous namespace
152
153namespace llvm {
154namespace orc {
155
156Expected<std::unique_ptr<COFFPlatform>>
158 std::unique_ptr<MemoryBuffer> OrcRuntimeArchiveBuffer,
159 LoadDynamicLibrary LoadDynLibrary, bool StaticVCRuntime,
160 const char *VCRuntimePath,
161 std::optional<SymbolAliasMap> RuntimeAliases) {
162
163 auto &ES = ObjLinkingLayer.getExecutionSession();
164
165 // If the target is not supported then bail out immediately.
166 if (!supportedTarget(ES.getTargetTriple()))
167 return make_error<StringError>("Unsupported COFFPlatform triple: " +
168 ES.getTargetTriple().str(),
170
171 auto GeneratorArchive =
172 object::Archive::create(OrcRuntimeArchiveBuffer->getMemBufferRef());
173 if (!GeneratorArchive)
174 return GeneratorArchive.takeError();
175
176 std::set<std::string> DylibsToPreload;
177 auto OrcRuntimeArchiveGenerator = StaticLibraryDefinitionGenerator::Create(
178 ObjLinkingLayer, nullptr, std::move(*GeneratorArchive),
179 COFFImportFileScanner(DylibsToPreload));
180 if (!OrcRuntimeArchiveGenerator)
181 return OrcRuntimeArchiveGenerator.takeError();
182
183 // We need a second instance of the archive (for now) for the Platform. We
184 // can `cantFail` this call, since if it were going to fail it would have
185 // failed above.
186 auto RuntimeArchive = cantFail(
187 object::Archive::create(OrcRuntimeArchiveBuffer->getMemBufferRef()));
188
189 // Create default aliases if the caller didn't supply any.
190 if (!RuntimeAliases)
191 RuntimeAliases = standardPlatformAliases(ES);
192
193 // Define the aliases.
194 if (auto Err = PlatformJD.define(symbolAliases(std::move(*RuntimeAliases))))
195 return std::move(Err);
196
197 {
198 // Add JIT dispatch reexports from bootstrap JITDylib.
199 auto Exports = buildSimpleReexportsAliasMap(
200 ES.getBootstrapJITDylib(),
201 {{ES.intern(rt::DispatchName), ES.intern(rt::DispatchCtxName)}});
202 if (!Exports)
203 return Exports.takeError();
204 if (auto Err =
205 PlatformJD.define(reexports(ES.getBootstrapJITDylib(), *Exports)))
206 return Err;
207 }
208
209 // Create the instance.
210 Error Err = Error::success();
211 auto P = std::unique_ptr<COFFPlatform>(new COFFPlatform(
212 ObjLinkingLayer, PlatformJD, std::move(*OrcRuntimeArchiveGenerator),
213 std::move(DylibsToPreload), std::move(OrcRuntimeArchiveBuffer),
214 std::move(RuntimeArchive), std::move(LoadDynLibrary), StaticVCRuntime,
215 VCRuntimePath, Err));
216 if (Err)
217 return std::move(Err);
218 return std::move(P);
219}
220
223 const char *OrcRuntimePath,
224 LoadDynamicLibrary LoadDynLibrary, bool StaticVCRuntime,
225 const char *VCRuntimePath,
226 std::optional<SymbolAliasMap> RuntimeAliases) {
227
228 auto ArchiveBuffer = MemoryBuffer::getFile(OrcRuntimePath);
229 if (!ArchiveBuffer)
230 return createFileError(OrcRuntimePath, ArchiveBuffer.getError());
231
232 return Create(ObjLinkingLayer, PlatformJD, std::move(*ArchiveBuffer),
233 std::move(LoadDynLibrary), StaticVCRuntime, VCRuntimePath,
234 std::move(RuntimeAliases));
235}
236
237Expected<MemoryBufferRef> COFFPlatform::getPerJDObjectFile() {
238 auto PerJDObj = OrcRuntimeArchive->findSym("__orc_rt_coff_per_jd_marker");
239 if (!PerJDObj)
240 return PerJDObj.takeError();
241
242 if (!*PerJDObj)
243 return make_error<StringError>("Could not find per jd object file",
245
246 auto Buffer = (*PerJDObj)->getAsBinary();
247 if (!Buffer)
248 return Buffer.takeError();
249
250 return (*Buffer)->getMemoryBufferRef();
251}
252
254 ArrayRef<std::pair<const char *, const char *>> AL) {
255 for (auto &KV : AL) {
256 auto AliasName = ES.intern(KV.first);
257 assert(!Aliases.count(AliasName) && "Duplicate symbol name in alias map");
258 Aliases[std::move(AliasName)] = {ES.intern(KV.second),
260 }
261}
262
264 if (auto Err = JD.define(std::make_unique<COFFHeaderMaterializationUnit>(
265 *this, COFFHeaderStartSymbol)))
266 return Err;
267
268 if (auto Err = ES.lookup({&JD}, COFFHeaderStartSymbol).takeError())
269 return Err;
270
271 // Define the CXX aliases.
272 SymbolAliasMap CXXAliases;
273 addAliases(ES, CXXAliases, requiredCXXAliases());
274 if (auto Err = JD.define(symbolAliases(std::move(CXXAliases))))
275 return Err;
276
277 auto PerJDObj = getPerJDObjectFile();
278 if (!PerJDObj)
279 return PerJDObj.takeError();
280
281 auto I = getObjectFileInterface(ES, *PerJDObj);
282 if (!I)
283 return I.takeError();
284
285 if (auto Err = ObjLinkingLayer.add(
286 JD, MemoryBuffer::getMemBuffer(*PerJDObj, false), std::move(*I)))
287 return Err;
288
289 if (!Bootstrapping) {
290 auto ImportedLibs = StaticVCRuntime
291 ? VCRuntimeBootstrap->loadStaticVCRuntime(JD)
292 : VCRuntimeBootstrap->loadDynamicVCRuntime(JD);
293 if (!ImportedLibs)
294 return ImportedLibs.takeError();
295 for (auto &Lib : *ImportedLibs)
296 if (auto Err = LoadDynLibrary(JD, Lib))
297 return Err;
298 if (StaticVCRuntime)
299 if (auto Err = VCRuntimeBootstrap->initializeStaticVCRuntime(JD))
300 return Err;
301 }
302
303 JD.addGenerator(DLLImportDefinitionGenerator::Create(ES, ObjLinkingLayer));
304 return Error::success();
305}
306
308 std::lock_guard<std::mutex> Lock(PlatformMutex);
309 auto I = JITDylibToHeaderAddr.find(&JD);
310 if (I != JITDylibToHeaderAddr.end()) {
311 assert(HeaderAddrToJITDylib.count(I->second) &&
312 "HeaderAddrToJITDylib missing entry");
313 HeaderAddrToJITDylib.erase(I->second);
314 JITDylibToHeaderAddr.erase(I);
315 }
316 return Error::success();
317}
318
320 const MaterializationUnit &MU) {
321 auto &JD = RT.getJITDylib();
322 const auto &InitSym = MU.getInitializerSymbol();
323 if (!InitSym)
324 return Error::success();
325
326 RegisteredInitSymbols[&JD].add(InitSym,
328
329 LLVM_DEBUG({
330 dbgs() << "COFFPlatform: Registered init symbol " << *InitSym << " for MU "
331 << MU.getName() << "\n";
332 });
333 return Error::success();
334}
335
339
345
348 static const std::pair<const char *, const char *> RequiredCXXAliases[] = {
349 {"_CxxThrowException", "__orc_rt_coff_cxx_throw_exception"},
350 {"_onexit", "__orc_rt_coff_onexit_per_jd"},
351 {"atexit", "__orc_rt_coff_atexit_per_jd"}};
352
353 return ArrayRef<std::pair<const char *, const char *>>(RequiredCXXAliases);
354}
355
358 static const std::pair<const char *, const char *>
359 StandardRuntimeUtilityAliases[] = {
360 {"__orc_rt_run_program", "__orc_rt_coff_run_program"},
361 {"__orc_rt_jit_dlerror", "__orc_rt_coff_jit_dlerror"},
362 {"__orc_rt_jit_dlopen", "__orc_rt_coff_jit_dlopen"},
363 {"__orc_rt_jit_dlupdate", "__orc_rt_coff_jit_dlupdate"},
364 {"__orc_rt_jit_dlclose", "__orc_rt_coff_jit_dlclose"},
365 {"__orc_rt_jit_dlsym", "__orc_rt_coff_jit_dlsym"},
366 {"__orc_rt_log_error", "__orc_rt_log_error_to_stderr"}};
367
369 StandardRuntimeUtilityAliases);
370}
371
372bool COFFPlatform::supportedTarget(const Triple &TT) {
373 switch (TT.getArch()) {
374 case Triple::x86_64:
375 return true;
376 default:
377 return false;
378 }
379}
380
381COFFPlatform::COFFPlatform(
382 ObjectLinkingLayer &ObjLinkingLayer, JITDylib &PlatformJD,
383 std::unique_ptr<StaticLibraryDefinitionGenerator> OrcRuntimeGenerator,
384 std::set<std::string> DylibsToPreload,
385 std::unique_ptr<MemoryBuffer> OrcRuntimeArchiveBuffer,
386 std::unique_ptr<object::Archive> OrcRuntimeArchive,
387 LoadDynamicLibrary LoadDynLibrary, bool StaticVCRuntime,
388 const char *VCRuntimePath, Error &Err)
389 : ES(ObjLinkingLayer.getExecutionSession()),
390 ObjLinkingLayer(ObjLinkingLayer),
391 LoadDynLibrary(std::move(LoadDynLibrary)),
392 OrcRuntimeArchiveBuffer(std::move(OrcRuntimeArchiveBuffer)),
393 OrcRuntimeArchive(std::move(OrcRuntimeArchive)),
394 StaticVCRuntime(StaticVCRuntime),
395 COFFHeaderStartSymbol(ES.intern("__ImageBase")) {
397
398 Bootstrapping.store(true);
399 ObjLinkingLayer.addPlugin(std::make_unique<COFFPlatformPlugin>(*this));
400
401 // Load vc runtime
402 auto VCRT =
403 COFFVCRuntimeBootstrapper::Create(ES, ObjLinkingLayer, VCRuntimePath);
404 if (!VCRT) {
405 Err = VCRT.takeError();
406 return;
407 }
408 VCRuntimeBootstrap = std::move(*VCRT);
409
410 auto ImportedLibs =
411 StaticVCRuntime ? VCRuntimeBootstrap->loadStaticVCRuntime(PlatformJD)
412 : VCRuntimeBootstrap->loadDynamicVCRuntime(PlatformJD);
413 if (!ImportedLibs) {
414 Err = ImportedLibs.takeError();
415 return;
416 }
417
418 for (auto &Lib : *ImportedLibs)
419 DylibsToPreload.insert(Lib);
420
421 PlatformJD.addGenerator(std::move(OrcRuntimeGenerator));
422
423 // PlatformJD hasn't been set up by the platform yet (since we're creating
424 // the platform now), so set it up.
425 if (auto E2 = setupJITDylib(PlatformJD)) {
426 Err = std::move(E2);
427 return;
428 }
429
430 for (auto& Lib : DylibsToPreload)
431 if (auto E2 = this->LoadDynLibrary(PlatformJD, Lib)) {
432 Err = std::move(E2);
433 return;
434 }
435
436 if (StaticVCRuntime)
437 if (auto E2 = VCRuntimeBootstrap->initializeStaticVCRuntime(PlatformJD)) {
438 Err = std::move(E2);
439 return;
440 }
441
442 // Associate wrapper function tags with JIT-side function implementations.
443 if (auto E2 = associateRuntimeSupportFunctions(PlatformJD)) {
444 Err = std::move(E2);
445 return;
446 }
447
448 // Lookup addresses of runtime functions callable by the platform,
449 // call the platform bootstrap function to initialize the platform-state
450 // object in the executor.
451 if (auto E2 = bootstrapCOFFRuntime(PlatformJD)) {
452 Err = std::move(E2);
453 return;
454 }
455
456 Bootstrapping.store(false);
457 JDBootstrapStates.clear();
458}
459
460Expected<COFFPlatform::JITDylibDepMap>
461COFFPlatform::buildJDDepMap(JITDylib &JD) {
462 return ES.runSessionLocked([&]() -> Expected<JITDylibDepMap> {
463 JITDylibDepMap JDDepMap;
464
465 SmallVector<JITDylib *, 16> Worklist({&JD});
466 while (!Worklist.empty()) {
467 auto CurJD = Worklist.back();
468 Worklist.pop_back();
469
470 auto &DM = JDDepMap[CurJD];
471 CurJD->withLinkOrderDo([&](const JITDylibSearchOrder &O) {
472 DM.reserve(O.size());
473 for (auto &KV : O) {
474 if (KV.first == CurJD)
475 continue;
476 {
477 // Bare jitdylibs not known to the platform
478 std::lock_guard<std::mutex> Lock(PlatformMutex);
479 if (!JITDylibToHeaderAddr.count(KV.first)) {
480 LLVM_DEBUG({
481 dbgs() << "JITDylib unregistered to COFFPlatform detected in "
482 "LinkOrder: "
483 << CurJD->getName() << "\n";
484 });
485 continue;
486 }
487 }
488 DM.push_back(KV.first);
489 // Push unvisited entry.
490 if (JDDepMap.try_emplace(KV.first).second)
491 Worklist.push_back(KV.first);
492 }
493 });
494 }
495 return std::move(JDDepMap);
496 });
497}
498
499void COFFPlatform::pushInitializersLoop(PushInitializersSendResultFn SendResult,
500 JITDylibSP JD,
501 JITDylibDepMap &JDDepMap) {
502 SmallVector<JITDylib *, 16> Worklist({JD.get()});
503 DenseSet<JITDylib *> Visited({JD.get()});
504 DenseMap<JITDylib *, SymbolLookupSet> NewInitSymbols;
505 ES.runSessionLocked([&]() {
506 while (!Worklist.empty()) {
507 auto CurJD = Worklist.back();
508 Worklist.pop_back();
509
510 auto RISItr = RegisteredInitSymbols.find(CurJD);
511 if (RISItr != RegisteredInitSymbols.end()) {
512 NewInitSymbols[CurJD] = std::move(RISItr->second);
513 RegisteredInitSymbols.erase(RISItr);
514 }
515
516 for (auto *DepJD : JDDepMap[CurJD])
517 if (Visited.insert(DepJD).second)
518 Worklist.push_back(DepJD);
519 }
520 });
521
522 // If there are no further init symbols to look up then send the link order
523 // (as a list of header addresses) to the caller.
524 if (NewInitSymbols.empty()) {
525 // Build the dep info map to return.
526 COFFJITDylibDepInfoMap DIM;
527 DIM.reserve(JDDepMap.size());
528 for (auto &KV : JDDepMap) {
529 std::lock_guard<std::mutex> Lock(PlatformMutex);
530 COFFJITDylibDepInfo DepInfo;
531 DepInfo.reserve(KV.second.size());
532 for (auto &Dep : KV.second) {
533 DepInfo.push_back(JITDylibToHeaderAddr[Dep]);
534 }
535 auto H = JITDylibToHeaderAddr[KV.first];
536 DIM.push_back(std::make_pair(H, std::move(DepInfo)));
537 }
538 SendResult(DIM);
539 return;
540 }
541
542 // Otherwise issue a lookup and re-run this phase when it completes.
544 [this, SendResult = std::move(SendResult), &JD,
545 JDDepMap = std::move(JDDepMap)](Error Err) mutable {
546 if (Err)
547 SendResult(std::move(Err));
548 else
549 pushInitializersLoop(std::move(SendResult), JD, JDDepMap);
550 },
551 ES, std::move(NewInitSymbols));
552}
553
554void COFFPlatform::rt_pushInitializers(PushInitializersSendResultFn SendResult,
555 ExecutorAddr JDHeaderAddr) {
556 JITDylibSP JD;
557 {
558 std::lock_guard<std::mutex> Lock(PlatformMutex);
559 auto I = HeaderAddrToJITDylib.find(JDHeaderAddr);
560 if (I != HeaderAddrToJITDylib.end())
561 JD = I->second;
562 }
563
564 LLVM_DEBUG({
565 dbgs() << "COFFPlatform::rt_pushInitializers(" << JDHeaderAddr << ") ";
566 if (JD)
567 dbgs() << "pushing initializers for " << JD->getName() << "\n";
568 else
569 dbgs() << "No JITDylib for header address.\n";
570 });
571
572 if (!JD) {
573 SendResult(make_error<StringError>("No JITDylib with header addr " +
574 formatv("{0:x}", JDHeaderAddr),
576 return;
577 }
578
579 auto JDDepMap = buildJDDepMap(*JD);
580 if (!JDDepMap) {
581 SendResult(JDDepMap.takeError());
582 return;
583 }
584
585 pushInitializersLoop(std::move(SendResult), JD, *JDDepMap);
586}
587
588void COFFPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult,
589 ExecutorAddr Handle, StringRef SymbolName) {
590 LLVM_DEBUG(dbgs() << "COFFPlatform::rt_lookupSymbol(\"" << Handle << "\")\n");
591
592 JITDylib *JD = nullptr;
593
594 {
595 std::lock_guard<std::mutex> Lock(PlatformMutex);
596 auto I = HeaderAddrToJITDylib.find(Handle);
597 if (I != HeaderAddrToJITDylib.end())
598 JD = I->second;
599 }
600
601 if (!JD) {
602 LLVM_DEBUG(dbgs() << " No JITDylib for handle " << Handle << "\n");
603 SendResult(make_error<StringError>("No JITDylib associated with handle " +
604 formatv("{0:x}", Handle),
606 return;
607 }
608
609 // Use functor class to work around XL build compiler issue on AIX.
610 class RtLookupNotifyComplete {
611 public:
612 RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult)
613 : SendResult(std::move(SendResult)) {}
614 void operator()(Expected<SymbolMap> Result) {
615 if (Result) {
616 assert(Result->size() == 1 && "Unexpected result map count");
617 SendResult(Result->begin()->second.getAddress());
618 } else {
619 SendResult(Result.takeError());
620 }
621 }
622
623 private:
624 SendSymbolAddressFn SendResult;
625 };
626
627 ES.lookup(
629 SymbolLookupSet(ES.intern(SymbolName)), SymbolState::Ready,
630 RtLookupNotifyComplete(std::move(SendResult)), NoDependenciesToRegister);
631}
632
633Error COFFPlatform::associateRuntimeSupportFunctions(JITDylib &PlatformJD) {
635
636 using LookupSymbolSPSSig =
637 SPSExpected<SPSExecutorAddr>(SPSExecutorAddr, SPSString);
638 WFs[ES.intern("__orc_rt_coff_symbol_lookup_tag")] =
639 ES.wrapAsyncWithSPS<LookupSymbolSPSSig>(this,
640 &COFFPlatform::rt_lookupSymbol);
641 using PushInitializersSPSSig =
642 SPSExpected<SPSCOFFJITDylibDepInfoMap>(SPSExecutorAddr);
643 WFs[ES.intern("__orc_rt_coff_push_initializers_tag")] =
644 ES.wrapAsyncWithSPS<PushInitializersSPSSig>(
645 this, &COFFPlatform::rt_pushInitializers);
646
647 return ES.registerJITDispatchHandlers(PlatformJD, std::move(WFs));
648}
649
650Error COFFPlatform::runBootstrapInitializers(JDBootstrapState &BState) {
651 llvm::sort(BState.Initializers);
652 if (auto Err =
653 runBootstrapSubsectionInitializers(BState, ".CRT$XIA", ".CRT$XIZ"))
654 return Err;
655
656 if (auto Err = runSymbolIfExists(*BState.JD, "__run_after_c_init"))
657 return Err;
658
659 if (auto Err =
660 runBootstrapSubsectionInitializers(BState, ".CRT$XCA", ".CRT$XCZ"))
661 return Err;
662 return Error::success();
663}
664
665Error COFFPlatform::runBootstrapSubsectionInitializers(JDBootstrapState &BState,
666 StringRef Start,
667 StringRef End) {
668 CallInt32VoidProxy CallInitializer;
669 if (auto Err = lookupAndApply(
670 ES.getBootstrapJITDylib(),
671 {recordProxy<sps::CallInt32VoidProxySpec>(&CallInitializer)}))
672 return Err;
673 for (auto &Initializer : BState.Initializers)
674 if (Initializer.first >= Start && Initializer.first <= End &&
675 Initializer.second) {
676 auto Res = CallInitializer(ES, Initializer.second);
677 if (!Res)
678 return Res.takeError();
679 }
680 return Error::success();
681}
682
683Error COFFPlatform::bootstrapCOFFRuntime(JITDylib &PlatformJD) {
684 // Lookup of runtime symbols causes the collection of initializers if
685 // it's static linking setting.
686 if (auto Err = lookupAndApply(
687 PlatformJD, {recordAddr("__orc_rt_coff_platform_bootstrap",
688 &orc_rt_coff_platform_bootstrap),
689 recordAddr("__orc_rt_coff_platform_shutdown",
690 &orc_rt_coff_platform_shutdown),
691 recordAddr("__orc_rt_coff_register_jitdylib",
692 &orc_rt_coff_register_jitdylib),
693 recordAddr("__orc_rt_coff_deregister_jitdylib",
694 &orc_rt_coff_deregister_jitdylib),
695 recordAddr("__orc_rt_coff_register_object_sections",
696 &orc_rt_coff_register_object_sections),
697 recordAddr("__orc_rt_coff_deregister_object_sections",
698 &orc_rt_coff_deregister_object_sections)}))
699 return Err;
700
701 // Call bootstrap functions
702 if (auto Err = ES.callSPSWrapper<void()>(orc_rt_coff_platform_bootstrap))
703 return Err;
704
705 // Do the pending jitdylib registration actions that we couldn't do
706 // because orc runtime was not linked fully.
707 for (auto KV : JDBootstrapStates) {
708 auto &JDBState = KV.second;
709 if (auto Err = ES.callSPSWrapper<void(SPSString, SPSExecutorAddr)>(
710 orc_rt_coff_register_jitdylib, JDBState.JDName,
711 JDBState.HeaderAddr))
712 return Err;
713
714 for (auto &ObjSectionMap : JDBState.ObjectSectionsMaps)
715 if (auto Err = ES.callSPSWrapper<void(SPSExecutorAddr,
717 orc_rt_coff_register_object_sections, JDBState.HeaderAddr,
718 ObjSectionMap, false))
719 return Err;
720 }
721
722 // Run static initializers collected in bootstrap stage.
723 for (auto KV : JDBootstrapStates) {
724 auto &JDBState = KV.second;
725 if (auto Err = runBootstrapInitializers(JDBState))
726 return Err;
727 }
728
729 return Error::success();
730}
731
732Error COFFPlatform::runSymbolIfExists(JITDylib &PlatformJD,
733 StringRef SymbolName) {
734 ExecutorAddr jit_function;
735 auto AfterCLookupErr = lookupAndRecordAddrs(
737 {{ES.intern(SymbolName), &jit_function}});
738 if (!AfterCLookupErr) {
739 CallInt32VoidProxy CallFn;
740 if (auto Err =
741 lookupAndApply(ES.getBootstrapJITDylib(),
742 {recordProxy<sps::CallInt32VoidProxySpec>(&CallFn)}))
743 return Err;
744 auto Res = CallFn(ES, jit_function);
745 if (!Res)
746 return Res.takeError();
747 return Error::success();
748 }
749 if (!AfterCLookupErr.isA<SymbolsNotFound>())
750 return AfterCLookupErr;
751 consumeError(std::move(AfterCLookupErr));
752 return Error::success();
753}
754
755void COFFPlatform::COFFPlatformPlugin::modifyPassConfig(
756 MaterializationResponsibility &MR, jitlink::LinkGraph &LG,
757 jitlink::PassConfiguration &Config) {
758
759 bool IsBootstrapping = CP.Bootstrapping.load();
760
761 if (auto InitSymbol = MR.getInitializerSymbol()) {
762 if (InitSymbol == CP.COFFHeaderStartSymbol) {
763 Config.PostAllocationPasses.push_back(
764 [this, &MR, IsBootstrapping](jitlink::LinkGraph &G) {
765 return associateJITDylibHeaderSymbol(G, MR, IsBootstrapping);
766 });
767 return;
768 }
769 Config.PrePrunePasses.push_back([this, &MR](jitlink::LinkGraph &G) {
770 return preserveInitializerSections(G, MR);
771 });
772 }
773
774 if (!IsBootstrapping)
775 Config.PostFixupPasses.push_back(
776 [this, &JD = MR.getTargetJITDylib()](jitlink::LinkGraph &G) {
777 return registerObjectPlatformSections(G, JD);
778 });
779 else
780 Config.PostFixupPasses.push_back(
781 [this, &JD = MR.getTargetJITDylib()](jitlink::LinkGraph &G) {
782 return registerObjectPlatformSectionsInBootstrap(G, JD);
783 });
784}
785
786Error COFFPlatform::COFFPlatformPlugin::associateJITDylibHeaderSymbol(
787 jitlink::LinkGraph &G, MaterializationResponsibility &MR,
788 bool IsBootstraping) {
789 auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) {
790 return *Sym->getName() == *CP.COFFHeaderStartSymbol;
791 });
792 assert(I != G.defined_symbols().end() && "Missing COFF header start symbol");
793
794 auto &JD = MR.getTargetJITDylib();
795 std::lock_guard<std::mutex> Lock(CP.PlatformMutex);
796 auto HeaderAddr = (*I)->getAddress();
797 CP.JITDylibToHeaderAddr[&JD] = HeaderAddr;
798 CP.HeaderAddrToJITDylib[HeaderAddr] = &JD;
799 if (!IsBootstraping) {
800 G.allocActions().push_back(
802 SPSArgList<SPSString, SPSExecutorAddr>>(
803 CP.orc_rt_coff_register_jitdylib, JD.getName(), HeaderAddr)),
804 cantFail(WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>(
805 CP.orc_rt_coff_deregister_jitdylib, HeaderAddr))});
806 } else {
807 G.allocActions().push_back(
808 {{},
809 cantFail(WrapperFunctionCall::Create<SPSArgList<SPSExecutorAddr>>(
810 CP.orc_rt_coff_deregister_jitdylib, HeaderAddr))});
811 JDBootstrapState BState;
812 BState.JD = &JD;
813 BState.JDName = JD.getName();
814 BState.HeaderAddr = HeaderAddr;
815 CP.JDBootstrapStates.emplace(&JD, BState);
816 }
817
818 return Error::success();
819}
820
821Error COFFPlatform::COFFPlatformPlugin::registerObjectPlatformSections(
822 jitlink::LinkGraph &G, JITDylib &JD) {
823 COFFObjectSectionsMap ObjSecs;
824 auto HeaderAddr = CP.JITDylibToHeaderAddr[&JD];
825 assert(HeaderAddr && "Must be registered jitdylib");
826 for (auto &S : G.sections()) {
827 jitlink::SectionRange Range(S);
828 if (Range.getSize())
829 ObjSecs.push_back(std::make_pair(S.getName().str(), Range.getRange()));
830 }
831
832 G.allocActions().push_back(
834 CP.orc_rt_coff_register_object_sections, HeaderAddr, ObjSecs, true)),
835 cantFail(
837 CP.orc_rt_coff_deregister_object_sections, HeaderAddr,
838 ObjSecs))});
839
840 return Error::success();
841}
842
843Error COFFPlatform::COFFPlatformPlugin::preserveInitializerSections(
844 jitlink::LinkGraph &G, MaterializationResponsibility &MR) {
845
846 if (const auto &InitSymName = MR.getInitializerSymbol()) {
847
848 jitlink::Symbol *InitSym = nullptr;
849
850 for (auto &InitSection : G.sections()) {
851 // Skip non-init sections.
852 if (!isCOFFInitializerSection(InitSection.getName()) ||
853 InitSection.empty())
854 continue;
855
856 // Create the init symbol if it has not been created already and attach it
857 // to the first block.
858 if (!InitSym) {
859 auto &B = **InitSection.blocks().begin();
860 InitSym = &G.addDefinedSymbol(
861 B, 0, *InitSymName, B.getSize(), jitlink::Linkage::Strong,
863 }
864
865 // Add keep-alive edges to anonymous symbols in all other init blocks.
866 for (auto *B : InitSection.blocks()) {
867 if (B == &InitSym->getBlock())
868 continue;
869
870 auto &S = G.addAnonymousSymbol(*B, 0, B->getSize(), false, true);
871 InitSym->getBlock().addEdge(jitlink::Edge::KeepAlive, 0, S, 0);
872 }
873 }
874 }
875
876 return Error::success();
877}
878
879Error COFFPlatform::COFFPlatformPlugin::
880 registerObjectPlatformSectionsInBootstrap(jitlink::LinkGraph &G,
881 JITDylib &JD) {
882 std::lock_guard<std::mutex> Lock(CP.PlatformMutex);
883 auto HeaderAddr = CP.JITDylibToHeaderAddr[&JD];
884 COFFObjectSectionsMap ObjSecs;
885 for (auto &S : G.sections()) {
886 jitlink::SectionRange Range(S);
887 if (Range.getSize())
888 ObjSecs.push_back(std::make_pair(S.getName().str(), Range.getRange()));
889 }
890
891 G.allocActions().push_back(
892 {{},
893 cantFail(
895 CP.orc_rt_coff_deregister_object_sections, HeaderAddr,
896 ObjSecs))});
897
898 auto &BState = CP.JDBootstrapStates[&JD];
899 BState.ObjectSectionsMaps.push_back(std::move(ObjSecs));
900
901 // Collect static initializers
902 for (auto &S : G.sections())
903 if (isCOFFInitializerSection(S.getName()))
904 for (auto *B : S.blocks()) {
905 if (B->edges_empty())
906 continue;
907 for (auto &E : B->edges())
908 BState.Initializers.push_back(std::make_pair(
909 S.getName().str(), E.getTarget().getAddress() + E.getAddend()));
910 }
911
912 return Error::success();
913}
914
915} // End namespace orc.
916} // 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
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:153
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
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
LLVM_ABI 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)
LLVM_ABI Expected< MaterializationUnit::Interface > getObjectFileInterface(ExecutionSession &ES, MemoryBufferRef ObjBuffer)
Returns a MaterializationUnit::Interface for the object file contained in the given buffer,...
LLVM_ABI void lookupAndApply(unique_function< void(Error)> OnApplied, ExecutionSession &ES, 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...
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
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878