Commit Graph
1703 Commits
Author SHA1 Message Date
Giova c1c01e6593 darwin: allow cancelling bulk stream transfers
darwin_cancel_transfer() routes bulk, interrupt and isochronous
transfers to darwin_abort_transfers(), which already knows how to abort
a single bulk stream with AbortStreamsPipe(). LIBUSB_TRANSFER_TYPE_BULK_STREAM
was missing from the switch, so libusb_cancel_transfer() returned
LIBUSB_ERROR_INVALID_PARAM for every stream transfer.

USB Attached SCSI uses the command tag as the bulk stream id, so a
redirection host cancels stream transfers constantly. When the cancel is
not applied the transfer stays in flight on the host controller and the
guest's command never completes, which surfaces as a 30 second SCSI
timeout and a device reset in the guest.

A caller that cancels its transfers and waits for them to complete, as
usbredirhost does when it releases a device, waits forever while a
stream transfer is pending, and USB Attached SCSI keeps one pending on
its status pipe.

Assisted-by: OpenCode:deepseek-v4.1-flash
Assisted-by: Claude:claude-fable-5-2
2026-11-10 22:18:40 -08:00
osy 9eaebb7141 darwin: do not set NULL device in darwin_reload_device
We need to maintain the invariant that `device` is never an invalid
pointer because another thread might be concurrently accessing it. We
want that thread to error from an outdated `device` rather than crash
on a NULL pointer.
2025-10-01 12:20:41 -07:00
osy 80a7d8ed3d darwin: handle error from GetConfigurationDescriptorPtr
When a device is disconnected or otherwise `dpriv->device` is invalid,
`GetConfigurationDescriptorPtr` will return `kIOReturnNoDevice` and
`IOUSBConfigurationDescriptorPtr` will not be set. This means that we
have an uninitialized pointer that is read from which is... very bad.
2025-10-01 12:15:18 -07:00
osy e63455ac85 darwin: fix race condition on device open
Similar to the previous commit with device capture counts, we also need to
take account of multiple contexts calling open/close on a device and make
sure the open_count is immune to data races.
2025-08-25 12:07:26 -07:00
osy 26ba141610 darwin: fix use after free during reenumeration
When one process has two contexts to libusb, it may trigger a reenumeration
while the other context accesses `*dpriv->device`. Adding a mutex to access
`device` can be costly because it is used in every function. Instead, we
maintain an invariant: the `darwin_cached_device` must be valid at all
times. In particular, this means the fields `device` and `service` must not
be stale or we will have a use after free triggerable through a race
condition.

Previously, in `darwin_devices_detached` during reenumeration, it was
possible for `old_device->device` to be freed. We now defer this free to
`darwin_get_cached_device` after a new `device` is written. Note that the
order is important because we do not have locks, so we must free the old
device after writing the new one. The same point applies to `service` which
we take care to free after the new `service` is written.

A caveat here is that even if we do not crash it is still possible for one
context to be using an outdated `device` and `service` leading to an error
return. This should be acceptable because it would be a similar situation
to the device being detached during an API call.
2025-08-24 20:19:19 -07:00
osy e3af7352dd darwin: fix race condition on device capture
If two threads try to capture at the same time, the result can be
inconsistent. For example, a process can have two different contexts to
libusb and both call `libusb_reset_device`.
2025-08-24 20:19:19 -07:00
Nathan Hjelm 4183a1c6c6 darwin: add missing locking around cached device list cleanup
The cleanup function darwin_cleanup_devices was intented to be called only once
at program exit. When the initialization/finalization code was changed to
destroy the cached device list on last exit this function should have been
modified to require a lock on darwin_cached_devices_lock. This commit updates
cleanup to protect the cached device list with the cached devices mutex and
updates darwin_init to print out an error and return if a reference leak is
detected.

Also using this opportunity to correct the naming of the mutex. Changed
darwin_cached_devices_lock to darwin_cached_devices_mutex. Also cleaning the
initialization code up a bit. Removing the context pointer from the hotplug
thread as it is not used for anything but logging.

Fixes #1124

Signed-off-by: Nathan Hjelm <[email protected]>
2025-08-17 18:34:57 -07:00
Nathan Hjelm 2c55fbe171 darwin: Do not clear device data toggle on macOS 10.5 or newer
Historically Mac OS X always cleared the data toggle on the host side. For
consistency, libusb has been calling ClearPipeStallBothEnds to also clear the
device side toggle. Newer versions of the IOUSBLib do not clear the host side
toggle so there is no need to make this call. Additionally, some buggy devices
may fail to correctly implement clearing the data toggle.

