Skip to content

Commit df83f3f

Browse files
committed
Load hostfxr library from dotnet root so it can be found from NativeAOT
1 parent bc8ec58 commit df83f3f

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

src/Resolvers/Microsoft.DotNet.NativeWrapper/NETBundlesNativeWrapper.cs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,55 @@ namespace Microsoft.DotNet.NativeWrapper
55
{
66
public class NETBundlesNativeWrapper : INETBundleProvider
77
{
8+
// lpFileName passed to LoadLibraryEx must be a full path.
9+
private const int LOAD_WITH_ALTERED_SEARCH_PATH = 0x8;
10+
11+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
12+
private static extern IntPtr LoadLibraryExW(string lpFileName, IntPtr hFile, int dwFlags);
13+
814
public NetEnvironmentInfo GetDotnetEnvironmentInfo(string dotnetExeDirectory)
915
{
16+
PreloadHostFxrLibrary(dotnetExeDirectory);
17+
1018
var info = new NetEnvironmentInfo();
1119
IntPtr reserved = IntPtr.Zero;
1220
IntPtr resultContext = IntPtr.Zero;
1321

14-
int errorCode = Interop.hostfxr_get_dotnet_environment_info(dotnetExeDirectory, reserved, info.Initialize, resultContext);
22+
// If directory doesn't exist, we may not be able to load hostfxr, so treat as if there are no installed frameworks/SDKs.
23+
if (Directory.Exists(dotnetExeDirectory))
24+
{
25+
int errorCode = Interop.hostfxr_get_dotnet_environment_info(dotnetExeDirectory, reserved, info.Initialize, resultContext);
26+
}
1527

1628
return info;
1729
}
30+
31+
private void PreloadHostFxrLibrary(string dotnetExeDirectory)
32+
{
33+
string? hostFxrPath = FindHostFxrLibrary(dotnetExeDirectory);
34+
if (hostFxrPath != null)
35+
{
36+
LoadLibraryExW(hostFxrPath, IntPtr.Zero, LOAD_WITH_ALTERED_SEARCH_PATH);
37+
}
38+
}
39+
40+
private static string? FindHostFxrLibrary(string installRoot)
41+
{
42+
string hostFxrDirectory = Path.Combine(installRoot, "host", "fxr");
43+
if (!Directory.Exists(hostFxrDirectory))
44+
{
45+
return null;
46+
}
47+
48+
string libraryName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
49+
? "hostfxr.dll"
50+
: RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
51+
? "libhostfxr.dylib"
52+
: "libhostfxr.so";
53+
54+
return Directory.EnumerateFiles(hostFxrDirectory, libraryName, SearchOption.AllDirectories)
55+
.OrderByDescending(File.GetLastWriteTimeUtc)
56+
.FirstOrDefault();
57+
}
1858
}
1959
}

0 commit comments

Comments
 (0)