From 4bfff51d71c330ca8c7877a9827accfbe9d285fe Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 17 Oct 2023 01:53:21 +0200 Subject: [PATCH] Refactor DXC libraries loading logic in D3D12 generator --- ...eShaderDescriptorGenerator.HlslBytecode.cs | 77 +------------- .../Dxc/DxcLibraryLoader.cs | 100 ++++++++++++++++++ 2 files changed, 101 insertions(+), 76 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Dxc/DxcLibraryLoader.cs diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs index e6aed98c..75cb5643 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs @@ -1,10 +1,7 @@ using System; using System.Collections.Immutable; using System.ComponentModel; -using System.IO; -using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Threading; using ComputeSharp.SourceGeneration.Extensions; @@ -17,8 +14,6 @@ using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; -#pragma warning disable RS1035 - namespace ComputeSharp.SourceGenerators; /// @@ -34,11 +29,6 @@ partial class ComputeShaderDescriptorGenerator /// private static readonly DynamicCache HlslBytecodeCache = new(); - /// - /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. - /// - private static volatile bool areDxcLibrariesLoaded; - /// /// Gets the instance for the input shader info. /// @@ -58,7 +48,7 @@ partial class ComputeShaderDescriptorGenerator try { // Try to load dxcompiler.dll and dxil.dll - LoadNativeDxcLibraries(); + DxcLibraryLoader.LoadNativeDxcLibraries(); token.ThrowIfCancellationRequested(); @@ -141,70 +131,5 @@ partial class ComputeShaderDescriptorGenerator return message.NormalizeToSingleLine(); } - - /// - /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. - /// - /// Thrown if the CPU architecture is not supported. - /// Thrown if a library fails to load. - private static void LoadNativeDxcLibraries() - { - // Extracts a specified native library for a given runtime identifier - static string ExtractLibrary(string folder, string rid, string name) - { - string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll"; - string targetFilename = Path.Combine(folder, rid, $"{name}.dll"); - - _ = Directory.CreateDirectory(Path.GetDirectoryName(targetFilename)); - - using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename); - - try - { - using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write); - - sourceStream.CopyTo(destinationStream); - } - catch (IOException) - { - } - - return targetFilename; - } - - // Loads a target native library - static unsafe void LoadLibrary(string filename) - { - [DllImport("kernel32", ExactSpelling = true, SetLastError = true)] - static extern void* LoadLibraryW(ushort* lpLibFileName); - - fixed (char* p = filename) - { - if (LoadLibraryW((ushort*)p) is null) - { - int hresult = Marshal.GetLastWin32Error(); - - throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}."); - } - } - } - - if (!areDxcLibrariesLoaded) - { - string rid = RuntimeInformation.ProcessArchitecture switch - { - Architecture.X64 => "x64", - Architecture.Arm64 => "arm64", - _ => throw new NotSupportedException("Invalid process architecture") - }; - - string folder = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName()); - - LoadLibrary(ExtractLibrary(folder, rid, "dxil")); - LoadLibrary(ExtractLibrary(folder, rid, "dxcompiler")); - - areDxcLibrariesLoaded = true; - } - } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Dxc/DxcLibraryLoader.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcLibraryLoader.cs new file mode 100644 index 00000000..f8aae469 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcLibraryLoader.cs @@ -0,0 +1,100 @@ +using System; +using System.ComponentModel; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; + +#pragma warning disable RS1035 + +namespace ComputeSharp.SourceGenerators.Dxc; + +/// +/// A that handles loading the DXC libraries. +/// +internal sealed unsafe class DxcLibraryLoader +{ + /// + /// An object to use to synchronize loading the DXC libraries. + /// + private static readonly object LoadingLock = new(); + + /// + /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. + /// + private static volatile bool areDxcLibrariesLoaded; + + /// + /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. + /// + /// Thrown if the CPU architecture is not supported. + /// Thrown if a library fails to load. + public static void LoadNativeDxcLibraries() + { + // Extracts a specified native library for a given runtime identifier + static string ExtractLibrary(string folder, string rid, string name) + { + string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll"; + string targetFilename = Path.Combine(folder, rid, $"{name}.dll"); + + _ = Directory.CreateDirectory(Path.GetDirectoryName(targetFilename)); + + using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename); + + try + { + using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write); + + sourceStream.CopyTo(destinationStream); + } + catch (IOException) + { + } + + return targetFilename; + } + + // Loads a target native library + static unsafe void LoadLibrary(string filename) + { + [DllImport("kernel32", ExactSpelling = true, SetLastError = true)] + static extern void* LoadLibraryW(ushort* lpLibFileName); + + fixed (char* p = filename) + { + if (LoadLibraryW((ushort*)p) is null) + { + int hresult = Marshal.GetLastWin32Error(); + + throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}."); + } + } + } + + if (areDxcLibrariesLoaded) + { + return; + } + + lock (LoadingLock) + { + if (areDxcLibrariesLoaded) + { + return; + } + + string rid = RuntimeInformation.ProcessArchitecture switch + { + Architecture.X64 => "x64", + Architecture.Arm64 => "arm64", + _ => throw new NotSupportedException("Invalid process architecture") + }; + + string folder = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName()); + + LoadLibrary(ExtractLibrary(folder, rid, "dxil")); + LoadLibrary(ExtractLibrary(folder, rid, "dxcompiler")); + + areDxcLibrariesLoaded = true; + } + } +} \ No newline at end of file