Signed-off-by: Nathan Hjelm <[email protected]>
[Tormod: Return result from AbortPipe]
Signed-off-by: Tormod Volden <[email protected]>
2025-08-03 14:00:45 -07:00
Benjamin Berg c6cfa4b7ea darwin: Fix crash in log handler when stopping event thread
The darwin event thread (in contrast to other OS implementations) tries
to log to the context that created it. However, this context is only
guaranteed to be valid until the thread has started. It may be that
another context is the last one to be destroyed, causing the event
thread to log using an already destroyed context.

Fix this by only passing on ctx where it is acceptable.

Fixes #1108
2025-08-03 13:56:23 -07:00
osy b5a7dca8cb darwin: reset by re-enumerate on non-macOS platforms
On non-macOS platforms, ResetDevice() does nothing so we use the "old" way of
calling re-enumerate. If the device is captured, we have to re-enumerate, then
re-capture, re-authorize, and finally restore the state.
2022-03-05 18:11:33 -08:00
Tormod Volden 4622bfcf44 libusb 1.0.25
Signed-off-by: Tormod Volden <[email protected]>
2022-01-31 13:57:06 +01:00
Tormod Volden cfc4714452 appveyor: Retain selected build artifacts
Signed-off-by: Tormod Volden <[email protected]>
2022-01-30 00:00:32 +01:00
Tormod Volden afcd360005 examples: Do not assume positive errno macros
Some functions were returning e.g. -ENOMEM and the caller would check
for negative return values. However, on Haiku, contrary to modern
standards, these macros are negative, so this logic would fail. In any
case, change the function to return -1 instead. For good measure also
set errno to the appropriate value, although it is not used in the
current code.

This was discovered on Haiku builds because the value for ENOMEM is
INT_MIN which cannot be negated without overflow.

Signed-off-by: Tormod Volden <[email protected]>
2022-01-22 14:47:17 +01:00
Tormod Volden 65b786f77d netbsd: Fix typo preventing build
Fixup of commit 6cae9c6

Tested-by: Xiaofan Chen <[email protected]>
Signed-off-by: Tormod Volden <[email protected]>
2022-01-22 12:55:44 +01:00
Tormod Volden f1e562e007 libusb 1.0.25-rc1
Signed-off-by: Tormod Volden <[email protected]>
2022-01-21 21:10:16 +01:00
Tormod Volden 99d9bbda44 Add libusb_set_option to libusb-1.0.def manually
Since libusb_set_option() is variadic, there is no symbol
for it with @ appended in the DLL, and the automatic
generation of libusb-1.0.def misses it.

Signed-off-by: Tormod Volden <[email protected]>
2022-01-21 20:24:15 +01:00
Tormod Volden 7ffad5c137 Update AUTHORS
Based on `git shortlog -s | cut -c8-` and a lot of manual fixups.

Signed-off-by: Tormod Volden <[email protected]>
2022-01-21 18:32:23 +01:00
Tormod Volden 7691236353 Update libusb-1.0.def
Updated by running the following on a libusb-1.0 DLL generated by MinGW32:

echo -e "LIBRARY \"libusb-1.0.dll\"\nEXPORTS" > libusb-1.0.def
strings libusb-1.0.dll | grep ^libusb | grep @ | LC_ALL=C sort | uniq | \
 sed -e "s/\(.*\)@\([0-9]*\)/  \1\n  \1@\2 = \1/" | LC_ALL=C sort >> libusb-1.0.def

Signed-off-by: Tormod Volden <[email protected]>
2022-01-21 18:03:01 +01:00
Ludovic Rousseau b4ff207501 Add github action for macOS
Signed-off-by: Ludovic Rousseau <[email protected]>
2022-01-20 22:27:37 +01:00
Ludovic Rousseau 1ec1f9ba07 Add github action for GNU/Linux
Signed-off-by: Ludovic Rousseau <[email protected]>
2022-01-20 22:26:53 +01:00
Andrew Goodney c1ed589543 The current code for calculating the timeout in darwin_reenumerate_device_timeout() doesn't calculate elapsed microseconds, it counts the number of times the loop runs.
This results in very long timeouts.

This PR uses clock_gettime(CLOCK_MONOTONIC, ...) to calculate the elapsed time

Closes #1035

Signed-off-by: Nathan Hjelm <[email protected]>
2022-01-18 15:32:24 -07:00
Tormod Volden f2b218b618 darwin: Minor tidy up in darwin_set_interface_altsetting()
Closes #1032

Signed-off-by: Tormod Volden <[email protected]>
2021-12-01 09:43:27 -07:00
Nathan Hjelm b4b4138a31 darwin: fix behavior of libusb_set_interface_alt_setting when it stalls the pipe
In some versions of macOS a pipe stall returned when setting the alternate interface
causes the interface to become unusable. To handle this case the backend was always
re-claiming the interface before clearing the pipe stall. In macOS Monterey
unconditionally re-claiming the interface leads to an error due to the process already
having exclusive access. To resolve this issue we attempt to clear the halt and only
re-claim the interface if clearing the pipe stall returns kIOUSBUnknownPipeErr. Tested
with 12.0.1 and 10.13 and get the expected results in both cases with a custom USB
device that has this behavior.

