platform/upstream/libusb.git
3 years agoDocumentation: Add section regarding transfer length limitations
Chris Dickens [Tue, 18 Aug 2020 17:14:50 +0000 (10:14 -0700)]
Documentation: Add section regarding transfer length limitations

Closes #204

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agoWindows: Update INSTALL_WIN.txt
Chris Dickens [Tue, 18 Aug 2020 17:07:46 +0000 (10:07 -0700)]
Windows: Update INSTALL_WIN.txt

Add info regarding where the 'INSTALL' file comes from.

Remove link for Windows SDKs as this is no longer relevant.

Update to account for Visual Studio 2019.

Closes #235

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agoAutotools: Use built-in shell tests and exec autoreconf
Chris Dickens [Tue, 18 Aug 2020 16:28:27 +0000 (09:28 -0700)]
Autotools: Use built-in shell tests and exec autoreconf

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agoWindows: Fix I/O completion port thread behavior on error
Chris Dickens [Tue, 18 Aug 2020 16:19:03 +0000 (09:19 -0700)]
Windows: Fix I/O completion port thread behavior on error

The GetQueuedCompletionStatus() returns FALSE when the I/O operation
itself does not complete successfully. The I/O completion thread should
therefore not exit on this condition. Adjust the check to verify that an
OVERLAPPED structure was provided and use an explicit completion key
value in the exit path to disambiguate receiving a valid NULL OVERLAPPED
pointer.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agoWindows: Improve how root hubs are reported
Chris Dickens [Mon, 17 Aug 2020 21:15:10 +0000 (14:15 -0700)]
Windows: Improve how root hubs are reported

Microsoft provides very little information about the actual root hub
characterstics beyond the number of ports. Determining the maximum
supported speed of the root hub is not directly possible but instead
requires that a device matching the highest speed of the root hub is
connected. Additionally, Windows 8 or later is required for _any_
successful detection of SuperSpeed devices.

One other inconvenience is that there are no descriptors exposed for
root hubs. This does not fit well with the structure of the library
because root hubs are considered first-class devices.

This change addresses some of these shortcomings. Each root hub is now
given a configuration descriptor that is matched to the fastest speed
detected for the root hub. The information is most accurate on Windows 8
or later, but the best information possible is constructed on earlier
versions. The device descriptor is also adjusted accordingly based on
the detected speed.

This solution is not perfect but is better than the status quo.

Closes #688

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agoWindows: Prevent NULL pointer dereference when ancestor is missing
Chris Dickens [Mon, 17 Aug 2020 15:40:33 +0000 (08:40 -0700)]
Windows: Prevent NULL pointer dereference when ancestor is missing

A buggy virtual USB device driver can cause the device enumeration
process to fail during the init_device() function when trying to
determine the bus number of the device. Guard against this by checking
that the ancestor device was actually found and skipping the bogus
device when there is no ancestor.

Closes #491

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agodescriptor: Miscellaneous improvements to the overall source
Chris Dickens [Thu, 13 Aug 2020 17:31:51 +0000 (10:31 -0700)]
descriptor: Miscellaneous improvements to the overall source

Introduce union types that simplify working with descriptors. Previously
there were simple arrays declared on the stack and these were either
parsed into the target descriptor structure or were accessed with magic
offsets into the array. Using the union type allows the descriptors to
be read with the need to parse it into a separate structure.

Fix a memory leak that would occur in the interface parsing code if the
usbi_reallocf() function failed. Each interface has a separately
allocated array of endpoints and potential extra descriptors. These
cannot be freed when using usbi_reallocf(), so switch to use realloc().

Fix an obscure limitation where extra descriptors would not be appended
to the configuration is any previous extra descriptors had already been
found.

Make the error checking and error messages consistent across all the
parsing functions. This includes printing unknown or unexpected
descriptor types in hex format, which is often easier to lookup as most
specifications use hex notation.

Constify the input buffer argument to the parsing functions.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agocore: Optimize check for pending events
Chris Dickens [Thu, 13 Aug 2020 05:34:03 +0000 (22:34 -0700)]
core: Optimize check for pending events

Prior to this commit, a check for whether any events are pending
involved checking four different variables within the context. Optimize
this by using multiple bits within a single unsigned integer to
represent all the possible events that could be pending. This reduces
the check for whether any events are pending to a single load.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agocore: Add support for eventfd
Chris Dickens [Thu, 13 Aug 2020 01:44:31 +0000 (18:44 -0700)]
core: Add support for eventfd

On systems that support it, using an eventfd for simple signalling is
much more efficient than using a pipe. Add detection of eventfd to the
configure script and wire it up in the POSIX event abstraction.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agocore: Introduce platform events abstraction
Chris Dickens [Wed, 12 Aug 2020 23:06:38 +0000 (16:06 -0700)]
core: Introduce platform events abstraction

The way in which system handles or resources are represented differs
greatly between Unix-like operating systems and Windows. Ever since
Windows support was added to libusb, Windows been emulating principles
of Unix-like operating systems such as file descriptors and poll().

This commit introduces an abstraction layer that completely removes the
need to perform any emulation. Fundamentally there are three things that
each platform provides to libusb:

  1) A signallable event
  2) A timer (not required, but useful)
  3) A means to wait for event sources such as the above to be triggered

The POSIX abstraction for Unix-like operating systems uses file
descriptors as the "handles" to the underlying system resources. The
signallable event is implemented using a pipe, the timer as a timerfd
(where supported) and the poll() system call is used to wait for events.

The Windows abstraction uses native HANDLEs as the "handles" to the
underlying system resources. The signallable event is implemented using
a manual-reset event, the timer as a manual-reset waitable timer, and
the WaitForMultipleObjects() system call is used to wait for events.

Closes #252

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agoWindows: Use I/O completion ports for transfers
Chris Dickens [Tue, 11 Aug 2020 02:19:21 +0000 (19:19 -0700)]
Windows: Use I/O completion ports for transfers

As a first step in removing the Windows poll() emulation, switch the
transfers to use an I/O completion port. A dedicated per-context thread
will wait on the I/O completion port and report transfer completions
using usbi_signal_transfer_completion(). This enables the complete
removal of the handle_events() function for the Windows backend and
removes the notion of one "file descriptor" per transfer.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agocore: Introduce list iteration helpers
Chris Dickens [Tue, 11 Aug 2020 02:01:42 +0000 (19:01 -0700)]
core: Introduce list iteration helpers

The syntax for traversing over lists is somewhat cluttered. It could be
made much better with the use of the 'typeof' keyword, but unfortunately
this is not universally supported by all compilers. We can, however,
improve the situation by introducing some macros for the common cases.
To that end, this commit introduces a number of 'for_each' macros that
iterate over a specific linked list.

Current syntax:

  list_for_each_entry(itransfer, &ctx->flying_transfers, list, struct usbi_transfer)

New syntax:

  for_each_transfer(ctx, itransfer)

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agoOpenBSD: support libusb_get_port_number
Theo Buehler [Wed, 5 Aug 2020 13:53:14 +0000 (15:53 +0200)]
OpenBSD: support libusb_get_port_number

From mpi@openbsd.org

Fixes #314
Closes #764

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agoOpenBSD: allow opening ugen devices multiple times
Theo Buehler [Wed, 5 Aug 2020 13:23:45 +0000 (15:23 +0200)]
OpenBSD: allow opening ugen devices multiple times

