Skip to content

Commit

Permalink
Added DLL resolver for Cuda on WSL. (#1177)
Browse files Browse the repository at this point in the history
  • Loading branch information
MoFtZ authored Apr 10, 2024
1 parent b81e422 commit 5b250cb
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions Src/ILGPU/Runtime/Cuda/CudaContextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
using ILGPU.Backends.PTX;
using ILGPU.Resources;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

namespace ILGPU.Runtime.Cuda
{
Expand Down Expand Up @@ -90,6 +94,13 @@ public static Context.Builder CudaInternal(
if (builder.LibDevicePath is null && builder.LibNvvmPath is null)
builder.LibDevice(throwIfNotFound: false);

if (IsRunningOnWSL())
{
NativeLibrary.SetDllImportResolver(
Assembly.GetExecutingAssembly(),
CudaWSLDllImportResolver);
}

CudaDevice.GetDevices(
configure,
predicate,
Expand All @@ -99,6 +110,77 @@ public static Context.Builder CudaInternal(

#endregion

#region Windows Subsystem for Linux

/// <summary>
/// The base directory where WSL is expected to be installed.
/// </summary>
private const string WslLibaryBasePath = "/usr/lib/wsl/lib";

/// <summary>
/// Detects if we are running on WSL.
/// </summary>
[SuppressMessage(
"Design",
"CA1031:Do not catch general exception types",
Justification = "If file does not exist, or cannot be read, this is not WSL")]
private static bool IsRunningOnWSL()
{
try
{
return RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
&& File.ReadAllText("/proc/version").Contains(
"Microsoft",
StringComparison.OrdinalIgnoreCase)
&& Directory.Exists(WslLibaryBasePath);
}
catch (Exception)
{
return false;
}
}

/// <summary>
/// Ordered list of library name combinations to try loading.
/// </summary>
private static readonly (string Prefix, string Suffix)[] WslLibraryCombinations =
new[]
{
( string.Empty, ".so" ),
( "lib", ".so" ),
( string.Empty, string.Empty ),
( "lib", string.Empty )
};

/// <summary>
/// Attempts to load the Cuda DLL from the WSL folder.
/// </summary>
private static IntPtr CudaWSLDllImportResolver(
string libraryName,
Assembly assembly,
DllImportSearchPath? searchPath)
{
if (!libraryName.Equals(
CudaAPI.LibNameLinux,
StringComparison.OrdinalIgnoreCase))
{
return IntPtr.Zero;
}

foreach (var (prefix, suffix) in WslLibraryCombinations)
{
var filename = $"{prefix}{libraryName}{suffix}";
var libraryPath = Path.Combine(WslLibaryBasePath, filename);

if (NativeLibrary.TryLoad(libraryPath, out var handle))
return handle;
}

return IntPtr.Zero;
}

#endregion

#region Context

/// <summary>
Expand Down

0 comments on commit 5b250cb

Please sign in to comment.