Skip to content

Commit

Permalink
Further hardern the logic inside HostFxrResolver
Browse files Browse the repository at this point in the history
Adds more logging and handles empty folder.
  • Loading branch information
Lifeng Lu committed Aug 27, 2023
1 parent a2f280e commit 9361ae8
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions src/MSBuildLocator/DotNetSdkLocationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,16 +133,16 @@ private static IntPtr HostFxrResolver(Assembly assembly, string libraryName)
{
Console.Error.WriteLine($"Try to load native library {libraryName}");

var hostFxrLibName = "libhostfxr";
var libExtension = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "dylib" : "so";
string hostFxrLibName = "libhostfxr";
string libExtension = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "dylib" : "so";

// the DllImport hardcoded the name as hostfxr.
if (!hostFxrLibName.Equals(libraryName, StringComparison.OrdinalIgnoreCase) && !libraryName.Equals("hostfxr", StringComparison.OrdinalIgnoreCase))
{
return IntPtr.Zero;
}

var hostFxrRoot = Path.Combine(DotnetPath.Value, "host", "fxr");
string hostFxrRoot = Path.Combine(DotnetPath.Value, "host", "fxr");
if (Directory.Exists(hostFxrRoot))
{
var fileEnumerable = new FileSystemEnumerable<SemanticVersion?>(
Expand All @@ -153,16 +153,35 @@ private static IntPtr HostFxrResolver(Assembly assembly, string libraryName)
};

// Load hostfxr from the highest version, because it should be backward-compatible
SemanticVersion? hostFxrVersion = fileEnumerable.Max();
SemanticVersion? hostFxrVersion;

try
{
hostFxrVersion = fileEnumerable.Max();
}
catch (ArgumentException)
{
// LINQ Max throws when the list is empty.
Console.Error.WriteLine($"No child folder was found in '{hostFxrRoot}'.");
return IntPtr.Zero;
}

if (hostFxrVersion is not null)
{
var hostFxrAssembly = Path.Combine(hostFxrRoot, hostFxrVersion.OriginalValue, Path.ChangeExtension(hostFxrLibName, libExtension));
string hostFxrAssembly = Path.Combine(hostFxrRoot, hostFxrVersion.OriginalValue, Path.ChangeExtension(hostFxrLibName, libExtension));

if (File.Exists(hostFxrAssembly))
{
return NativeLibrary.TryLoad(hostFxrAssembly, out var handle) ? handle : IntPtr.Zero;
}
else
{
Console.Error.WriteLine($"hostfxr file '{hostFxrAssembly}' cannot be found.");
}
}
else
{
Console.Error.WriteLine($"No runtime version was found in '{hostFxrRoot}'.");
}
}
else
Expand Down

0 comments on commit 9361ae8

Please sign in to comment.