Fix an OpenBSD backend bug where an existing open file descriptor is
overwritten if a libusb user attempts to open the same ugen(4) device
multiple times. This was observed with sane-backends and broke scanning.

Fix from stsp@openbsd.org

Closes #763

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agoAPI docs: Elaborate on "NOT_SUPPORTED" status for set_configuration()
Martin Thierer [Sun, 2 Aug 2020 13:08:31 +0000 (15:08 +0200)]
API docs: Elaborate on "NOT_SUPPORTED" status for set_configuration()

Closes #762

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agolibusb: fix a memory leak in sunos_new_string_list func
Zhiqiang Liu [Mon, 27 Jul 2020 09:46:01 +0000 (17:46 +0800)]
libusb: fix a memory leak in sunos_new_string_list func

In sunos_new_string_list func, if alloc list->string fails,
we will return NULL without free list, which has alread been
allocated successfully.

Fixes: 17348731b4 ('Solaris backend depends on Solaris private symbols')

Closes #756

Signed-off-by: Zhiqiang Liu <lzhq28@mail.ustc.edu.cn>
Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agostress: test_get_device_list: change printf format for ssize_t
Uri Lublin [Sun, 5 Jul 2020 13:29:57 +0000 (16:29 +0300)]
stress: test_get_device_list: change printf format for ssize_t

The type of list_size is ssize_t.
First idea was to use "%zd" printf format specifier.
But that is not supported by Visual Studio 2013.

Use "%ld" + cast list_size to long.

Closes #751

Suggested-by: Chris Dickens <christopher.a.dickens@gmail.com>
Signed-off-by: Uri Lublin <uril@redhat.com>
Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agodescriptor: Fix alignment for 32-bit words in parse_descriptor
Saleem Rashid [Thu, 21 May 2020 17:12:04 +0000 (18:12 +0100)]
descriptor: Fix alignment for 32-bit words in parse_descriptor

parse_descriptor was aligning 32-bit words to 2 bytes, instead of 4
bytes. This didn't cause any issues before, because the only time the
32-bit word code path is used is from a 3 byte offset (which
incidentally aligns to 4 bytes). However, a 1 byte offset would
incorrectly align to 2 bytes.

Closes #734

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agowinusb: setting a non-default config not supported
Martin Thierer [Wed, 8 Jul 2020 18:47:57 +0000 (20:47 +0200)]
winusb: setting a non-default config not supported

Just because winusb doesn't seem to support setting a different
configuration, that doesn't mean it's an invalid parameter.

It's generally supported by libusb, just not on this platform.

So return LIBUSB_ERROR_NOT_SUPPORTED instead of
LIBUSB_ERROR_INVALID_PARAM.

Closes #743
Closes #752

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agodarwin: Fix invalid GetPipePropertiesV3 argument
Ido Yariv [Wed, 17 Jun 2020 03:22:31 +0000 (23:22 -0400)]
darwin: Fix invalid GetPipePropertiesV3 argument

GetPipePropertiesV3 seems to require that the bVersion field of the
properties argument be set before calling it:
"Version of the structure. Currently kUSBEndpointPropertiesVersion3.
Need to set this when using this structure"

Not doing so results in an invalid argument error.

Closes #744

Signed-off-by: Ido Yariv <ido@wizery.com>
Signed-off-by: Nathan Hjelm <hjelmn@google.com>
3 years agoos/darwin: use IOUSBDevice as darwin_device_class explicitly
Igor Anokhin [Wed, 15 Apr 2020 10:47:51 +0000 (13:47 +0300)]
os/darwin: use IOUSBDevice as darwin_device_class explicitly

kIOUSBDeviceClassName define from IOUSBLib.h file was changed from
IOUSBDevice to IOUSBHostDevice in macOS Catalina.

In previous macOS versions, it was always defined as IOUSBDevice:
```
 #define kIOUSBDeviceClassName  "IOUSBDevice"
```
In macOS Catalina it looks as follows:
```
 #if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_14
 #define kIOUSBDeviceClassName           "IOUSBDevice"
 #define kIOUSBInterfaceClassName        "IOUSBInterface"
 #else
 #define kIOUSBDeviceClassName           kIOUSBHostDeviceClassName
 #define kIOUSBInterfaceClassName        kIOUSBHostInterfaceClassName
 #endif /* MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_14 */
```

By default, macOS Catalina uses IOUSBHostDevice. The problem is that
using the IOUSBHostDevice class misses some devices.  This has been
described in 044a7ee commit. To work only with IOUSBDevice,
darwin_device_class has been explicitly set to IOUSBDevice.

Closes #693

For reference, here's the output of the 'listdevs' example before my changes:
05ac:027b (bus 128, device 2) path: 5
2109:0102 (bus 20, device 6) path: 4
05e3:0751 (bus 20, device 5) path: 1
1a40:0801 (bus 20, device 3) path: 2
0bda:8153 (bus 0, device 2) path: 3
2109:2817 (bus 20, device 1) path: 8
2109:0817 (bus 0, device 1) path: 4

And here's the output after my changes:
05ac:027b (bus 128, device 2) path: 5
2109:0102 (bus 20, device 6) path: 3.2.4
05e3:0751 (bus 20, device 5) path: 3.2.1
1a40:0801 (bus 20, device 3) path: 3.2
0bda:8153 (bus 0, device 2) path: 2.3
2109:2817 (bus 20, device 1) path: 3
2109:0817 (bus 0, device 1) path: 2

Closes #712

Signed-off-by: Nathan Hjelm <hjelmn@google.com>
3 years agodarwin: use GetPipePropertiesV3 on 10.9 and later
Nathan Hjelm [Fri, 12 Jun 2020 05:31:36 +0000 (23:31 -0600)]
darwin: use GetPipePropertiesV3 on 10.9 and later

Apple added the GetPipePropertiesV3 in IOUSBFamily version 550. The old
function appears to be deprecated. When 10.8.x and older are no longer
supported the GetPipeProperties call should be removed.

Signed-off-by: Nathan Hjelm <hjelmn@google.com>
3 years agodarwin: add kIOUSBUnknownPipeErr to error string list
Nathan Hjelm [Fri, 12 Jun 2020 05:30:48 +0000 (23:30 -0600)]
darwin: add kIOUSBUnknownPipeErr to error string list

Signed-off-by: Nathan Hjelm <hjelmn@google.com>
3 years agoDocument that libusb_set_option may also return NOT_FOUND
Jonas Malaco [Fri, 22 May 2020 09:36:58 +0000 (06:36 -0300)]
Document that libusb_set_option may also return NOT_FOUND

If the platform is Windows but UsbDk is not available libusb_set_option
returns LIBUSB_ERROR_NOT_FOUND.[1] Adjust the documentation to reflect that.

[1] https://github.com/libusb/libusb/blob/26611eaa494ed9e077b5b0e1f999f5ae377de958/libusb/os/windows_common.c#L570-L578

Closes #735

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
3 years agodarwin: Fix stale descriptor information post reset
Ido Yariv [Wed, 20 May 2020 20:23:11 +0000 (16:23 -0400)]
darwin: Fix stale descriptor information post reset

As part of the recent removal of the backend get_device_descriptor()
function, the darwin backend was modified to update the cached
device_descriptor when a new device is processed. However, this wasn't
done for cases where the device is reused rather than allocated.
This could potentially result in getting stale data when using the
device following a reset.

In addition, when the device is reused, its session ID should be kept
up-to-date in the cached devices list, so it could be found in subsequent
resets.

