From 7cf7bf6c8558adaeb247d6729030a0a591e9c13d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 23:36:02 +0100 Subject: [PATCH] Improved some comments --- .../Translation/ShaderCompiler.cs | 46 ++++++----- .../NativeLibrariesResolverTests.cs | 76 +++++++++++++++---- 2 files changed, 85 insertions(+), 37 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 75e77b7d..78c5b1ea 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -7,7 +7,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; -using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; @@ -62,32 +61,35 @@ namespace ComputeSharp.Shaders.Translation /// private static void InitializeDxcLibrariesLoading() { - // We are probing for a "dotnet run" scenario - string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @$"runtimes\win-x64\native"); - bool probeNuGetDirectory = Directory.Exists(nugetNativeLibsPath); + // Test whether the native libraries are present in the same folder of the executable + // (which is the case when the program was built with a runtime identifier), or whether + // they are in the "runtimes\win-x64\native" folder in the executable directory. + string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native"); + bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath); - // We fail to load "dxil.dll" when doing "dotnet bin\Debug\net5.0\MyApp.dll" - FX.ResolveLibrary += (n, a, s) => ResolveLibrary(n, a, s, probeNuGetDirectory); + // Register a custom library resolver for the two DXC libraries. We need to either manually load the two + // libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is + // loaded correctly in case the program was executed with the host being in another directory. + // This happens when doing eg. "dotnet bin\Debug\net5.0\MyApp.dll", which would crash at runtime. + FX.ResolveLibrary += (n, a, s) => ResolveLibrary(n, a, s, isNuGetRuntimeLibrariesDirectoryPresent); } /// /// A custom resolver to override the default library resolution behavior for the DXC and DXIL libraries. - /// Meant to enable "dotnet run"-like scenarios for projects without RIDs by loading native dependencies from where the SDK puts them. + /// This either loads the libraries from the NuGet directory, or just ensures that DXIL is always loaded. /// /// - private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool probeNuGetDirectory) + private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool isNuGetRuntimeLibrariesDirectoryPresent) { - if (libraryName != "dxcompiler") return IntPtr.Zero; + if (libraryName is not "dxcompiler") return IntPtr.Zero; - if (probeNuGetDirectory) + if (isNuGetRuntimeLibrariesDirectoryPresent) { - string dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @$"runtimes\win-x64\native\dxcompiler.dll"); - string dxilPath = Path.Combine(AppContext.BaseDirectory, @$"runtimes\win-x64\native\dxil.dll"); + string + dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxcompiler.dll"), + dxilPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxil.dll"); - // We are loading the dependency of dxcompiler.dll, dxil.dll, first, so that it is automatically picked up - // from memory by dxcompiler.dll on it being loaded - // This is necessary because .NET does not currently provide great facilities for loading - // native dependencies of native dependencies + // Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path if (NativeLibrary.TryLoad(dxilPath, out _) && NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle)) { return handle; @@ -95,11 +97,13 @@ namespace ComputeSharp.Shaders.Translation } else { - // It may come as a surprise we need this, but apparently we do - // The suspicion is that's because Windows doesn't know anything about .NET's - // "App directory" concept, only "Process directory", and when we invoke "dotnet bin\Managed.dll" - // Neither our current directory ("bin"), nor our "Process directory" ("C:\Program Files\dotnet") contain the native dependency - // Which means LoadLibraryEx fails to load it + // Even when the two libraries are correctly copied next to the executable in use, we load them + // manually to ensure the operation is successful. This is to avoid failures in cases such as when + // doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use. + // This is probably because DXIL is a native dependency for DXC, but the way Windows loads these + // libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin" + // directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the + // native library we need, hence the runtime crash. Manually loading the library this way solves this. if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) && NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle)) { diff --git a/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs b/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs index 27dedca6..6f1add7c 100644 --- a/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs +++ b/tests/ComputeSharp.Tests.NativeLibrariesResolver/NativeLibrariesResolverTests.cs @@ -1,9 +1,6 @@ -using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; using System.ComponentModel; using System.Diagnostics; -using System.Globalization; using System.IO; namespace ComputeSharp.Tests.NativeLibrariesResolver @@ -13,21 +10,29 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver { static NativeLibrariesResolverTests() { - var path = Path.GetDirectoryName(typeof(NativeLibrariesResolverTests).Assembly.Location); + string path = Path.GetDirectoryName(typeof(NativeLibrariesResolverTests).Assembly.Location); + while (Path.GetFileName(path) is not "ComputeSharp") { path = Path.GetDirectoryName(path); } SampleProjectDirectory = Path.Combine(path, "samples", "ComputeSharp.Sample.NuGet"); - var sampleProjectPath = Path.Combine(SampleProjectDirectory, "ComputeSharp.Sample.NuGet.csproj"); - var packagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.msbuildproj"); + string + sampleProjectPath = Path.Combine(SampleProjectDirectory, "ComputeSharp.Sample.NuGet.csproj"), + packagingProjectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.msbuildproj"); + + // Run dotnet pack and on the packaging project, to ensure the local NuGet package is + // available. Then run dotnet restore on the sample project. This is done so that + // other tests can skip the restore step to run faster, as there's lots of them. Process.Start("dotnet", $"pack {packagingProjectPath} -c Release").WaitForExit(); - // We use "--no-restore" where possible to speed up the tests Process.Start("dotnet", $"restore {sampleProjectPath}").WaitForExit(); } + /// + /// Gets the directory of the ComputeSharp.Sample.NuGet project. + /// private static string SampleProjectDirectory { get; } [TestMethod] @@ -37,7 +42,7 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver [DataRow(Configuration.Release, RID.Win_x64)] public void DotnetRunWorks(Configuration configuration, RID rid) { - // "dotnet run" fails with "--no-restore" + // "dotnet run" fails with "--no-restore", so in this case we restore packages as well Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", $"run -c {configuration} {ToOption(rid)}")); } @@ -49,7 +54,9 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver public void DotnetBuildWithRunningDotnetHostFromProjectDirectoryWorks(Configuration configuration, RID rid) { BuildSampleProject(configuration, rid); - var realtivePathToDll = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.dll"); + + string realtivePathToDll = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.dll"); + Assert.AreEqual(0, Exec(SampleProjectDirectory, "dotnet", realtivePathToDll)); } @@ -61,7 +68,9 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver public void DotnetBuildWithRunningDotnetHostDirectlyWorks(Configuration configuration, RID rid) { BuildSampleProject(configuration, rid); - var pathToDllDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + + string pathToDllDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + Assert.AreEqual(0, Exec(pathToDllDirectory, "dotnet", "ComputeSharp.Sample.NuGet.dll")); } @@ -73,7 +82,9 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver public void DotnetBuildWithRunningAppHostFromProjectDirectoryWorks(Configuration configuration, RID rid) { BuildSampleProject(configuration, rid); - var relativePathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.exe"); + + string relativePathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}", "ComputeSharp.Sample.NuGet.exe"); + Assert.AreEqual(0, Exec(SampleProjectDirectory, relativePathToAppHost, "")); } @@ -85,7 +96,9 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver public void DotnetBuildWithRunningAppHostDirectlyWorks(Configuration configuration, RID rid) { BuildSampleProject(configuration, rid); - var pathToAppHostDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + + string pathToAppHostDirectory = Path.Combine(SampleProjectDirectory, "bin", $"{configuration}", "net5.0", $"{ToDirectory(rid)}"); + Assert.AreEqual(0, Exec(pathToAppHostDirectory, "ComputeSharp.Sample.NuGet.exe", "")); } @@ -94,20 +107,34 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver [DataRow(Configuration.Release)] public void DotnetPublishWorks(Configuration configuration) { - // We do not support publishing without the RID + // Publishing without specifying an RID is not supported Exec(SampleProjectDirectory, "dotnet", $"publish -c {configuration} -r win-x64 --no-restore"); - var pathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", "win-x64", "publish", "ComputeSharp.Sample.NuGet.exe"); + + string pathToAppHost = Path.Combine("bin", $"{configuration}", "net5.0", "win-x64", "publish", "ComputeSharp.Sample.NuGet.exe"); + Assert.AreEqual(0, Exec(SampleProjectDirectory, pathToAppHost, "")); } + /// + /// Builds the sample project with a specific configuration and target runtime. + /// + /// The configuration to use to build the project. + /// The RID to use to build the project. private static void BuildSampleProject(Configuration configuration, RID rid) { Exec(SampleProjectDirectory, "dotnet", $"build -c {configuration} {ToOption(rid)} --no-restore"); } + /// + /// Executes a specified process from the command line and returns the exit code. + /// + /// The working directory to execute the process. + /// The target file path for the process to execute. + /// The arguments to invoke the process. + /// The exit code for the executed process. private static int Exec(string workingDirectory, string filePath, string arguments) { - var startInfo = new ProcessStartInfo + ProcessStartInfo startInfo = new() { UseShellExecute = true, CreateNoWindow = true, @@ -117,12 +144,18 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver WorkingDirectory = workingDirectory }; - var process = Process.Start(startInfo); + Process process = Process.Start(startInfo); + process.WaitForExit(); return process.ExitCode; } + /// + /// Gets a text representation of a cmd option for the dotnet tool, for the given . + /// + /// The input value. + /// A text representation for . private static string ToOption(RID rid) => rid switch { RID.None => "", @@ -130,6 +163,11 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver _ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID)) }; + /// + /// Gets a text representation of the build folder for the given . + /// + /// The input value. + /// A text representation for . private static string ToDirectory(RID rid) => rid switch { RID.None => "", @@ -137,12 +175,18 @@ namespace ComputeSharp.Tests.NativeLibrariesResolver _ => throw new InvalidEnumArgumentException(nameof(rid), (int)rid, typeof(RID)) }; + /// + /// A build configuration. + /// public enum Configuration { Debug, Release } + /// + /// A runtime identifier. + /// public enum RID { None,