Fixes #1011
Closes #1031

Signed-off-by: Nathan Hjelm <[email protected]>
2021-12-01 09:42:15 -07:00
Tormod Volden 1170db79bd Bump LIBUSB_API_VERSION
LIBUSB_OPTION_NO_DEVICE_DISCOVERY is new.

Closes #1004

Signed-off-by: Tormod Volden <[email protected]>
Signed-off-by: Nathan Hjelm <[email protected]>
2021-11-27 10:05:00 -07:00
Tormod Volden 33d9949921 Keep LIBUSB_OPTION_WEAK_AUTHORITY as a macro with same value
If the value is always the same we retain binary compatibility.

References #935

Signed-off-by: Tormod Volden <[email protected]>
Signed-off-by: Nathan Hjelm <[email protected]>
2021-11-27 10:04:05 -07:00
AdamKorcz 143a33744f Fuzzing: Add CIFuzz 2021-11-27 10:01:08 -07:00
Matthias Bolte d4452bd555 core: Unlock and clear default ctx in all error paths in libusb_init
Commit 32a2206942 reordered and
refactored libusb_init. This resulted in moving code outside the
default ctx lock that was unrelated to it. But this resulted in
broken error path cleanup logic that leaves the default ctx as
locked, half initialized and freed in case a libusb_set_option or
the usbi_io_init call fails.

Undo part of the previous reordering to unlock and clear the default
ctx in all error paths in libusb_init.

Closes #995

Signed-off-by: Nathan Hjelm <[email protected]>
2021-11-23 23:02:43 -07:00
Tormod Volden 683e3cf21e core: Minor code cleanup in libusb_init (NOP)
After commit f7084fe the if clause would always be true, so remove it.

Thanks to "xloem" for reporting.

References #942

Signed-off-by: Tormod Volden <[email protected]>
2021-11-09 10:05:38 +01:00
Tormod Volden 5b408d1084 Windows: Allow synchronous control transfers (for libusb0)
Some of the changes in commit 9c28ad2 rely on all transfers having (or
appearing to have) asynchronous completion.

However, the libusb0.sys backend of libusbk.dll performs all control
transfers synchronously and ignores any "overlapped" structure handed to
it. Our asynchronous handling will in this case be pending and
eventually time out although the USB request itself was successful.

Therefore restore the possibility of synchronous completion of control
transfers, by forcing the completion handling on a successful return
from request submission. This brings the code closer to how it was
established in commit ce95f65.

Fixes #94

Tested-by: Xiaofan Chen <[email protected]>
Signed-off-by: Tormod Volden <[email protected]>
2021-11-09 09:19:59 +01:00
Julian Scheel 7b342030d2 Windows: Fix timeouts if only endpoint 0 exists
The default timeouts of 5 seconds used by WinUSB are cleared in
configure_endpoints(). This was not called if not at least one extra
endpoint apart from endpoint 0 existed, so that in those cases the
default timeout of 5 seconds remained in place.
Fix this by calling configure_endpoints, even if no interface specific
endpoints were found, so that it can configure endpoint 0.

Closes #963

Signed-off-by: Julian Scheel <[email protected]>
[Tormod: Refactored to reduce duplicated code]
Signed-off-by: Tormod Volden <[email protected]>
2021-11-07 12:58:15 +01:00
Tormod Volden 3178abb790 Windows: Ignore any device interface GUIDs beyond the first
The NZXT Kraken Z73 device has been reported to brokenly have two
identical device interface GUIDs registered. Accept such cases by
treating the ERROR_MORE_DATA return value as success and processing the
first returned GUID as if it would be the only one.

If one day we see legitimate cases of multiple GUIDs we will need to
deal with them properly.

References jdkvision/libusb#1
Closes #1010

Signed-off-by: Tormod Volden <[email protected]>
2021-11-07 12:48:27 +01:00
Evan Miller 8fa0582438 darwin: Fix compilation on macOS 10.9 and earlier
kUSBReEnumerateCaptureDeviceMask was introduced in the 10.10 SDK, so
compiling on 10.9 and earlier will fail with:

 os/darwin_usb.c: In function 'darwin_reenumerate_device':
 os/darwin_usb.c:1749:18: error: 'kUSBReEnumerateCaptureDeviceMask' undeclared (first use in this function); did you mean 'USBReEnumerateOptions'?
        options |= kUSBReEnumerateCaptureDeviceMask;
                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                   USBReEnumerateOptions
 os/darwin_usb.c:1749:18: note: each undeclared identifier is reported only once for each function it appears in

Downstream report: https://trac.macports.org/ticket/63668