Closes #733

Signed-off-by: Ido Yariv <ido@wizery.com>
Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoWindows: Translate ERROR_NO_SUCH_DEVICE to LIBUSB_TRANSFER_NO_DEVICE
Sebastian von Ohr [Tue, 28 Apr 2020 14:28:27 +0000 (16:28 +0200)]
Windows: Translate ERROR_NO_SUCH_DEVICE to LIBUSB_TRANSFER_NO_DEVICE

Windows SDK 10.0.18362.0 adds a new error code ERROR_NO_SUCH_DEVICE
which is returned when the device is disconnected.

Closes #721, Closes #722

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolinux_usbfs: Parse config descriptors during device initialization
Chris Dickens [Wed, 29 Apr 2020 19:39:35 +0000 (12:39 -0700)]
linux_usbfs: Parse config descriptors during device initialization

Do the work ahead of time and cache the results so that fetching config
descriptors becomes a trivial operation.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Narrow the types passed to certain backend functions
Chris Dickens [Wed, 29 Apr 2020 05:04:11 +0000 (22:04 -0700)]
core: Narrow the types passed to certain backend functions

Backend functions dealing with interfaces and alternate settings should
use a type whose range represents that of valid values for interfaces
and alternate settings. Switch to use uint8_t instead of int so that
backends do not have to cast values or do range checks.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agosunos: Fix a number of compiler warnings
Chris Dickens [Tue, 28 Apr 2020 19:36:29 +0000 (12:36 -0700)]
sunos: Fix a number of compiler warnings

  * [-Wdiscarded-qualifiers] assignment discards 'const' qualifier from pointer target type
  * [-Wpointer-sign] pointer targets in passing argument N of 'func' differ in signedness
  * [-Wsign-compare] comparision between signed and unsigned integer expressions
  * [-Wunused-function] 'func' declared 'static' but never defined
  * [-Wunused-parameter] unused parameter 'p'

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoFix some trivial compiler warnings for the Haiku and BSD backends
Chris Dickens [Tue, 28 Apr 2020 19:24:59 +0000 (12:24 -0700)]
Fix some trivial compiler warnings for the Haiku and BSD backends

  * [-Wformat=] format 'S' expects argument of type 'T1', but argument N has type 'T2'
  * [-Wmissing-declarations] no previous declaration for 'func'
  * [-Wreorder] 'Class::Member' will be initialized after
  * [-Wsign-compare] comparison between signed and unsigned integer expressions
  * [-Wunused-but-set-variable] variable 'v' set but not used
  * [-Wunused-parameter] unused parameter 'p'

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agodescriptor: Remove usbi_get_config_index_by_value()
Chris Dickens [Tue, 28 Apr 2020 19:17:50 +0000 (12:17 -0700)]
descriptor: Remove usbi_get_config_index_by_value()

Only one caller of this function exists and it lives in the descriptor
source code. Remove the function and merge it into the function that
calls it.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Kill backend get_device_descriptor() function
Chris Dickens [Tue, 28 Apr 2020 19:08:08 +0000 (12:08 -0700)]
core: Kill backend get_device_descriptor() function

Simplify the library by moving device descriptor initialization to the
backend, while the device is being set up. This removes the duplication
of essentially the same code in every backend.

Add some missing calls to libusb_le16_to_cpu() when reading multi-byte
fields from the "raw" device descriptor. It has worked thus far because
the platforms not using the calls happen to be the same endianness as
the USB bus.

While here, throw in some static assertions to ensure there is no
mismatch between the libusb device descriptor structure and any
device descriptor structure provided by the platform headers.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Fix some minor inconsistencies in API and coding
Chris Dickens [Tue, 28 Apr 2020 01:43:42 +0000 (18:43 -0700)]
core: Fix some minor inconsistencies in API and coding

All of the API functions should take the typedef'ed versions of the
opaque libusb structures, but some recent additions to the API did not
follow this convention. Fix this by making the changes to the
declarations and definitions of the functions.

Make the placement of the asterisk in pointer variable declarations
consistent (always with the variable name, not the type).

Remove some unnecessary casts and initializations relating to
dynamically allocated memory. While at it, make casts within the core
library consistent in style with no space after the closing parenthesis
of the cast. Most of the core already used this style.

When using the 'sizeof' operator, dereference the pointer instead of
using the type.  Most of the core was already doing this, so fix up the
few places that weren't.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Change pointer type from 'unsigned char' to 'void'
Chris Dickens [Fri, 17 Apr 2020 21:21:44 +0000 (14:21 -0700)]
core: Change pointer type from 'unsigned char' to 'void'

This removes the need for pointer casts when calling backend functions.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agodescriptor: Minor improvements to the parse_descriptor() function
Chris Dickens [Fri, 17 Apr 2020 20:22:34 +0000 (13:22 -0700)]
descriptor: Minor improvements to the parse_descriptor() function

Change the type of the source pointer to 'void' so that callers need not
cast to 'unsigned char'. Also change working types to 'uint8_t' to make
it explicit that we are dealing with 8-bit types.

Refactor the parsing loop to avoid unnecessary stack variables. The
generated assembly with this change is more efficient.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Kill the 'host_endian' argument for most functions
Chris Dickens [Fri, 17 Apr 2020 19:57:49 +0000 (12:57 -0700)]
core: Kill the 'host_endian' argument for most functions

The 'host_endian' argument exists only for a special case in the Linux
backend, that being when the device descriptor is read using usbfs
rather than sysfs. It does not apply to any other descriptor types nor
any other backends, so remove it.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Remove redundant definitions for descriptor sizes
Chris Dickens [Fri, 17 Apr 2020 19:21:46 +0000 (12:21 -0700)]
core: Remove redundant definitions for descriptor sizes

The public libusb header provides all the definitions for the various
descriptor sizes, so use them instead of defining them again with
different names.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Remove usbi_parse_descriptor() function
Chris Dickens [Fri, 17 Apr 2020 19:07:38 +0000 (12:07 -0700)]
core: Remove usbi_parse_descriptor() function

The Linux backend was the only caller of this function, but with the
packed structures introduced in commit d06cc52851 its use is no longer
necessary. Convert the function to static and remove the return type as
no callers paid attention to it.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agodescriptor: Optimize descriptor parsing
Chris Dickens [Fri, 17 Apr 2020 18:43:54 +0000 (11:43 -0700)]
descriptor: Optimize descriptor parsing

While iterating over descriptors, we can simplify and speed up the
process by looking at the descriptor header directly rather than calling
the parse function each time.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoAdd packed definitions for some standard USB descriptor types
Chris Dickens [Fri, 17 Apr 2020 18:31:55 +0000 (11:31 -0700)]
Add packed definitions for some standard USB descriptor types

These are going to be used in future commits to cleanup some code. Note
that these are prefixed as 'usbi' rather than 'usb' to avoid conflicts
with definitions provided by some system headers.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agohotplug: Fix definition of libusb_hotplug_register_callback()
Chris Dickens [Thu, 16 Apr 2020 23:47:01 +0000 (16:47 -0700)]
hotplug: Fix definition of libusb_hotplug_register_callback()

