Skip to content

Commit

Permalink
Use CancelIoEx instead of CancelIo on windows_native
Browse files Browse the repository at this point in the history
Fixes a use-after-free bug when dropping the HidDevice from a thread
other than the one that was last used to read it, because of a pending
async operation that did not get canceled.

If the cancellation does not return an error, we get the overlapped
result to block until it actually goes through. This is recommended by
Microsoft in this example:
<https://learn.microsoft.com/en-us/windows/win32/fileio/canceling-pending-i-o-operations#canceling-asynchronous-io>.

Closes #151
  • Loading branch information
YgorSouza committed Feb 23, 2024
1 parent c2b41a5 commit 884544d
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/windows_native/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ use windows_sys::Win32::Storage::FileSystem::{
OPEN_EXISTING,
};
use windows_sys::Win32::System::Threading::ResetEvent;
use windows_sys::Win32::System::IO::{CancelIo, DeviceIoControl};
use windows_sys::Win32::System::IO::{CancelIoEx, DeviceIoControl};

const STRING_BUF_LEN: usize = 128;

Expand Down Expand Up @@ -179,7 +179,7 @@ impl HidDeviceBackendBase for HidDevice {
if res != TRUE {
let err = Win32Error::last();
if err != Win32Error::IoPending {
unsafe { CancelIo(self.device_handle.as_raw()) };
unsafe { CancelIoEx(self.device_handle.as_raw(), state.overlapped.as_raw()) };
self.read_pending.set(false);
return Err(err.into());
}
Expand Down Expand Up @@ -335,7 +335,16 @@ impl HidDeviceBackendWindows for HidDevice {
impl Drop for HidDevice {
fn drop(&mut self) {
unsafe {
CancelIo(self.device_handle.as_raw());
for state in [
&mut self.read_state,
&mut self.write_state,
&mut self.feature_state,
] {
let mut state = state.borrow_mut();
if CancelIoEx(self.device_handle.as_raw(), state.overlapped.as_raw()) > 0 {
_ = state.overlapped.get_result(&self.device_handle, None);
}
}
}
}
}
Expand Down

0 comments on commit 884544d

Please sign in to comment.