The last native error is read after a call of a native method that does not save it
What it finds
The error code of a failed Windows or POSIX call reaches .NET code only when the marshaller saves it right after the call, which it does for a [DllImport] or [LibraryImport] declared with SetLastError = true. Without it, Marshal.GetLastWin32Error(), Marshal.GetLastPInvokeError() and new Win32Exception() give whatever code some earlier call left behind, often 0, so the error is misreported.
Reported is a read of the last error in the statement of a call, or the statement after it, of a native method declared in the file without SetLastError = true, when no declaration of that name in the file sets it and no other native call of the file comes in between. Tests are left alone.
From the rule's source, last_error_without_set_last_error.rs.
using System;using System.ComponentModel;using System.Runtime.InteropServices; static class Native{ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", SetLastError = true)] static extern bool FlushFileBuffers(IntPtr handle); static void Close(IntPtr handle) { if (!CloseHandle(handle)) { int error = Marshal.GetLastWin32Error();tx0 reports: the last error is read after CloseHandle, which is declared without SetLastError = true } } static void Flush(IntPtr handle) { if (!FlushFileBuffers(handle)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (!CloseHandle(handle)) { throw new Win32Exception();tx0 reports: new Win32Exception() reads the last error after CloseHandle } } static int Last() => Marshal.GetLastWin32Error();} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/csharp:last-error-without-set-last-error" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/csharp:last-error-without-set-last-error] reason="..."tx0 explain tx0/csharp:last-error-without-set-last-error shows the same in the terminal. Found a false positive? Report it.