The signature of the libusb_hotplug_register_callback() is slightly
incorrect in two regards:

  1) The 'events' parameter is meant to represent a bitwise OR of
     libusb_hotplug_event values. By OR'ing multiple values together,
     the result is not something that is actually a libusb_hotplug_event
     enumeration.

  2) The 'flags' parameter is meant to represent a bitwise OR of
     libusb_hotplug_flag values. The same considerations as above apply,
     though this has not practically been the case as there is currently
     only one flag value defined. However, a special value was already
     defined to represent the absence of any flags, which hinted at the
     problem with how it is currently defined.

Address these two issues by changing the types of the 'events' and
'flags' parameter to plain integers. As enumerations should already be
promoted to integers, this change should not cause any ABI concerns.

Closes #714

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoAdd vcpkg installation instructions
NancyLi1013 [Fri, 17 Apr 2020 08:52:28 +0000 (01:52 -0700)]
Add vcpkg installation instructions

Closes #708, Closes #715

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoAndroid: fixes unknown warning option from ndk build
Aaron Luft [Fri, 17 Apr 2020 15:30:12 +0000 (11:30 -0400)]
Android: fixes unknown warning option from ndk build

A command line option is not correct.
Fix by spelling the option correctly.

BEFORE

[x86] Compile        : xusb <= xusb.c
warning: unknown warning option '-Werror=unintialized'; did you mean '-Werror=uninitialized'? [-Wunknown-warning-option]

AFTER

[x86] Compile        : xusb <= xusb.c
[x86] Executable     : xusb
[x86] Install        : xusb => libs/x86/xusb

4 years agoAdd a way to skip the git hooks via an environment variable
Chris Dickens [Fri, 17 Apr 2020 00:10:39 +0000 (17:10 -0700)]
Add a way to skip the git hooks via an environment variable

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolibusb.h: Ensure that struct libusb_control_transfer is not padded
Chris Dickens [Thu, 16 Apr 2020 22:57:15 +0000 (15:57 -0700)]
libusb.h: Ensure that struct libusb_control_transfer is not padded

There is nothing explicitly preventing the compiler from adding any sort
of padding to the libusb_control_transfer structure. It does not seem
that any sane compiler would do so, but there is library functionality
that depends on this not happening. Address this by explicitly
instructing the compiler to pack the structure.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolibusb.h: Simplify condition governing the inclusion of sys/time.h
Chris Dickens [Thu, 16 Apr 2020 21:31:18 +0000 (14:31 -0700)]
libusb.h: Simplify condition governing the inclusion of sys/time.h

The expression for the condition grows each time a new backend is added,
but it can be simplified if changed to key off of the _MSC_VER macro.
The sys/time.h header is ubiquitous across all platforms and build
environments except Visual Studio, so change the condition to be based
on this. This fixes builds on BSD where the condition was not evaluating
to true.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolibusb.h: Make C-preprocessor checks consistent and safe
Chris Dickens [Thu, 16 Apr 2020 21:26:42 +0000 (14:26 -0700)]
libusb.h: Make C-preprocessor checks consistent and safe

Instead of mixing 'ifdef' with 'if defined(...)', use the latter
everywhere.

Check whether the __GNUC__ macro is defined before using it to avoid
compiler warnings.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolibusb.h: Make formatting and style consistent across the whole file
Chris Dickens [Thu, 16 Apr 2020 20:54:17 +0000 (13:54 -0700)]
libusb.h: Make formatting and style consistent across the whole file

  * Define USB spec. definitions as hexadecimal values
  * Define bitmask values using a shift operation
  * Fix Doxygen for enum libusb_log_level
  * Fix some broken/missing whitespace
  * Give explicit values to all enumerations
  * Remove trailing comma from all enumerations

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolibusb.h: Move BOS descriptor enumerations
Chris Dickens [Thu, 16 Apr 2020 19:40:49 +0000 (12:40 -0700)]
libusb.h: Move BOS descriptor enumerations

The location of the enumerations for the various bits in the BOS
descriptors is not consistent with the other enumerations, so move it up
to group it with the rest. In addition, fix the Doxygen documentation to
put these in the descriptors group rather than the devices group.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Fix definition and use of enum libusb_transfer_type
Chris Dickens [Thu, 16 Apr 2020 19:20:16 +0000 (12:20 -0700)]
core: Fix definition and use of enum libusb_transfer_type

