LLVM 20.0.0git
COFFVCRuntimeSupport.cpp
Go to the documentation of this file.
1//===------- COFFVCRuntimeSupport.cpp - VC runtime support 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
15
16#define DEBUG_TYPE "orc"
17
18using namespace llvm;
19using namespace llvm::orc;
20using namespace llvm::orc::shared;
21
24 ObjectLinkingLayer &ObjLinkingLayer,
25 const char *RuntimePath) {
26 return std::unique_ptr<COFFVCRuntimeBootstrapper>(
27 new COFFVCRuntimeBootstrapper(ES, ObjLinkingLayer, RuntimePath));
28}
29
30COFFVCRuntimeBootstrapper::COFFVCRuntimeBootstrapper(
31 ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer,
32 const char *RuntimePath)
33 : ES(ES), ObjLinkingLayer(ObjLinkingLayer) {
34 if (RuntimePath)
35 this->RuntimePath = RuntimePath;
36}
37
40 bool DebugVersion) {
41 StringRef VCLibs[] = {"libvcruntime.lib", "libcmt.lib", "libcpmt.lib"};
42 StringRef UCRTLibs[] = {"libucrt.lib"};
43 std::vector<std::string> ImportedLibraries;
44 if (auto Err = loadVCRuntime(JD, ImportedLibraries, ArrayRef(VCLibs),
45 ArrayRef(UCRTLibs)))
46 return std::move(Err);
47 return ImportedLibraries;
48}
49
52 bool DebugVersion) {
53 StringRef VCLibs[] = {"vcruntime.lib", "msvcrt.lib", "msvcprt.lib"};
54 StringRef UCRTLibs[] = {"ucrt.lib"};
55 std::vector<std::string> ImportedLibraries;
56 if (auto Err = loadVCRuntime(JD, ImportedLibraries, ArrayRef(VCLibs),
57 ArrayRef(UCRTLibs)))
58 return std::move(Err);
59 return ImportedLibraries;
60}
61
62Error COFFVCRuntimeBootstrapper::loadVCRuntime(
63 JITDylib &JD, std::vector<std::string> &ImportedLibraries,
65 MSVCToolchainPath Path;
66 if (!RuntimePath.empty()) {
67 Path.UCRTSdkLib = RuntimePath;
68 Path.VCToolchainLib = RuntimePath;
69 } else {
70 auto ToolchainPath = getMSVCToolchainPath();
71 if (!ToolchainPath)
72 return ToolchainPath.takeError();
73 Path = *ToolchainPath;
74 }
76 dbgs() << "Using VC toolchain pathes\n";
77 dbgs() << " VC toolchain path: " << Path.VCToolchainLib << "\n";
78 dbgs() << " UCRT path: " << Path.UCRTSdkLib << "\n";
79 });
80
81 auto LoadLibrary = [&](SmallString<256> LibPath, StringRef LibName) -> Error {
82 sys::path::append(LibPath, LibName);
83
84 auto G = StaticLibraryDefinitionGenerator::Load(ObjLinkingLayer,
85 LibPath.c_str());
86 if (!G)
87 return G.takeError();
88
89 for (auto &Lib : (*G)->getImportedDynamicLibraries())
90 ImportedLibraries.push_back(Lib);
91
92 JD.addGenerator(std::move(*G));
93
94 return Error::success();
95 };
96 for (auto &Lib : UCRTLibs)
97 if (auto Err = LoadLibrary(Path.UCRTSdkLib, Lib))
98 return Err;
99
100 for (auto &Lib : VCLibs)
101 if (auto Err = LoadLibrary(Path.VCToolchainLib, Lib))
102 return Err;
103 ImportedLibraries.push_back("ntdll.dll");
104 ImportedLibraries.push_back("Kernel32.dll");
105
106 return Error::success();
107}
108
110 ExecutorAddr jit_scrt_initialize, jit_scrt_dllmain_before_initialize_c,
111 jit_scrt_initialize_type_info,
112 jit_scrt_initialize_default_local_stdio_options;
113 if (auto Err = lookupAndRecordAddrs(
115 {{ES.intern("__scrt_initialize_crt"), &jit_scrt_initialize},
116 {ES.intern("__scrt_dllmain_before_initialize_c"),
117 &jit_scrt_dllmain_before_initialize_c},
118 {ES.intern("?__scrt_initialize_type_info@@YAXXZ"),
119 &jit_scrt_initialize_type_info},
120 {ES.intern("__scrt_initialize_default_local_stdio_options"),
121 &jit_scrt_initialize_default_local_stdio_options}}))
122 return Err;
123
124 auto RunVoidInitFunc = [&](ExecutorAddr Addr) -> Error {
126 return Error::success();
127 else
128 return Res.takeError();
129 };
130
131 auto R =
132 ES.getExecutorProcessControl().runAsIntFunction(jit_scrt_initialize, 0);
133 if (!R)
134 return R.takeError();
135
136 if (auto Err = RunVoidInitFunc(jit_scrt_dllmain_before_initialize_c))
137 return Err;
138
139 if (auto Err = RunVoidInitFunc(jit_scrt_initialize_type_info))
140 return Err;
141
142 if (auto Err =
143 RunVoidInitFunc(jit_scrt_initialize_default_local_stdio_options))
144 return Err;
145
146 SymbolAliasMap Alias;
147 Alias[ES.intern("__run_after_c_init")] = {
148 ES.intern("__scrt_dllmain_after_initialize_c"), JITSymbolFlags::Exported};
149 if (auto Err = JD.define(symbolAliases(Alias)))
150 return Err;
151
152 return Error::success();
153}
154
156COFFVCRuntimeBootstrapper::getMSVCToolchainPath() {
157 std::string VCToolChainPath;
158 ToolsetLayout VSLayout;
160 if (!findVCToolChainViaCommandLine(*VFS, std::nullopt, std::nullopt,
161 std::nullopt, VCToolChainPath, VSLayout) &&
162 !findVCToolChainViaEnvironment(*VFS, VCToolChainPath, VSLayout) &&
163 !findVCToolChainViaSetupConfig(*VFS, {}, VCToolChainPath, VSLayout) &&
164 !findVCToolChainViaRegistry(VCToolChainPath, VSLayout))
165 return make_error<StringError>("Couldn't find msvc toolchain.",
167
168 std::string UniversalCRTSdkPath;
169 std::string UCRTVersion;
170 if (!getUniversalCRTSdkDir(*VFS, std::nullopt, std::nullopt, std::nullopt,
171 UniversalCRTSdkPath, UCRTVersion))
172 return make_error<StringError>("Couldn't find universal sdk.",
174
175 MSVCToolchainPath ToolchainPath;
176 SmallString<256> VCToolchainLib(VCToolChainPath);
177 sys::path::append(VCToolchainLib, "lib", "x64");
178 ToolchainPath.VCToolchainLib = VCToolchainLib;
179
180 SmallString<256> UCRTSdkLib(UniversalCRTSdkPath);
181 sys::path::append(UCRTSdkLib, "Lib", UCRTVersion, "ucrt", "x64");
182 ToolchainPath.UCRTSdkLib = UCRTSdkLib;
183 return ToolchainPath;
184}
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
#define G(x, y, z)
Definition: MD5.cpp:56
Defines the virtual file system interface vfs::FileSystem.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
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
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
const char * c_str()
Definition: SmallString.h:259
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Bootstraps the vc runtime within jitdylibs.
static Expected< std::unique_ptr< COFFVCRuntimeBootstrapper > > Create(ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer, const char *RuntimePath=nullptr)
Try to create a COFFVCRuntimeBootstrapper instance.
Expected< std::vector< std::string > > loadStaticVCRuntime(JITDylib &JD, bool DebugVersion=false)
Adds symbol definitions of static version of msvc runtime libraries.
Expected< std::vector< std::string > > loadDynamicVCRuntime(JITDylib &JD, bool DebugVersion=false)
Adds symbol definitions of dynamic version of msvc runtime libraries.
Error initializeStaticVCRuntime(JITDylib &JD)
Runs the initializer of static version of msvc runtime libraries.
An ExecutionSession represents a running JIT program.
Definition: Core.h:1431
ExecutorProcessControl & getExecutorProcessControl()
Get the ExecutorProcessControl object associated with this ExecutionSession.
Definition: Core.h:1471
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1485
Represents an address in the executor process.
virtual Expected< int32_t > runAsIntFunction(ExecutorAddr IntFnAddr, int Arg)=0
Run function with a int (*)(int) signature.
virtual Expected< int32_t > runAsVoidFunction(ExecutorAddr VoidFnAddr)=0
Run function with a int (*)(void) signature.
Represents a JIT'd dynamic library.
Definition: Core.h:989
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:1910
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition: Core.h:1893
An ObjectLayer implementation built on JITLink.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName, GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibraryDefinitionGenerator from the given path.
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:166
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition: Core.h:837
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.
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:457
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool findVCToolChainViaCommandLine(vfs::FileSystem &VFS, std::optional< llvm::StringRef > VCToolsDir, std::optional< llvm::StringRef > VCToolsVersion, std::optional< llvm::StringRef > WinSysRoot, std::string &Path, ToolsetLayout &VSLayout)
Definition: MSVCPaths.cpp:481
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
bool findVCToolChainViaEnvironment(vfs::FileSystem &VFS, std::string &Path, ToolsetLayout &VSLayout)
Definition: MSVCPaths.cpp:508
bool findVCToolChainViaSetupConfig(vfs::FileSystem &VFS, std::optional< llvm::StringRef > VCToolsVersion, std::string &Path, ToolsetLayout &VSLayout)
Definition: MSVCPaths.cpp:617
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
ToolsetLayout
Definition: MSVCPaths.h:30
bool findVCToolChainViaRegistry(std::string &Path, ToolsetLayout &VSLayout)
Definition: MSVCPaths.cpp:714
bool getUniversalCRTSdkDir(vfs::FileSystem &VFS, std::optional< llvm::StringRef > WinSdkDir, std::optional< llvm::StringRef > WinSdkVersion, std::optional< llvm::StringRef > WinSysRoot, std::string &Path, std::string &UCRTVersion)
Definition: MSVCPaths.cpp:456