Closes #1023
2021-11-07 11:38:03 +01:00
Peter-St f33c9562a1 examples: Add example for unrooted Android
Closes #830
2021-11-02 00:20:26 +01:00
Tormod Volden 78eb865b31 descriptor: Provide more detailed warning if suspicious bLength
Signed-off-by: Tormod Volden <[email protected]>
2021-11-01 23:40:44 +01:00
Tormod Volden 1d1411b606 doc: Explain default options in libusb_set_option documentation
References #942

Signed-off-by: Tormod Volden <[email protected]>
2021-11-01 23:22:56 +01:00
Bruno Harbulot f7084fea11 core: Apply default options to all new contexts
The default options configured with libusb_set_option(NULL, ...)
were only applied when the default context was created, and were
ignored when calling libusb_init() with a non-null context pointer.

Make sure the default options will be applied to all new contexts. This
is important when using LIBUSB_OPTION_NO_DEVICE_DISCOVERY which must
be respected during the context initialization in order to work.

Closes #942

[Tormod: amend comments]
Signed-off-by: Tormod Volden <[email protected]>
2021-11-01 23:20:59 +01:00
Tormod Volden b88f144185 xusb: Print total length of configuration descriptor
Signed-off-by: Tormod Volden <[email protected]>
2021-10-31 18:32:25 +01:00
luz paz 14d3bde10f Fix various typos in docs/comments
Found via `codespell -q 3`

Closes #1015
2021-10-31 17:44:55 +01:00
Tormod Volden 6992d9bd4f xusb: Print configuration descriptor length
Also inform about reading OS string descriptor.

Signed-off-by: Tormod Volden <[email protected]>
2021-10-31 09:12:48 +01:00
Sean McBride edd1a4bfe4 darwin: After last CFRelease of struct field, set it to NULL
Other code checks this field for being NULL or not, so NULLing it upon
last release seems the right thing to do.  I noticed this during code
review, I never actually reproduced any problem.

Closes #981
2021-10-30 15:23:45 +02:00
Sean McBride 35b23a047e doc: Improve comments related to device discovery and hotplug
Closes #1013
2021-10-30 15:23:15 +02:00
Tormod Volden 762456139a doc: Update note about LIBUSB_TRANSFER_ADD_ZERO_PACKET availability
Closes #1005

Signed-off-by: Tormod Volden <[email protected]>
2021-10-30 15:22:31 +02:00
Paul Cercueil 619c28f37e Windows: Fix ssize_t unconditionally defined
The standard procedure to define ssize_t on Windows is to wrap it around
a check for the _SSIZE_T_DEFINED macro.

If not done, it makes it impossible to use the libusb.h header along
with other headers (from other libraries) that also attempt to define
ssize_t.

Closes #1007

Signed-off-by: Paul Cercueil <[email protected]>
2021-10-30 15:21:56 +02:00
Bohdan Tymkiv a584d060c8 Windows: Partial fix for data race in composite_copy_transfer_data
This only fixes issue (A):
libusb: error [composite_copy_transfer_data] program assertion failed - no function to copy transfer data

References #966
Closes #967
2021-10-30 15:20:35 +02:00
Nathan Hjelm 8d7616886e darwin: fix deprecation warning about kIOMasterPortDefault
The kIOMasterPortDefault constant has been replaced by kIOMainPortDefault. Both
are synonmys for 0. To avoid extra checks on the target macOS release just go
ahead and use 0.

Signed-off-by: Nathan Hjelm <[email protected]>
2021-10-28 10:36:30 -06:00
Nathan Hjelm 4f6754f3c6 darwin: add support for handling new error code (kUSBHostReturnPipeStalled)
With macOS Monterey Apple started using a new error code to indicate a pipe
stall. This new error code needs to be handled both in translation to libusb
error codes and when handling errors setting the alt setting.

References #1011

Signed-off-by: Nathan Hjelm <[email protected]>
2021-10-28 10:25:03 -06:00
Tormod Volden e88b77ff6e git hooks: Remove "source" bashism
"source" is not supported in Bourne shell

Closes #997

Signed-off-by: Tormod Volden <[email protected]>
2021-09-23 10:52:11 +02:00
Peter-St 35b3a52188 Update Android Readme
Add another approach for connecting USB devices on Android.

References #830
Closes #996
2021-09-23 10:52:11 +02:00
Ankur Verma 6929b82701 Fix segmentation fault in libusb_init() if usbi_backend.init() fails
If the backend init fails, the control goes to err_io_exit which tries
to clean up hotplug related lists that aren't initialized. Moving
hotplug_init before makes sure the lists are valid so if backend init
fails they get cleaned up without errors.

Closes #989
2021-09-23 10:52:11 +02:00
Sean McBride 7d7733a377 Fix comment typos
References #981
2021-09-23 10:52:11 +02:00