Since the beginning of the libusb-1.0, the libusb_transfer_type enum had
a 1:1 mapping to the endpoint transfer type (bits 1:0 of the endpoint
descriptor's bmAttributes). This was broken with the addition of bulk
stream support because the value of LIBUSB_TRANSFER_TYPE_BULK_STREAM
does not map to a valid value for an endpoint's transfer type.

Fix this by splitting the endpoint's transfer type for its descriptor
and the library's transfer type for its logical transfers into different
enumerations. None of the values are altered, so applications testing
an endpoint descriptor's bmAttributes field against the
libusb_transfer_type enum values will still work.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agonetbsd: Recognize device timeouts.
nia [Fri, 3 Apr 2020 21:15:02 +0000 (22:15 +0100)]
netbsd: Recognize device timeouts.

Closes #710

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoMakefiles: Remove target-specific variables
Chris Dickens [Thu, 9 Apr 2020 19:30:57 +0000 (12:30 -0700)]
Makefiles: Remove target-specific variables

Improve portability with non-GNU make by using standard variables.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoconfigure.ac: Enhance compiler checks for pthreads
Chris Dickens [Thu, 9 Apr 2020 19:05:16 +0000 (12:05 -0700)]
configure.ac: Enhance compiler checks for pthreads

There apparently exist some compiler ports (e.g Haiku's GCC) that do not
support the ubiquitous '-pthread' compiler option. Add a check for this
and only use the option if supported.

Also tweak the check for the pthread library to check for the
pthread_create() function. Even though libusb does not use this function,
it seems to be sufficiently distinct such that the standard C library
would not provide this directly if the pthread implementation resided in
a separate library. Also explicitly check whether no additional library
linkage is required.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoconfigure.ac: Simplify detection of Windows compilation
Chris Dickens [Thu, 9 Apr 2020 18:46:03 +0000 (11:46 -0700)]
configure.ac: Simplify detection of Windows compilation

There are a few parts within the library where code is conditionally
compiled based on whether or not the target OS is Windows. Prior to
commit 8b09dd490d ("core: Kill the OS_* definitions and use in the
source code"), the OS_WINDOWS definition was used. With that definition
gone, the checks were replaced with _WIN32. Unfortunately the different
cross-platform toolchains do not universally define this, so add this to
AM_CPPFLAGS when building for Windows.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoconfigure.ac: Fix compilation of Haiku's C++ convenience library
Chris Dickens [Thu, 9 Apr 2020 18:30:19 +0000 (11:30 -0700)]
configure.ac: Fix compilation of Haiku's C++ convenience library

Commit 9a1bc8cafb ("build: Require C11 to build and clean up
autoconfig/automake files") added the language standard compiler option
to the AM_CFLAGS and AM_CXXFLAGS. Placing it in the latter is incorrect
as compiling C++ source with the C11 language standard does not make
sense.

Fix this by determining which C11 dialect (GNU or C) the compiler
supports and then constructing the compiler option from that.

Also restrict LT_LDFLAGS to the final libusb library (as was done
previously) since libtool complains about versioning options for
convenience libraries.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoautomake: Add extra Makefile to handle unknown automake targets
Chris Dickens [Thu, 2 Apr 2020 03:54:09 +0000 (20:54 -0700)]
automake: Add extra Makefile to handle unknown automake targets

Automake does not know how to compile Windows Resource files, so we have
manually told automake how to do this. One particular short-coming is
that dependencies are not automatically generated and tracked as they
are with other known automake targets. Address this by creating an extra
makefile that contains the automake rules needed for building source for
Windows targets. This also includes outputting more accurate tags during
compilation instead of using the generic "GEN" tag.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoWindows: Improve the get_interface_details_filter() function
Chris Dickens [Wed, 1 Apr 2020 02:57:28 +0000 (19:57 -0700)]
Windows: Improve the get_interface_details_filter() function

The sole caller of this function only cares about the device interface
path, so change the calling convention to be like that of the
get_interface_details() function. This also adds more precise error
reporting.

Since this function is specific to the libusb0 filter driver, do not
require the caller to provide the GUID for the libusb0 filter driver.

Remove the use of strtok() on the result of this function. The strtok()
function is not reentrant and is less-than-optimal for locating the
start of the GUID component in the device interface path.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoWindows: Replace the sanitize_path() function with normalize_path()
Chris Dickens [Wed, 1 Apr 2020 01:23:43 +0000 (18:23 -0700)]
Windows: Replace the sanitize_path() function with normalize_path()

Once upon a time the sanitize_path() function was needed to generate a
consistent path format in order to hash the resulting string for use as
session IDs. Since commit 71a779d078 ("Windows: Rework WinUSB
enumeration process to fix issues on Win8+"), this hashing method is no
longer used for session IDs, thus the sanitize_path() function was no
longer explicitly needed.

User lo1ol also reports in issue #633 that the function actually causes
issues with devices where there is a path component following the device
interface GUID. Rather than patching the function to fix this specific
behavior, just replace it with a simpler function that returns an
uppercased duplicate of the input string.

Closes #633, Closes #662

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoMove CI-related files into .private directory and add unified build script
Chris Dickens [Tue, 31 Mar 2020 22:47:31 +0000 (15:47 -0700)]
Move CI-related files into .private directory and add unified build script

The files needed for Continuous Integration (AppVeyor, Travis) are not
meant for public consumption, so clean up the root directory by moving
these files underneath .private.

Create a single build script that is leveraged by both AppVeyor and
Travis. This script replaces the previous 'travis-autogen.sh' file and
enables additional compiler warnings that should provide additional
coverage for all build environments.

Update the Travis configuration file to absorb the Brewfile and update
the Xcode images. Per warnings from Travis, Xcode6.4 is obsolete, thus
replace it with Xcode7.3. Additionally remove the "gcc" variants for the
macOS builds. The builds never used gcc to begin with and actually using
gcc causes build errors due to Clang-specific pragmas in the IOKit
header files.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoXcode: Update project file
Chris Dickens [Mon, 30 Mar 2020 23:53:43 +0000 (16:53 -0700)]
Xcode: Update project file

Add '-fvisibility=hidden' to the additional compiler flags of the libusb
target so that internal library symbols are hidden.

Add '-pthread' to the additional compiler flags of the targets that
directly use pthread functionality

Add the 'sam3u_benchmark' and 'testlibusb' targets so that all examples
are now built and fix build warnings that occur when building
'sam3u_benchmark'.

Fix target dependencies so that all targets are able to build without
issues.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoandroid: Update makefiles to include recent autobuild changes
Chris Dickens [Mon, 30 Mar 2020 20:21:04 +0000 (13:21 -0700)]
android: Update makefiles to include recent autobuild changes

Add C11, thread and visibility compiler flags. Enable additional
warnings and errors. Unify spacing amongst the makefiles.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agobuild: Enable additional build errors and warnings
Chris Dickens [Mon, 30 Mar 2020 19:38:47 +0000 (12:38 -0700)]
build: Enable additional build errors and warnings

Help catch more errors by enabling additional build errors and warnings.
Address some of the warnings seen with these new flags, including moving
the libusb_transfer structure back out of the usbi_transfer structure to
address 'warning: invalid use of structure with flexible array member'.
Apparently a structure ending with a flexible array member is not okay
with the compiler as the last member within another structure.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agobuild: Require C11 to build and clean up autoconfig/automake files
Chris Dickens [Mon, 30 Mar 2020 19:28:11 +0000 (12:28 -0700)]
build: Require C11 to build and clean up autoconfig/automake files

C11 compiler support has been available for many years now. It is not
unreasonable to require this now, and doing so allows some cleanup to
the configure script. It is no longer necessary to check for compiler
support of the '-fvibility' flag because any compiler that supports C11
will support this flag as well.

Fix up the way that compiler and linker flags are passed down to the
various makefiles. The compiler flags should be shared by all, but the
linker flags and libraries should be separated between the library and
the examples/tests. The visibility flag is only relevant for the
library and the thread flags are only relevant for sources using thread
constructs, so provide them as needed.

Rearrange configure.ac to group similar functionality and consolidate
where possible.

Based on these changes, update the Travis configuration file to include
newer versions of test platforms to ensure proper C11 compiler support.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolibusb/Makefile.am: Remove unnecessary assignments
Chris Dickens [Sat, 28 Mar 2020 02:48:15 +0000 (19:48 -0700)]
libusb/Makefile.am: Remove unnecessary assignments

Remove the unnecessary assignment of EXTRA_DIST. Anything that could end
up in SOURCES is automatically included in the distribution.

Remove the unnecessary assignment of libusb_1_0_la_CFLAGS. AM_CFLAGS is
already the default value, but assigning to the variable makes automake
think that custom CFLAGS are needed and therefore causes a bunch of
pointless additional rules to be generated. As a reference, the
generated Makefile shed 21,560 bytes (from 52,029 bytes to 30,469).

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Kill the OS_* definitions and use in the source code
Chris Dickens [Sat, 28 Mar 2020 01:23:16 +0000 (18:23 -0700)]
core: Kill the OS_* definitions and use in the source code

These symbols are no longer necessary for the source code since commit
cad7d0edd9 ("core: Kill usbi_os_backend structure definition madness").

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agothreads_posix: Improve usbi_get_tid() for various platforms
Chris Dickens [Fri, 27 Mar 2020 07:03:41 +0000 (00:03 -0700)]
threads_posix: Improve usbi_get_tid() for various platforms

Add support for real thread IDs on macOS 10.6 and later using the new
pthread_threadid_np() function.

Add support for thread IDs on Haiku, NetBSD and Solaris.

Provide a fallback value other than -1 when direct support is not
available. This should suffice as a unique identifier since pthread_t,
while opaque, is still distinct amongst active threads.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agostrerror: Micro-optimize implementation and remove use of strncasecmp()
Chris Dickens [Fri, 27 Mar 2020 04:38:45 +0000 (21:38 -0700)]
strerror: Micro-optimize implementation and remove use of strncasecmp()

When comparing the user-provided locale string in libusb_setlocale(), we
only care about the first two characters. The lookup strings within
libusb are always lowercase, so simplify the comparison by directly
comparing the result of tolower(). This removes the need for
strncasecmp() which was not able to be cleanly included in the first
place.

Rather than storing an index into the array of localized strings, store
a pointer to the selected sub-array instead. This trims the generated
code of libusb_strerror() by nearly half as loads can be dropped.

Also constify the arrays of strings as they should not be mutable.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agodarwin: Explicitly cleanup cached devices during the last libusb_exit()
Chris Dickens [Thu, 26 Mar 2020 22:50:04 +0000 (15:50 -0700)]
darwin: Explicitly cleanup cached devices during the last libusb_exit()

Deferring the cached devices cleanup until the "destructor" function is
called makes it appear as though libusb is leaking memory, especially if
heap allocations are analyzed after calling libusb_exit(). It can also
lead to devices staying on the list longer than they should, as seen by
the following sequence of events:

  libusb_init() <-- init_count is 0, async thread is started
    devices_scan_devices() <-- enumerates devices
  libusb_exit() <-- init_count is 0, async thread is stopped
  [one or more devices disconnected]

Because the async thread is stopped when device(s) are disconnected in
the above sequence, the disconnection event(s) will not be processed and
thus darwin_devices_detached() will not be called and the list will have
one or more stale entries until the "destructor" function is finally
called.

Address both of these shortcomings by cleaning up the cached devices
list after stopping the async thread.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoappveyor: Increase build coverage to all VS solutions
Chris Dickens [Thu, 26 Mar 2020 22:40:23 +0000 (15:40 -0700)]
appveyor: Increase build coverage to all VS solutions

Using the 'for' construct allows the specification of a more complex
build matrix. This additionally simplifies the builds using MinGW and
Cygwin because the build script can be unified and does not require
checking for the 'Release' configuration.

This change also extends the MinGW builds to cover both 32-bit and
64-bit builds using GCC versions 6.3.0 and 8.1.0, respectively. The
Cygwin builds were similarly extended to include 64-bit build coverage.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolibusb/Makefile.am: Fix out-of-tree builds on Windows
Chris Dickens [Wed, 25 Mar 2020 07:41:32 +0000 (00:41 -0700)]
libusb/Makefile.am: Fix out-of-tree builds on Windows

The prerequisite $< includes the path when not building in-tree, thus
the use of $(srcdir) as a prefix is incorrect.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agomsvc: Update include path for getopt in fxload projects
Chris Dickens [Wed, 25 Mar 2020 07:27:11 +0000 (00:27 -0700)]
msvc: Update include path for getopt in fxload projects

Commit 07d6d3a2a5 ("msvc: Reorder solution projects and add project
filter files") moved the getopt source into the msvc directory but did
not include updating the include paths for the project that needs the
header files.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoautotools: Fix a number of issues
Chris Dickens [Wed, 25 Mar 2020 07:09:26 +0000 (00:09 -0700)]
autotools: Fix a number of issues

Change the name of the project to be what it actually is called
everywhere: libusb-1.0. This allows the public libusb.h header file to
be tracked by automake through pkginclude_HEADERS.

Decouple the doc directory from automake. There aren't any targets that
automake understands, so the build uselessly recurses into the directory.
Update the makefile targets with the correct dependencies so that the
docs aren't regenerated unnecessarily. Update the doxygen config file to
include the version, exclude irrelevant source files and create the
output into 'api-1.0' instead of 'html'. Also fix a deprecation tag for
the libusb_get_port_path() function and add Solaris to the list of
supported platforms.

Fix the 'dist' target. Clean up the README file to remote the GitHub
Markdown and remove the .gitattributes file from the msvc directory.
Add doc/libusb.png to EXTRA_DIST.

Enhance the {dist,doc}-upload targets to look at the SF_USER environment
variable to get the SourceForge username. This allows maintainers (like
me!) to have a local username that is different from their SourceForge
username. Switch the docs-upload recipe to use rsync with --delete to
clean up obsolete files.

Fix the Windows shared library (DLL) targets. The dependencies for the
RC file were incorrect, leading to cases of missed recompilation. The
'all' rule should not be overridden, so define an 'all-local' rule when
necessary. Fix the rule for running dlltool on the just generated DLL so
that it only fires when the correct dependencies change and do not
bother to run the rule when not building a DLL.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agomsvc: Reorder solution projects and add project filter files
Chris Dickens [Mon, 23 Mar 2020 22:17:50 +0000 (15:17 -0700)]
msvc: Reorder solution projects and add project filter files

Since Visual Studio picks the first project as the default startup
project, move the library projects back to the top of the list. This use
to be the order but was changed in commit 9843b689df.

Add the project filter files to help organize the source files within
the Solution Explorer window pane.

Additionally move the getopt source underneath the msvc directory since
it is only used for Visual Studio builds.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoHaiku: Fix some issues in the backend
Chris Dickens [Tue, 17 Mar 2020 03:14:24 +0000 (20:14 -0700)]
Haiku: Fix some issues in the backend

Since commit 8cfcc63f4f ("haiku_usb_raw: Add missing wrap_sys_device
field to usbi_os_backend"), compilation of the Haiku backend has been
broken. Since the code is C++, named initializers are not supported. Fix
this by going back to the original style of initializing
usbi_os_backend.

Additionally, commit db99ef3451 ("Various fixes for the Haiku port")
further broken some things. The ClearHalt() function was defined as a
member of the USBDevice class but is declared and needed as a member of
the USBDeviceHandle class. The ioctl command code also contained a typo.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Make the 'reset_device' function of the backend optional
Chris Dickens [Mon, 16 Mar 2020 08:15:29 +0000 (01:15 -0700)]
core: Make the 'reset_device' function of the backend optional

The majority of backends do not have support for resetting a device, so
simplify them all by making the function optional and having the core
return the appropriate error when the function is not implemented.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Fix return value of usbi_clock_gettime()
Chris Dickens [Mon, 16 Mar 2020 08:06:27 +0000 (01:06 -0700)]
core: Fix return value of usbi_clock_gettime()

In most cases, usbi_clock_gettime() will map to the standard library's
clock_gettime() function. The semantics of this function are that it
returns -1 upon failure with the error code available in the errno
variable. The backends that need to implement this function should
follow the same semantics, and the return value of usbi_clock_gettime()
should not be directly propagated upwards.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Move parameter validation from backend to core
Chris Dickens [Mon, 16 Mar 2020 08:01:51 +0000 (01:01 -0700)]
core: Move parameter validation from backend to core

Some functions (e.g. libusb_set_interface_alt_setting()) do not perform
sufficient parameter validation, leaving the burden on the backend to
catch invalid user input. Much of this validation is common across all
backends, yet not every backend implemented it. Fix this by moving
parameter validation to the core library functions.

This is also a good opportunity to remove the redundant
'num_configurations' field from the libusb_device structure. The value
of this field is already contained in the 'device_descriptor' member.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Kill usbi_backend.clock_gettime() function
Chris Dickens [Mon, 27 Jan 2020 06:43:28 +0000 (22:43 -0800)]
core: Kill usbi_backend.clock_gettime() function

Out of all the backends supported by libusb, only two need to provide an
implementation of the clock_gettime() function. Windows completely lacks
such a function and versions of Mac OS prior to 10.12 do not provide it.
In all other cases the backend simply ends up calling the C library's
clock_gettime() function.

Let's optimize for the common case and check for the availability of
clock_gettime() during configure. If available, we will just call it
directly from any part of the library that needs it. If not available,
the backend is required to provide an implementation of
usbi_clock_gettime() that matches the current requirements.

Closes #685

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoWindows: Fix some harmless build warnings
Chris Dickens [Tue, 10 Mar 2020 06:06:17 +0000 (23:06 -0700)]
Windows: Fix some harmless build warnings

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Switch usbi_transfer to store timeout as timespec
Chris Dickens [Fri, 6 Mar 2020 07:19:55 +0000 (23:19 -0800)]
core: Switch usbi_transfer to store timeout as timespec

The transfer timeout is structured around time values provided by the
clock_gettime() function. This function uses a timespec structure, but
the usbi_transfer structure was storing its calculated timeout in a
timeval structure. This mismatch introduces extra work when checking for
transfer timeouts as there must be a conversion between these two
structures. Eliminate this by storing the calculated timeout as a
timespec, thus allowing direct comparison.

Note that a conversion to a timeval is still necessary in the
libusb_get_next_timeout() function because the public API uses a timeval
structure, but this is now the only place where such a conversion is
done.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agodarwin: Fix race condition that results in segmentation fault
Chris Dickens [Tue, 3 Mar 2020 00:23:45 +0000 (16:23 -0800)]
darwin: Fix race condition that results in segmentation fault

Commit 763668cc92 ("darwin: fix occasional dead-lock on libusb_exit")
resolved the deadlock situation observed in #112, but unfortunately
there is a very rare race condition that can occur when the asynchronous
event thread exits the run loop before CFRunLoopWakeUp() is called. This
can occur when the shutdown source signal is processed as part of other
events in the run loop, in which case the thread was already "awake".

Prior to this change I was able to consistently trigger a segmentation
fault within 10,000 iterations of a libusb_init()/libusb_exit() loop.
With this change I reached over 4 million iterations without issue.

Closes #701

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Introduce accessor functions for structure private data
Chris Dickens [Wed, 26 Feb 2020 23:55:10 +0000 (15:55 -0800)]
core: Introduce accessor functions for structure private data

The backend private data for the internal library structures has been
accessed through a zero-length os_priv array of type unsigned char.
This approach had two particular disadvantages:

  1) A special attribute was needed on the 'os_priv' member to ensure
     that the field was properly aligned to a natural pointer alignment.
     The support needed for this is not available in every compiler.

  2) Each access to the private data areas required an explicit cast
     from unsigned char to the type required by the backend.

This change reworks the way the private data is accessed by the
backends. New accessor functions return the private data as a void
pointer type, removing the need for an explicit cast (except for Haiku,
which is C++). The special alignment attribute trickery is also replaced
by simple pointer arithmetic.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Optimize the memory layout of the transfer structure
Chris Dickens [Wed, 26 Feb 2020 23:14:56 +0000 (15:14 -0800)]
core: Optimize the memory layout of the transfer structure

Prior to this commit, the memory layout of the transfer structure was as
follows:

         ------------------------------------------------------
        | usbi_transfer | libusb_transfer [variable] | os_priv |
         ------------------------------------------------------

With this layout, accessing the os_priv area requires calculating the
size of the area used by the libusb_transfer, which varies based on the
number of iso packets allocated for the transfer.

This commit changes the memory layout of the transfer structure to the
following:

         ------------------------------------------------------
        | os_priv | usbi_transfer | libusb_transfer [variable] |
         ------------------------------------------------------

Having the os_priv in a fixed position relative to the usbi_transfer
allows for constant-time access with the added benefit of not allowing
the user to corrupt the data by accessing elements of the
libusb_transfer structure that are out-of-bounds.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Use a consistent variable name for usbi_transfer structures
Chris Dickens [Wed, 26 Feb 2020 17:18:02 +0000 (09:18 -0800)]
core: Use a consistent variable name for usbi_transfer structures

Most places in the library use the name 'itransfer' when referring to a
usbi_transfer structure. This is helpful to distinguish between the
public libusb_transfer structure and the internal structure. Fix up the
few places that don't follow this convention so that it is consistent
across the entire library.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoWindows: fix MAX_PATH_LENGTH
a1exdandy [Sat, 22 Feb 2020 22:43:09 +0000 (01:43 +0300)]
Windows: fix MAX_PATH_LENGTH

The MAX_PATH_LENGTH in libusb Windows backend is used as size of
dev_id buffer. This buffer used for retreiving Device Instance Id
by SetupDiGetDeviceInstanceIdA function. Acording to Microsoft,
Device Instance Id must be less than MAX_DEVICE_ID_LEN = 200.
So, value of 128 maybe not enough.

Closes #699

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolinux: provide an event thread name
Alexander Stein [Wed, 5 Feb 2020 20:41:07 +0000 (21:41 +0100)]
linux: provide an event thread name

Instead of having just the application name as thread name, provide a more
descriptive one, which can e.g. read by htop.
If setting the name fails, the thread will still work as intended, just
raise a warning in this case.

Closes #689

Signed-off-by: Alexander Stein <alexander.stein@mailbox.org>
Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agothreads_posix: Use thread-local storage to cache thread ID
Chris Dickens [Fri, 24 Jan 2020 19:51:55 +0000 (11:51 -0800)]
threads_posix: Use thread-local storage to cache thread ID

Trying to capture debug logs that reproduce a problem can be tricky.
Turning up the debug level will automatically make the program a bit
slower. This alone cane make timing-sensitive bugs "disappear" when
capturing logs. One of the hot paths for debug messages is fetching the
thread ID, which is immeasurably helpful in understanding thread
interactions within the library. Unfortunately most implementations
require a system call to fetch the executing thread's ID, which isn't
exactly going to help in the way of execution time.

Add a check for thread-local storage support when configuring the
library to build. If the toolchain provides this support, only one
system call will be required per thread. This check is only done for
non-Windows systems because thread-local storage is inefficiently
implemented on MinGW.

Closes #682

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoWindows: Refactoring to consolidate and simplify common code
Chris Dickens [Fri, 7 Feb 2020 23:47:55 +0000 (15:47 -0800)]
Windows: Refactoring to consolidate and simplify common code

Both the UsbDk and WinUSB backends perform common steps when handling
transfers in order to interact with the poll abstraction, both during
submission and when processing transfer completion. With some
rearranging of shared structures, this can be yanked from the individual
backends and placed in the common area. This allows for several
functions to be removed outright from each backend.

The cancellation logic can also be simplified by attempting CancelIoEx()
at the highest level and delegating to the backend if there are
alternatives to try should CancelIoEx() fail.

After some analysis of how Windows processes asychronous (OVERLAPPED)
requests that the underlying driver completes synchronously, it is now
evident that such requests need not be handled in any special fashion.
Each function that called a driver function that was expected to
complete asynchronously had logic to handle the case of a synchronous
completion, so this has all been killed off. This significantly cleans
up these call sites as now they must only check for an error condition.

Finally, the initialization code for the WinUSB backend has been
reworked to load the WinUSB DLL independent of the libusbK DLL.
Previously when the libusbK DLL was present, all requests to devices
using WinUSB would first be sent through the libusbK DLL where
they would then be forwarded to the WinUSB DLL. This is slightly
inefficient but is also limiting when using Windows 8.1 or later because
support for isochronous transfers through WinUSB will be lost.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoWindows: Fix poll implementation for NDEBUG (Release) builds
Chris Dickens [Fri, 31 Jan 2020 04:48:56 +0000 (20:48 -0800)]
Windows: Fix poll implementation for NDEBUG (Release) builds

The refactoring in commit df61c0c3a3 ("Windows: improve poll
abstraction") introduced a bug in builds where NDEBUG is defined because
of a statement with side-effects that was put inside an assertion. When
this statement is not evaluated, the file descriptor table gets corrupt.
Fix this by moving the statement outside of the assertion.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoWindows: Fix reported length of synchronous control transfers
Chris Dickens [Tue, 28 Jan 2020 18:24:14 +0000 (10:24 -0800)]
Windows: Fix reported length of synchronous control transfers

WinUSB control transfers that complete synchronously are incorrectly
having the actual transfer length set to the size of the transfer
buffer. If the control transfer is a read, the device may return less
data than the transfer buffer size. Fix this by reporting the actual
bytes transferred.

Closes #667

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolinux_usbfs: Drop support for kernel versions earlier than 2.6.32
Chris Dickens [Mon, 27 Jan 2020 06:01:50 +0000 (22:01 -0800)]
linux_usbfs: Drop support for kernel versions earlier than 2.6.32

The Linux backend plays lots of games to try and work with older
versions of the kernel that do not have certain features. Lets simplify
the backend by requiring at least 2.6.32 to use libusb. The only thing
remaining that still requires explicit version checking is the maximum
iso frame packet size.

Anything running 2.6.32 or later is sure to have a functional monotonic
clock, so this change also allows the removal of the get_timerfd_clock()
function from the backend as well as the check for a functional
monotonic clock during initialization.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoWindows: Fix GCC printf format warnings due to DWORD/ULONG types
Chris Dickens [Sun, 26 Jan 2020 22:31:35 +0000 (14:31 -0800)]
Windows: Fix GCC printf format warnings due to DWORD/ULONG types

The Visual Studio compiler considers a long to always be 32-bits, so the
official Windows API headers define the DWORD and ULONG types as
unsigned long proper. GCC (and possibly other compilers) vary the width
of a long to match the build target, so this complicates printf format
strings for these two types because the underlying type is inconsistent.

Address this mess by introducing a macro that casts as necessary for the
compiler.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoautobuild: Fix two issues
Chris Dickens [Sun, 26 Jan 2020 22:29:48 +0000 (14:29 -0800)]
autobuild: Fix two issues

The test for defining the automake conditional for the poll
implementation was keying off of the threads variable, producing
incorrect results for Cygwin.

A simple typo in the Makefile causes a build failure when
cross-compiling for Windows.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agocore: Fix build on linux
root [Sun, 26 Jan 2020 13:01:09 +0000 (15:01 +0200)]
core: Fix build on linux

Commit 7bc0ff3 left a parenthesis over which prevents succesful build.

Signed-off-by: Andrey Perevortkin <asavah@avh.od.ua>
4 years agocore: Convert internal macros to static inline functions
Chris Dickens [Sat, 25 Jan 2020 20:10:04 +0000 (12:10 -0800)]
core: Convert internal macros to static inline functions

Older versions of the Visual Studio compiler are picky about macros
constructed with the 'do { ... } while (0)' construct. Convert these
internal ones to static inline functions. The result is functionally
equivalent but gets us type checking and a bit more readability.

Also address some compiler warnings due to some header files that are
being included in a different order than before.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoFix msvc 2019 project files (internal linkage)
winterrace [Fri, 24 Jan 2020 21:59:52 +0000 (22:59 +0100)]
Fix msvc 2019 project files (internal linkage)

Closes #683

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agolinux_usbfs: Clean up inconsistencies and optimize memory usage
Chris Dickens [Fri, 24 Jan 2020 00:18:24 +0000 (16:18 -0800)]
linux_usbfs: Clean up inconsistencies and optimize memory usage

The formatting and coding style varied across the whole file. Adopt the
following consistent style:

  - Align function arguments to the opening parenthesis
  - Do not check for NULL before calling free()
  - Reduce indentation where possible in loops by continuing in the
    success case
  - Remove space between function name and opening parenthesis
  - Remove pointless pointer casts from void *
  - Replace comparisons with NULL or 0 by a negation operator
  - When comparing against rvalues, place the rvalue on the right side
    of the expression
  - Where possible, have the debug message string on the same line as
    the usbi_* call. This makes it easier to grep for specific strings.

Also update the definitions in linux_usbfs.h to exactly match that of
the kernel and remove definitions that are not needed.

A number of functions declared stack buffers of size PATH_MAX. This is
generally 4K, which is very much overkill for a lot of the strings and
is not friendly for embedded environments. Replace many of these buffers
with reasonably-sized ones, in many cases using exactly the size needed.

When reading the descriptors during device enumeration, we were starting
with a 1K buffer and doubling as needed. The vast majority of devices
will not have a large set of descriptors, so change the allocation logic
to grow the buffer in steps of 256 bytes.

Introduce a new parsing function for reading sysfs attributes. Using the
fdopen() function to use fscanf() results in excessive memory
allocation, one for the FILE object and another for the buffer into
which the C library will read the data. The sysfs attributes of interest
are generally just a few characters, so use a small stack buffer and
some rigorous parsing to read these attributes. This also consolidates
error checking (e.g. negative values or larger than expected values).

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoconfigure.ac: Cleanup and refactoring
Chris Dickens [Thu, 23 Jan 2020 01:39:14 +0000 (17:39 -0800)]
configure.ac: Cleanup and refactoring

Make the formatting consistent across the entire file. In particular:

  - Always quote strings whose values are derived
  - Use tabs consistently
  - Wrap all arguments with square brackets

Replace the use of '-a' with '&&' to be more portable.

Rearrange some of the feature checks to be conditional upon the platform
or backend. For example, there is no need to check for nfds_t on Windows
because poll() doesn't exist there. Similarly we now only check for
timerfd on Linux and Solaris. This translates into slightly faster
configure times.

Explicitly define tokens for both the poll and thread implementations.
This makes the preprocessor conditionals much nicer since it is not
necessary to enumerate all possible OS_* tokens. Also replace
POLL_NFDS_TYPE with a proper typedef that is based on the availability
of the nfds_t type.

Migrate to config definition names that are more consistent with
autoconf. The check for timerfd actually verifies the presence of the
library function instead of just the header definitions, and the token
USBI_TIMERFD_AVAILABLE is now HAVE_TIMERFD. Similarly the check for
syslog results in a definition of HAVE_SYSLOG.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoMisc: Clean up zero-length strings and recursion in clock_gettime()
Chris Dickens [Thu, 23 Jan 2020 01:02:20 +0000 (17:02 -0800)]
Misc: Clean up zero-length strings and recursion in clock_gettime()

Commit 0bf84e4d51 ("core: fix build warning on newer versions of gcc")
addressed compiler warnings for zero-length printf format strings in the
core library files, but there are some additional remaining in some of
the backends. Address these remaining ones in the same manner.

Also remove the usbi_dbg() call in netbsd_clock_gettime(). This causes
infinite recursion since usbi_dbg() calls the backend's clock_gettime()
function. This was similarly addressed for the OpenBSD backend in commit
6acbd8b405 ("Remove infinite recursion in OpenBSD backend").

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
4 years agoMisc: Cleanup across multiple backends
Chris Dickens [Thu, 23 Jan 2020 00:59:25 +0000 (16:59 -0800)]
Misc: Cleanup across multiple backends

Remove the clear_transfer_priv() function from all backends besides
Linux. This function is only needed if the backend calls
usbi_handle_disconnect(), which only Linux does.

Remove the {attach,detach}_kernel_driver() functions from the Darwin
backend. They return LIBUSB_ERROR_NOT_SUPPORTED, but the same result is
achieved by having those functions be NULL.

Remove the init() and exit() functions from the SunOS backend. They are
optional and as no-ops are pointless.

Remove NULL and 0 initializers from usbi_backend structures.

Use named initializers in the NetBSD backend.

Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>