Skip to content

Commit

Permalink
Fixed NTSTATUS to Win32 error code conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
nefarius committed Jun 28, 2024
1 parent 79a9678 commit 3526322
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
3 changes: 3 additions & 0 deletions App/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// See https://aka.ms/new-console-template for more information

using Nefarius.Utilities.DeviceManagement.Drivers;
using Nefarius.Utilities.DeviceManagement.PnP;

DriverStore.RemoveDriver(@"C:\temp\nonexistent");

const string instanceId = @"USB\VID_054C&PID_0CE6&MI_03\9&DC32669&3&0003";

PnPDevice device = PnPDevice.GetDeviceByInstanceId(instanceId);
Expand Down
16 changes: 14 additions & 2 deletions src/Util/NtStatusUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,25 @@ public static class NtStatusUtil
/// <remarks>https://stackoverflow.com/a/32205631</remarks>
/// <param name="ntStatus">The NTSTATUS value to convert.</param>
/// <returns>The converted Win32 error code.</returns>
public static int ConvertNtStatusToWin32Error(uint ntStatus)
public static unsafe int ConvertNtStatusToWin32Error(uint ntStatus)
{
NativeOverlapped ol = new() { InternalLow = (IntPtr)ntStatus };
int oldError = Marshal.GetLastWin32Error();
PInvoke.GetOverlappedResult(null, ol, out uint _, new BOOL(false));
// tricking GetOverlappedResult to do the conversion for us :)
GetOverlappedResult(IntPtr.Zero, &ol, out int _, new BOOL(false));
int result = Marshal.GetLastWin32Error();
PInvoke.SetLastError((WIN32_ERROR)oldError);
return result;
}

/// <summary>
/// The CsWin32-generated variant doesn't allow for an empty file handle so we gotta cheat a bit :)
/// </summary>
[DllImport("Kernel32.dll", SetLastError = true)]
private static extern unsafe bool GetOverlappedResult(
IntPtr hFile,
NativeOverlapped* lpOverlapped,
out int lpNumberOfBytesTransferred,
bool bWait
);
}

0 comments on commit 3526322

Please sign in to comment.