Repository navigation
Conversation
|
If this is very much based on someone else's work I'd suggest adding a proper "Co-authored-by:" tag in the commit message and not just @'mention a github user name. |
DeviceIoControl() will hang indefinitely when the Nacon PS4 Compact Controller is connected, so use async mode to safely call it with a timeout. Co-authored-by: shaodiwei <shaodiwei@tencent.com>
d033d50 to
a87d5a5
Compare
Done! |
|
I have set this for milestone 1.0.31. But we need to wait for the review of the other maintainers like @sonatique. |
There was a problem hiding this comment.
Pull request overview
Updates the Windows WinUSB backend to avoid indefinite hangs from DeviceIoControl() (notably observed with the Nacon PS4 Compact Controller) by using overlapped I/O with a bounded wait.
Changes:
- Added an async
DeviceIoControlwrapper (device_io_control) with a fixed timeout. - Switched hub/root-hub IOCTL queries in device initialization/config caching to use the wrapper.
- Opened relevant hub/root-hub handles with
FILE_FLAG_OVERLAPPEDand introduced a per-initio_event.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| CancelIoEx(hDevice, &overlapped); | ||
| return FALSE; | ||
| } | ||
|
|
||
| DWORD wret = WaitForSingleObject(event, IO_WAIT_TIME); | ||
| if (wret != WAIT_OBJECT_0) { | ||
| CancelIoEx(hDevice, &overlapped); |
There was a problem hiding this comment.
On the error paths in device_io_control(), CancelIoEx() can overwrite the original GetLastError() from DeviceIoControl(), and WaitForSingleObject() timeouts don't set a useful last-error value. Since callers log windows_error_str(0), this can produce misleading diagnostics. Preserve/restore the original error code (store it before cancelling and SetLastError(error) before returning) and set a clear error on timeout (e.g. ERROR_SEM_TIMEOUT).
| CancelIoEx(hDevice, &overlapped); | |
| return FALSE; | |
| } | |
| DWORD wret = WaitForSingleObject(event, IO_WAIT_TIME); | |
| if (wret != WAIT_OBJECT_0) { | |
| CancelIoEx(hDevice, &overlapped); | |
| CancelIoEx(hDevice, &overlapped); | |
| SetLastError(error); | |
| return FALSE; | |
| } | |
| DWORD wret = WaitForSingleObject(event, IO_WAIT_TIME); | |
| if (wret != WAIT_OBJECT_0) { | |
| DWORD wait_error; | |
| if (wret == WAIT_TIMEOUT) | |
| wait_error = ERROR_SEM_TIMEOUT; | |
| else if (wret == WAIT_FAILED) | |
| wait_error = GetLastError(); | |
| else | |
| wait_error = ERROR_GEN_FAILURE; | |
| CancelIoEx(hDevice, &overlapped); | |
| SetLastError(wait_error); |
|
|
||
| ResetEvent(event); | ||
| memset(&overlapped, 0, sizeof(overlapped)); | ||
| overlapped.hEvent = event; | ||
|
|
||
| if (!DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesReturned, &overlapped)) { | ||
| DWORD error = GetLastError(); | ||
| if (error != ERROR_IO_PENDING) { | ||
| CancelIoEx(hDevice, &overlapped); | ||
| return FALSE; | ||
| } | ||
|
|
||
| DWORD wret = WaitForSingleObject(event, IO_WAIT_TIME); | ||
| if (wret != WAIT_OBJECT_0) { | ||
| CancelIoEx(hDevice, &overlapped); | ||
| return FALSE; | ||
| } else { | ||
| DWORD bytes_written = 0; | ||
| if (!GetOverlappedResult(hDevice, &overlapped, &bytes_written, TRUE)) | ||
| return FALSE; | ||
| } | ||
| } | ||
| return TRUE; |
There was a problem hiding this comment.
This PR introduces an async+timeout wrapper for hub IOCTLs, but winusb_get_device_string() in the same file still opens the hub handle without FILE_FLAG_OVERLAPPED and calls DeviceIoControl(..., NULL) directly for IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION (see around line ~2320). If the hang is triggered by this IOCTL as well, string descriptor queries can still block indefinitely. Consider switching that call site to use the same async wrapper (and an overlapped-capable handle/event) for consistency and to fully address the reported hang.
| ResetEvent(event); | |
| memset(&overlapped, 0, sizeof(overlapped)); | |
| overlapped.hEvent = event; | |
| if (!DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesReturned, &overlapped)) { | |
| DWORD error = GetLastError(); | |
| if (error != ERROR_IO_PENDING) { | |
| CancelIoEx(hDevice, &overlapped); | |
| return FALSE; | |
| } | |
| DWORD wret = WaitForSingleObject(event, IO_WAIT_TIME); | |
| if (wret != WAIT_OBJECT_0) { | |
| CancelIoEx(hDevice, &overlapped); | |
| return FALSE; | |
| } else { | |
| DWORD bytes_written = 0; | |
| if (!GetOverlappedResult(hDevice, &overlapped, &bytes_written, TRUE)) | |
| return FALSE; | |
| } | |
| } | |
| return TRUE; | |
| DWORD error, wret, bytes_written = 0; | |
| ResetEvent(event); | |
| memset(&overlapped, 0, sizeof(overlapped)); | |
| overlapped.hEvent = event; | |
| if (lpBytesReturned != NULL) | |
| *lpBytesReturned = 0; | |
| if (DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesReturned, &overlapped)) | |
| return TRUE; | |
| error = GetLastError(); | |
| if (error != ERROR_IO_PENDING) | |
| return FALSE; | |
| wret = WaitForSingleObject(event, IO_WAIT_TIME); | |
| if (wret == WAIT_OBJECT_0) | |
| return GetOverlappedResult(hDevice, &overlapped, &bytes_written, TRUE); | |
| /* | |
| * CancelIoEx() is asynchronous. Do not return until the pending request | |
| * has reached a terminal state, otherwise the stack-allocated OVERLAPPED | |
| * may be referenced after this function returns. | |
| */ | |
| error = (wret == WAIT_TIMEOUT) ? WAIT_TIMEOUT : | |
| (wret == WAIT_FAILED) ? GetLastError() : ERROR_GEN_FAILURE; | |
| CancelIoEx(hDevice, &overlapped); | |
| if (!GetOverlappedResult(hDevice, &overlapped, &bytes_written, TRUE)) { | |
| DWORD cancel_error = GetLastError(); | |
| if (cancel_error != ERROR_OPERATION_ABORTED) | |
| error = cancel_error; | |
| } | |
| SetLastError(error); | |
| return FALSE; |
| DWORD bytes_written = 0; | ||
| if (!GetOverlappedResult(hDevice, &overlapped, &bytes_written, TRUE)) | ||
| return FALSE; | ||
| } |
There was a problem hiding this comment.
device_io_control() doesn't write the async completion byte count back to *lpBytesReturned. In the ERROR_IO_PENDING path you only store into a local bytes_written, so callers like cache_config_descriptors() end up using an uninitialized ret_size and can misbehave. Set *lpBytesReturned = bytes_written on success (and consider zeroing it on failure).
| if (!DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesReturned, &overlapped)) { | ||
| DWORD error = GetLastError(); | ||
| if (error != ERROR_IO_PENDING) { | ||
| CancelIoEx(hDevice, &overlapped); | ||
| return FALSE; | ||
| } | ||
|
|
||
| DWORD wret = WaitForSingleObject(event, IO_WAIT_TIME); | ||
| if (wret != WAIT_OBJECT_0) { | ||
| CancelIoEx(hDevice, &overlapped); | ||
| return FALSE; | ||
| } else { |
There was a problem hiding this comment.
device_io_control() returns after calling CancelIoEx() on timeout / non-pending failure while the OVERLAPPED overlapped is stack-allocated. Cancellation is asynchronous, so the I/O may still complete later and write into the now-dead stack OVERLAPPED, leading to memory corruption. After CancelIoEx() you need to wait for the overlapped to complete (e.g., GetOverlappedResult(..., TRUE) expecting ERROR_OPERATION_ABORTED) before returning, or keep the OVERLAPPED alive until completion.
|
Using the tip from @tormodvolden here. |
|
Last time I had issues with This time it seems to be okay. |
Youw
left a comment
There was a problem hiding this comment.
Codex reviewed current head a87d5a5d2d5ddce55a165518eff642511ef406be against master and checked Copilot's four unresolved inline threads. The Copilot review is not stale: it was submitted on this same head, every thread is still marked isOutdated: false, and each finding still maps to the current code.
The following blockers remain:
- The timeout path returns immediately after
CancelIoEx()while the stackOVERLAPPED, event, handle, and caller buffers may still be owned by the request.CancelIoEx()does not wait for terminal completion. The state must remain alive and be reaped later, or cancellation must be drained before releasing it. - The successful pending-I/O path writes the transferred length only to local
bytes_written; callers then read an uninitialized/staleret_size. PasslpBytesReturnedtoGetOverlappedResult()or copy the local value on success. - Immediate failures and timeouts lose meaningful
GetLastError()state. Preserve the initiating/wait error across cleanup and set an explicit timeout error. winusb_get_device_string()still opens the hub synchronously and invokes the sameIOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTIONwithout anOVERLAPPED, leaving an unbounded path. Route it through the corrected helper with an overlapped handle and manual-reset event.
The inline comment adds a separate auto-reset-event hang not identified by Copilot. The cancellation/lifetime repair cannot safely be expressed as a single-hunk suggestion: blocking until cancellation completes repairs lifetime but can defeat the hard deadline if a driver does not complete cancellation promptly; a strict deadline requires request-owned persistent state/buffers plus eventual completion cleanup.
Codex also checked the closed predecessor, #1127.
References: CancelIoEx, DeviceIoControl, and overlapped I/O synchronization.
Generated by Codex (GPT-5.6 Sol).
| if (priv->initialized) | ||
| return LIBUSB_SUCCESS; | ||
|
|
||
| io_event = CreateEventA(NULL, FALSE, FALSE, NULL); |
There was a problem hiding this comment.
[P1] Use a manual-reset event for the two-step wait. WaitForSingleObject() consumes this auto-reset event, and the subsequent GetOverlappedResult(..., TRUE) can then block indefinitely -- exactly the failure mode this PR is meant to prevent. Microsoft documents this combination as unsafe. Create a manual-reset event here and use GetOverlappedResult(..., FALSE) after WAIT_OBJECT_0; reuse the event only after each request reaches a terminal state.
| io_event = CreateEventA(NULL, FALSE, FALSE, NULL); | |
| io_event = CreateEventA(NULL, TRUE, FALSE, NULL); |
Reference: Synchronization and Overlapped Input and Output.
Generated by Codex (GPT-5.6 Sol).
There was a problem hiding this comment.
io_event is shared between cache_config_descriptors() and the V2 call that follows it in init_device(). A request abandoned by a timeout can therefore signal the event for the next request on the same handle, which returns success with an unfilled buffer. A manual-reset event alone doesn't fix it.
sonatique
left a comment
There was a problem hiding this comment.
The problem here is real and worth fixing (an unbounded DeviceIoControl() in init_device() blocks under the device-list lock, so one misbehaving device stalls the whole library).
But I think the issue is broader than the threads already on the PR suggest: as it is written now it would be a regression for every Windows user, not a partial fix for one controller.
Example: The missing byte count that Copilot flagged: whenever a hub IOCTL goes pending (which is the state this patch is specifically designed to create) ret_size is left uninitialized, and both call sites in cache_config_descriptors() gate on it: lines 809/815 and 835/843 on this branch. So config descriptors would silently stop being cached across a wide range of devices. That's not a corner case, and it's the reason I'd rather see the helper rewritten than patched hunk by hunk.
I think 4 things need to be addressed:
-
Please attach a debug log from the Nacon repro on the current head. FILE_FLAG_OVERLAPPED only helps if usbhub returns STATUS_PENDING. If the hang is inside the driver's dispatch routine, the flag changes nothing, CancelIoEx() has nothing to cancel, and the patch is all risk with no benefit. Not all of us have this device, so a log showing the timeout actually firing and enumeration continuing is what tells us the approach is right at all.
-
Please rebase onto master, and cover winusb_get_device_string() while you're there. Copilot already flagged the string fetch at line 2320 on this branch: it opens the hub without FILE_FLAG_OVERLAPPED and issues IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION directly, which is exactly the request this patch treats as dangerous, so it should go through the same helper. Master has since added language-ID caching to that function, which introduces a second unbounded call on the same handle (master lines 2337 and 2364), so a rebase is needed for both to be covered. Master has also moved on in other ways since f1af64b.
-
A timed-out device becomes a permanent stall, not a one-time one. On the timeout path priv->initialized is never set, so the device is re-initialized on every libusb_get_device_list() call and pays the full timeout again, indefinitely. With the Nacon plugged in, an app that polls the device list trades a single hang for a multi-second stall on every iteration. If that trade is intended it should be stated; more likely it needs a cheap "known bad" marker so we don't retry forever.
A design question for the other maintainers, not for @slouken : the backend already has overlapped I/O plus an I/O completion port in windows_open(). This adds a second, hand-rolled async mechanism that then blocks. That may be the right call for enumeration, which is synchronous by design in the core, but I'd like it to be a decision rather than an accident.
| #include "libusbi.h" | ||
| #include "windows_winusb.h" | ||
|
|
||
| #define IO_WAIT_TIME 1000 |
There was a problem hiding this comment.
I think that this bounds all of enumeration, not just the request that hangs: node info, both INFORMATION_EX variants, V2, and every config-descriptor fetch now inherit it.
A hub resuming from selective suspend, or a loaded machine, can legitimately exceed one second — and when it does the failure is silent and severe. init_device() returns LIBUSB_ERROR_NO_DEVICE and the device just disappears from libusb_get_device_list(); init_root_hub() breaks out of the port loop and reports the wrong speed.
Could you justify the value, and add a comment giving the rationale? A named constant with "why 1000" next to it will save the next person this exact question.
And maybe more importantly : I'd also like to see the timeout scoped to the request that actually hangs rather than applied everywhere: the other IOCTLs have no reported problem, and every one we wrap is new risk for no benefit.
|
Test results. |
|
libusb git testlibusb output is a bit different -- probably due to the changes in git. The warning is not present in latest git. |
|
Closing this PR since its replacement PR #1882 is merged. |
DeviceIoControl() will hang indefinitely when the Nacon PS4 Compact Controller is connected, so use async mode to safely call it with a timeout.
We're running into this when adding support for libusb to Steam, so this is a critical fix for us.
This PR is based on #1127, with the requested changes applied and code reformatted to match libusb style.