From 9361ae80f23b69b71f75d062cb7c1c071bc4f552 Mon Sep 17 00:00:00 2001 From: Lifeng Lu Date: Sun, 27 Aug 2023 10:15:42 -0700 Subject: [PATCH] Further hardern the logic inside HostFxrResolver Adds more logging and handles empty folder. --- src/MSBuildLocator/DotNetSdkLocationHelper.cs | 29 +++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/MSBuildLocator/DotNetSdkLocationHelper.cs b/src/MSBuildLocator/DotNetSdkLocationHelper.cs index 89e78001..06b439cf 100644 --- a/src/MSBuildLocator/DotNetSdkLocationHelper.cs +++ b/src/MSBuildLocator/DotNetSdkLocationHelper.cs @@ -133,8 +133,8 @@ 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)) @@ -142,7 +142,7 @@ private static IntPtr HostFxrResolver(Assembly assembly, string libraryName) 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( @@ -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