usb 2.17.0 → 3.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/LICENSE +18 -4
  2. package/README.md +25 -516
  3. package/dist/index.d.ts +67 -13
  4. package/dist/index.js +333 -64
  5. package/index.d.ts +89 -0
  6. package/index.js +583 -0
  7. package/package.json +53 -33
  8. package/CHANGELOG.md +0 -294
  9. package/binding.gyp +0 -128
  10. package/dist/index.js.map +0 -1
  11. package/dist/usb/bindings.d.ts +0 -266
  12. package/dist/usb/bindings.js +0 -10
  13. package/dist/usb/bindings.js.map +0 -1
  14. package/dist/usb/capability.d.ts +0 -13
  15. package/dist/usb/capability.js +0 -17
  16. package/dist/usb/capability.js.map +0 -1
  17. package/dist/usb/descriptors.d.ts +0 -128
  18. package/dist/usb/descriptors.js +0 -3
  19. package/dist/usb/descriptors.js.map +0 -1
  20. package/dist/usb/device.d.ts +0 -100
  21. package/dist/usb/device.js +0 -297
  22. package/dist/usb/device.js.map +0 -1
  23. package/dist/usb/endpoint.d.ts +0 -94
  24. package/dist/usb/endpoint.js +0 -219
  25. package/dist/usb/endpoint.js.map +0 -1
  26. package/dist/usb/index.d.ts +0 -31
  27. package/dist/usb/index.js +0 -116
  28. package/dist/usb/index.js.map +0 -1
  29. package/dist/usb/interface.d.ts +0 -80
  30. package/dist/usb/interface.js +0 -133
  31. package/dist/usb/interface.js.map +0 -1
  32. package/dist/webusb/index.d.ts +0 -64
  33. package/dist/webusb/index.js +0 -295
  34. package/dist/webusb/index.js.map +0 -1
  35. package/dist/webusb/webusb-device.d.ts +0 -54
  36. package/dist/webusb/webusb-device.js +0 -434
  37. package/dist/webusb/webusb-device.js.map +0 -1
  38. package/libusb/.clang-tidy +0 -34
  39. package/libusb/.codespellrc +0 -3
  40. package/libusb/.private/README.txt +0 -5
  41. package/libusb/.private/appveyor_build.sh +0 -26
  42. package/libusb/.private/bm.sh +0 -54
  43. package/libusb/.private/ci-build.sh +0 -92
  44. package/libusb/.private/ci-container-build.sh +0 -67
  45. package/libusb/.private/post-rewrite.sh +0 -32
  46. package/libusb/.private/pre-commit.sh +0 -52
  47. package/libusb/.private/wbs.txt +0 -43
  48. package/libusb/.travis.yml +0 -58
  49. package/libusb/AUTHORS +0 -231
  50. package/libusb/COPYING +0 -504
  51. package/libusb/ChangeLog +0 -365
  52. package/libusb/HACKING +0 -25
  53. package/libusb/INSTALL_WIN.txt +0 -52
  54. package/libusb/KEYS +0 -123
  55. package/libusb/Makefile.am +0 -50
  56. package/libusb/NEWS +0 -2
  57. package/libusb/PORTING +0 -94
  58. package/libusb/README +0 -29
  59. package/libusb/README.git +0 -41
  60. package/libusb/TODO +0 -2
  61. package/libusb/Xcode/common.xcconfig +0 -92
  62. package/libusb/Xcode/config.h +0 -31
  63. package/libusb/Xcode/debug.xcconfig +0 -32
  64. package/libusb/Xcode/libusb.xcconfig +0 -21
  65. package/libusb/Xcode/libusb.xcodeproj/project.pbxproj +0 -1391
  66. package/libusb/Xcode/libusb_debug.xcconfig +0 -21
  67. package/libusb/Xcode/libusb_release.xcconfig +0 -21
  68. package/libusb/Xcode/release.xcconfig +0 -30
  69. package/libusb/android/README +0 -152
  70. package/libusb/android/config.h +0 -55
  71. package/libusb/android/examples/unrooted_android.c +0 -301
  72. package/libusb/android/examples/unrooted_android.h +0 -36
  73. package/libusb/android/jni/Android.mk +0 -23
  74. package/libusb/android/jni/Application.mk +0 -40
  75. package/libusb/android/jni/examples.mk +0 -168
  76. package/libusb/android/jni/libusb.mk +0 -60
  77. package/libusb/android/jni/tests.mk +0 -45
  78. package/libusb/appveyor.yml +0 -108
  79. package/libusb/autogen.sh +0 -10
  80. package/libusb/bootstrap.sh +0 -10
  81. package/libusb/configure.ac +0 -450
  82. package/libusb/doc/Makefile.in +0 -22
  83. package/libusb/doc/doxygen.cfg.in +0 -2571
  84. package/libusb/doc/libusb.png +0 -0
  85. package/libusb/examples/Makefile.am +0 -12
  86. package/libusb/examples/dpfp.c +0 -711
  87. package/libusb/examples/ezusb.c +0 -846
  88. package/libusb/examples/ezusb.h +0 -109
  89. package/libusb/examples/fxload.c +0 -310
  90. package/libusb/examples/hotplugtest.c +0 -147
  91. package/libusb/examples/listdevs.c +0 -73
  92. package/libusb/examples/sam3u_benchmark.c +0 -228
  93. package/libusb/examples/testlibusb.c +0 -312
  94. package/libusb/examples/xusb.c +0 -1254
  95. package/libusb/libusb/Makefile.am +0 -98
  96. package/libusb/libusb/Makefile.am.extra +0 -26
  97. package/libusb/libusb/core.c +0 -2925
  98. package/libusb/libusb/descriptor.c +0 -1558
  99. package/libusb/libusb/hotplug.c +0 -489
  100. package/libusb/libusb/io.c +0 -2865
  101. package/libusb/libusb/libusb-1.0.def +0 -199
  102. package/libusb/libusb/libusb-1.0.rc +0 -53
  103. package/libusb/libusb/libusb.h +0 -2421
  104. package/libusb/libusb/libusbi.h +0 -1535
  105. package/libusb/libusb/os/darwin_usb.c +0 -2977
  106. package/libusb/libusb/os/darwin_usb.h +0 -156
  107. package/libusb/libusb/os/emscripten_webusb.cpp +0 -875
  108. package/libusb/libusb/os/events_posix.c +0 -340
  109. package/libusb/libusb/os/events_posix.h +0 -62
  110. package/libusb/libusb/os/events_windows.c +0 -214
  111. package/libusb/libusb/os/events_windows.h +0 -46
  112. package/libusb/libusb/os/haiku_pollfs.cpp +0 -372
  113. package/libusb/libusb/os/haiku_usb.h +0 -113
  114. package/libusb/libusb/os/haiku_usb_backend.cpp +0 -532
  115. package/libusb/libusb/os/haiku_usb_raw.cpp +0 -231
  116. package/libusb/libusb/os/haiku_usb_raw.h +0 -188
  117. package/libusb/libusb/os/linux_netlink.c +0 -401
  118. package/libusb/libusb/os/linux_udev.c +0 -321
  119. package/libusb/libusb/os/linux_usbfs.c +0 -2829
  120. package/libusb/libusb/os/linux_usbfs.h +0 -221
  121. package/libusb/libusb/os/netbsd_usb.c +0 -617
  122. package/libusb/libusb/os/null_usb.c +0 -111
  123. package/libusb/libusb/os/openbsd_usb.c +0 -700
  124. package/libusb/libusb/os/sunos_usb.c +0 -1619
  125. package/libusb/libusb/os/sunos_usb.h +0 -79
  126. package/libusb/libusb/os/threads_posix.c +0 -126
  127. package/libusb/libusb/os/threads_posix.h +0 -98
  128. package/libusb/libusb/os/threads_windows.c +0 -40
  129. package/libusb/libusb/os/threads_windows.h +0 -113
  130. package/libusb/libusb/os/windows_common.c +0 -923
  131. package/libusb/libusb/os/windows_common.h +0 -424
  132. package/libusb/libusb/os/windows_usbdk.c +0 -724
  133. package/libusb/libusb/os/windows_usbdk.h +0 -106
  134. package/libusb/libusb/os/windows_winusb.c +0 -4766
  135. package/libusb/libusb/os/windows_winusb.h +0 -787
  136. package/libusb/libusb/strerror.c +0 -223
  137. package/libusb/libusb/sync.c +0 -342
  138. package/libusb/libusb/version.h +0 -18
  139. package/libusb/libusb/version_nano.h +0 -1
  140. package/libusb/libusb-1.0.pc.in +0 -11
  141. package/libusb/msvc/Base.props +0 -60
  142. package/libusb/msvc/Configuration.Application.props +0 -7
  143. package/libusb/msvc/Configuration.Base.props +0 -47
  144. package/libusb/msvc/Configuration.DynamicLibrary.props +0 -21
  145. package/libusb/msvc/Configuration.StaticLibrary.props +0 -7
  146. package/libusb/msvc/ProjectConfigurations.Base.props +0 -69
  147. package/libusb/msvc/build_all.ps1 +0 -17
  148. package/libusb/msvc/config.h +0 -58
  149. package/libusb/msvc/dpfp.vcxproj +0 -33
  150. package/libusb/msvc/dpfp_threaded.vcxproj +0 -38
  151. package/libusb/msvc/fxload.vcxproj +0 -46
  152. package/libusb/msvc/getopt/getopt.c +0 -1060
  153. package/libusb/msvc/getopt/getopt.h +0 -180
  154. package/libusb/msvc/getopt/getopt1.c +0 -188
  155. package/libusb/msvc/getopt.vcxproj +0 -33
  156. package/libusb/msvc/hotplugtest.vcxproj +0 -32
  157. package/libusb/msvc/init_context.vcxproj +0 -35
  158. package/libusb/msvc/libusb.sln +0 -542
  159. package/libusb/msvc/libusb_dll.vcxproj +0 -61
  160. package/libusb/msvc/libusb_static.vcxproj +0 -49
  161. package/libusb/msvc/listdevs.vcxproj +0 -32
  162. package/libusb/msvc/sam3u_benchmark.vcxproj +0 -33
  163. package/libusb/msvc/set_option.vcxproj +0 -35
  164. package/libusb/msvc/stress.vcxproj +0 -35
  165. package/libusb/msvc/stress_mt.vcxproj +0 -33
  166. package/libusb/msvc/testlibusb.vcxproj +0 -32
  167. package/libusb/msvc/xusb.vcxproj +0 -38
  168. package/libusb/tests/Makefile.am +0 -40
  169. package/libusb/tests/init_context.c +0 -153
  170. package/libusb/tests/libusb_testlib.h +0 -76
  171. package/libusb/tests/macos.c +0 -130
  172. package/libusb/tests/set_option.c +0 -253
  173. package/libusb/tests/stress.c +0 -172
  174. package/libusb/tests/stress_mt.c +0 -267
  175. package/libusb/tests/testlib.c +0 -184
  176. package/libusb/tests/umockdev.c +0 -1175
  177. package/libusb/tests/webusb-test-shim/index.js +0 -12
  178. package/libusb/tests/webusb-test-shim/package-lock.json +0 -50
  179. package/libusb/tests/webusb-test-shim/package.json +0 -10
  180. package/libusb.gypi +0 -154
  181. package/libusb_config/config.h +0 -1
  182. package/prebuilds/android-arm/node.napi.armv7.node +0 -0
  183. package/prebuilds/android-arm64/node.napi.armv8.node +0 -0
  184. package/prebuilds/darwin-x64+arm64/node.napi.node +0 -0
  185. package/prebuilds/linux-arm/node.napi.armv6.node +0 -0
  186. package/prebuilds/linux-arm/node.napi.armv7.node +0 -0
  187. package/prebuilds/linux-arm64/node.napi.armv8.node +0 -0
  188. package/prebuilds/linux-ia32/node.napi.node +0 -0
  189. package/prebuilds/linux-x64/node.napi.glibc.node +0 -0
  190. package/prebuilds/linux-x64/node.napi.musl.node +0 -0
  191. package/prebuilds/win32-arm64/node.napi.node +0 -0
  192. package/prebuilds/win32-ia32/node.napi.node +0 -0
  193. package/prebuilds/win32-x64/node.napi.node +0 -0
  194. package/src/device.cc +0 -439
  195. package/src/helpers.h +0 -64
  196. package/src/hotplug/hotplug.h +0 -22
  197. package/src/hotplug/libusb.cc +0 -90
  198. package/src/hotplug/windows.cc +0 -168
  199. package/src/node_usb.cc +0 -314
  200. package/src/node_usb.h +0 -131
  201. package/src/thread_name.cc +0 -79
  202. package/src/thread_name.h +0 -11
  203. package/src/transfer.cc +0 -143
  204. package/src/uv_async_queue.h +0 -41
  205. package/test/usb.coffee +0 -250
  206. package/test/webusb.coffee +0 -227
  207. package/test/worker.cjs +0 -13
@@ -1,2925 +0,0 @@
1
- /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2
- /*
3
- * Core functions for libusb
4
- * Copyright © 2012-2023 Nathan Hjelm <hjelmn@cs.unm.edu>
5
- * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
6
- * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
7
- *
8
- * This library is free software; you can redistribute it and/or
9
- * modify it under the terms of the GNU Lesser General Public
10
- * License as published by the Free Software Foundation; either
11
- * version 2.1 of the License, or (at your option) any later version.
12
- *
13
- * This library is distributed in the hope that it will be useful,
14
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
- * Lesser General Public License for more details.
17
- *
18
- * You should have received a copy of the GNU Lesser General Public
19
- * License along with this library; if not, write to the Free Software
20
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
- */
22
-
23
- #include "libusbi.h"
24
- #include "version.h"
25
-
26
- #ifdef __ANDROID__
27
- #include <android/log.h>
28
- #endif
29
- #include <stdio.h>
30
- #include <string.h>
31
- #ifdef HAVE_SYSLOG
32
- #include <syslog.h>
33
- #endif
34
-
35
- static const struct libusb_version libusb_version_internal =
36
- { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
37
- LIBUSB_RC, "https://libusb.info" };
38
- static struct timespec timestamp_origin;
39
- #if defined(ENABLE_LOGGING) && !defined(USE_SYSTEM_LOGGING_FACILITY)
40
- static libusb_log_cb log_handler;
41
- #endif
42
-
43
- struct libusb_context *usbi_default_context;
44
- struct libusb_context *usbi_fallback_context;
45
- static int default_context_refcnt;
46
- #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
47
- static usbi_atomic_t default_debug_level = -1;
48
- #endif
49
- static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
50
- static struct usbi_option default_context_options[LIBUSB_OPTION_MAX];
51
-
52
-
53
- usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
54
- struct list_head active_contexts_list;
55
-
56
- /**
57
- * \mainpage libusb-1.0 API Reference
58
- *
59
- * \section intro Introduction
60
- *
61
- * libusb is an open source library that allows you to communicate with USB
62
- * devices from user space. For more info, see the
63
- * <a href="https://libusb.info">libusb homepage</a>.
64
- *
65
- * This documentation is aimed at application developers wishing to
66
- * communicate with USB peripherals from their own software. After reviewing
67
- * this documentation, feedback and questions can be sent to the
68
- * <a href="https://mailing-list.libusb.info">libusb-devel mailing list</a>.
69
- *
70
- * This documentation assumes knowledge of how to operate USB devices from
71
- * a software standpoint (descriptors, configurations, interfaces, endpoints,
72
- * control/bulk/interrupt/isochronous transfers, etc). Full information
73
- * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
74
- * Specification</a> which is available for free download. You can probably
75
- * find less verbose introductions by searching the web.
76
- *
77
- * \section API Application Programming Interface (API)
78
- *
79
- * See the \ref libusb_api page for a complete list of the libusb functions.
80
- *
81
- * \section features Library features
82
- *
83
- * - All transfer types supported (control/bulk/interrupt/isochronous)
84
- * - 2 transfer interfaces:
85
- * -# Synchronous (simple)
86
- * -# Asynchronous (more complicated, but more powerful)
87
- * - Thread safe (although the asynchronous interface means that you
88
- * usually won't need to thread)
89
- * - Lightweight with lean API
90
- * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
91
- * - Hotplug support (on some platforms). See \ref libusb_hotplug.
92
- *
93
- * \section gettingstarted Getting Started
94
- *
95
- * To begin reading the API documentation, start with the Topics page which
96
- * links to the different categories of libusb's functionality.
97
- *
98
- * One decision you will have to make is whether to use the synchronous
99
- * or the asynchronous data transfer interface. The \ref libusb_io documentation
100
- * provides some insight into this topic.
101
- *
102
- * Some example programs can be found in the libusb source distribution under
103
- * the "examples" subdirectory. The libusb homepage includes a list of
104
- * real-life project examples which use libusb.
105
- *
106
- * \section errorhandling Error handling
107
- *
108
- * libusb functions typically return 0 on success or a negative error code
109
- * on failure. These negative error codes relate to LIBUSB_ERROR constants
110
- * which are listed on the \ref libusb_misc "miscellaneous" documentation page.
111
- *
112
- * \section msglog Debug message logging
113
- *
114
- * libusb uses stderr for all logging. By default, logging is set to NONE,
115
- * which means that no output will be produced. However, unless the library
116
- * has been compiled with logging disabled, then any application calls to
117
- * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level),
118
- * libusb_init_context, or the setting of the environmental variable
119
- * LIBUSB_DEBUG outside of the application, can result in logging being
120
- * produced. Your application should therefore not close stderr, but instead
121
- * direct it to the null device if its output is undesirable.
122
- *
123
- * The libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) or
124
- * libusb_init_context functions can be used to enable logging of certain
125
- * messages. With the default configuration, libusb will not log much so if
126
- * you are advised to use one of these functions to enable all
127
- * error/warning/informational messages. It will help debug problems with your
128
- * software.
129
- *
130
- * The logged messages are unstructured. There is no one-to-one correspondence
131
- * between messages being logged and success or failure return codes from
132
- * libusb functions. There is no format to the messages, so you should not
133
- * try to capture or parse them. They are not and will not be localized.
134
- * These messages are not intended to being passed to your application user;
135
- * instead, you should interpret the error codes returned from libusb functions
136
- * and provide appropriate notification to the user. The messages are simply
137
- * there to aid you as a programmer, and if you're confused because you're
138
- * getting a strange error code from a libusb function, enabling message
139
- * logging may give you a suitable explanation.
140
- *
141
- * The LIBUSB_DEBUG environment variable can be used to enable message logging
142
- * at run-time. This environment variable should be set to a log level number,
143
- * which is interpreted the same as the
144
- * libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level), or
145
- * libusb_init_context(&ctx, &(struct libusb_init_option){.option = LIBUSB_OPTION_LOG_LEVEL, .value = {.ival = level}}, 0).
146
- * When the environment variable is set, the message logging verbosity level is
147
- * fixed and setting the LIBUSB_OPTION_LOG_LEVEL option has no effect.
148
- *
149
- * libusb can be compiled without any logging functions, useful for embedded
150
- * systems. In this case, neither the LIBUSB_OPTION_LOG_LEVEL option, nor the
151
- * LIBUSB_DEBUG environment variable will have any effect.
152
- *
153
- * libusb can also be compiled with verbose debugging messages always. When
154
- * the library is compiled in this way, all messages of all verbosities are
155
- * always logged. Again, in this case, neither the LIBUSB_OPTION_LOG_LEVEL
156
- * option, nor the LIBUSB_DEBUG environment variable will have any effect.
157
- *
158
- * \section remarks Other remarks
159
- *
160
- * libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts
161
- * to document these.
162
- */
163
-
164
- /**
165
- * \page libusb_caveats Caveats
166
- *
167
- * \section threadsafety Thread safety
168
- *
169
- * libusb is designed to be completely thread-safe, but as with any API it
170
- * cannot prevent a user from sabotaging themselves, either intentionally or
171
- * otherwise.
172
- *
173
- * Observe the following general guidelines:
174
- *
175
- * - Calls to functions that release a resource (e.g. libusb_close(),
176
- * libusb_free_config_descriptor()) should not be called concurrently on
177
- * the same resource. This is no different than concurrently calling free()
178
- * on the same allocated pointer.
179
- * - Each individual \ref libusb_transfer should be prepared by a single
180
- * thread. In other words, no two threads should ever be concurrently
181
- * filling out the fields of a \ref libusb_transfer. You can liken this to
182
- * calling sprintf() with the same destination buffer from multiple threads.
183
- * The results will likely not be what you want unless the input parameters
184
- * are all the same, but its best to avoid this situation entirely.
185
- * - Both the \ref libusb_transfer structure and its associated data buffer
186
- * should not be accessed between the time the transfer is submitted and the
187
- * time the completion callback is invoked. You can think of "ownership" of
188
- * these things as being transferred to libusb while the transfer is active.
189
- * - The various "setter" functions (e.g. libusb_set_log_cb(),
190
- * libusb_set_pollfd_notifiers()) should not be called concurrently on the
191
- * resource. Though doing so will not lead to any undefined behavior, it
192
- * will likely produce results that the application does not expect.
193
- *
194
- * Rules for multiple threads and asynchronous I/O are detailed
195
- * \ref libusb_mtasync "here".
196
- *
197
- * \section fork Fork considerations
198
- *
199
- * libusb is <em>not</em> designed to work across fork() calls. Depending on
200
- * the platform, there may be resources in the parent process that are not
201
- * available to the child (e.g. the hotplug monitor thread on Linux). In
202
- * addition, since the parent and child will share libusb's internal file
203
- * descriptors, using libusb in any way from the child could cause the parent
204
- * process's \ref libusb_context to get into an inconsistent state.
205
- *
206
- * On Linux, libusb's file descriptors will be marked as CLOEXEC, which means
207
- * that it is safe to fork() and exec() without worrying about the child
208
- * process needing to clean up state or having access to these file descriptors.
209
- * Other platforms may not be so forgiving, so consider yourself warned!
210
- *
211
- * \section devresets Device resets
212
- *
213
- * The libusb_reset_device() function allows you to reset a device. If your
214
- * program has to call such a function, it should obviously be aware that
215
- * the reset will cause device state to change (e.g. register values may be
216
- * reset).
217
- *
218
- * The problem is that any other program could reset the device your program
219
- * is working with, at any time. libusb does not offer a mechanism to inform
220
- * you when this has happened, so if someone else resets your device it will
221
- * not be clear to your own program why the device state has changed.
222
- *
223
- * Ultimately, this is a limitation of writing drivers in user space.
224
- * Separation from the USB stack in the underlying kernel makes it difficult
225
- * for the operating system to deliver such notifications to your program.
226
- * The Linux kernel USB stack allows such reset notifications to be delivered
227
- * to in-kernel USB drivers, but it is not clear how such notifications could
228
- * be delivered to second-class drivers that live in user space.
229
- *
230
- * \section blockonly Blocking-only functionality
231
- *
232
- * The functionality listed below is only available through synchronous,
233
- * blocking functions. There are no asynchronous/non-blocking alternatives,
234
- * and no clear ways of implementing these.
235
- *
236
- * - Configuration activation (libusb_set_configuration())
237
- * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
238
- * - Releasing of interfaces (libusb_release_interface())
239
- * - Clearing of halt/stall condition (libusb_clear_halt())
240
- * - Device resets (libusb_reset_device())
241
- *
242
- * \section configsel Configuration selection and handling
243
- *
244
- * When libusb presents a device handle to an application, there is a chance
245
- * that the corresponding device may be in unconfigured state. For devices
246
- * with multiple configurations, there is also a chance that the configuration
247
- * currently selected is not the one that the application wants to use.
248
- *
249
- * The obvious solution is to add a call to libusb_set_configuration() early
250
- * on during your device initialization routines, but there are caveats to
251
- * be aware of:
252
- * -# If the device is already in the desired configuration, calling
253
- * libusb_set_configuration() using the same configuration value will cause
254
- * a lightweight device reset. This may not be desirable behaviour.
255
- * -# In the case where the desired configuration is already active, libusb
256
- * may not even be able to perform a lightweight device reset. For example,
257
- * take my USB keyboard with fingerprint reader: I'm interested in driving
258
- * the fingerprint reader interface through libusb, but the kernel's
259
- * USB-HID driver will almost always have claimed the keyboard interface.
260
- * Because the kernel has claimed an interface, it is not even possible to
261
- * perform the lightweight device reset, so libusb_set_configuration() will
262
- * fail. (Luckily the device in question only has a single configuration.)
263
- * -# libusb will be unable to set a configuration if other programs or
264
- * drivers have claimed interfaces. In particular, this means that kernel
265
- * drivers must be detached from all the interfaces before
266
- * libusb_set_configuration() may succeed.
267
- *
268
- * One solution to some of the above problems is to consider the currently
269
- * active configuration. If the configuration we want is already active, then
270
- * we don't have to select any configuration:
271
- \code
272
- cfg = -1;
273
- libusb_get_configuration(dev, &cfg);
274
- if (cfg != desired)
275
- libusb_set_configuration(dev, desired);
276
- \endcode
277
- *
278
- * This is probably suitable for most scenarios, but is inherently racy:
279
- * another application or driver may change the selected configuration
280
- * <em>after</em> the libusb_get_configuration() call.
281
- *
282
- * Even in cases where libusb_set_configuration() succeeds, consider that other
283
- * applications or drivers may change configuration after your application
284
- * calls libusb_set_configuration().
285
- *
286
- * One possible way to lock your device into a specific configuration is as
287
- * follows:
288
- * -# Set the desired configuration (or use the logic above to realise that
289
- * it is already in the desired configuration)
290
- * -# Claim the interface that you wish to use
291
- * -# Check that the currently active configuration is the one that you want
292
- * to use.
293
- *
294
- * The above method works because once an interface is claimed, no application
295
- * or driver is able to select another configuration.
296
- *
297
- * \section earlycomp Early transfer completion
298
- *
299
- * NOTE: This section is currently Linux-centric. I am not sure if any of these
300
- * considerations apply to Darwin or other platforms.
301
- *
302
- * When a transfer completes early (i.e. when less data is received/sent in
303
- * any one packet than the transfer buffer allows for) then libusb is designed
304
- * to terminate the transfer immediately, not transferring or receiving any
305
- * more data unless other transfers have been queued by the user.
306
- *
307
- * On legacy platforms, libusb is unable to do this in all situations. After
308
- * the incomplete packet occurs, "surplus" data may be transferred. For recent
309
- * versions of libusb, this information is kept (the data length of the
310
- * transfer is updated) and, for device-to-host transfers, any surplus data was
311
- * added to the buffer. Still, this is not a nice solution because it loses the
312
- * information about the end of the short packet, and the user probably wanted
313
- * that surplus data to arrive in the next logical transfer.
314
- *
315
- * \section zlp Zero length packets
316
- *
317
- * - libusb is able to send a packet of zero length to an endpoint simply by
318
- * submitting a transfer of zero length.
319
- * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
320
- * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently supported on Linux,
321
- * Darwin and Windows (WinUSB).
322
- */
323
-
324
- /**
325
- * \page libusb_contexts Contexts
326
- *
327
- * It is possible that libusb may be used simultaneously from two independent
328
- * libraries linked into the same executable. For example, if your application
329
- * has a plugin-like system which allows the user to dynamically load a range
330
- * of modules into your program, it is feasible that two independently
331
- * developed modules may both use libusb.
332
- *
333
- * libusb is written to allow for these multiple user scenarios. The two
334
- * "instances" of libusb will not interfere: an option set by one user will have
335
- * no effect the same option for other users, other users can continue using
336
- * libusb after one of them calls libusb_exit(), etc.
337
- *
338
- * This is made possible through libusb's <em>context</em> concept. When you
339
- * call libusb_init_context(), you are (optionally) given a context. You can then pass
340
- * this context pointer back into future libusb functions.
341
- *
342
- * In order to keep things simple for more simplistic applications, it is
343
- * legal to pass NULL to all functions requiring a context pointer (as long as
344
- * you're sure no other code will attempt to use libusb from the same process).
345
- * When you pass NULL, the default context will be used. The default context
346
- * is created the first time a process calls libusb_init_context() when no other
347
- * context is alive. Contexts are destroyed during libusb_exit().
348
- *
349
- * The default context is reference-counted and can be shared. That means that
350
- * if libusb_init_context(NULL, x, y) is called twice within the same process, the two
351
- * users end up sharing the same context. The deinitialization and freeing of
352
- * the default context will only happen when the last user calls libusb_exit().
353
- * In other words, the default context is created and initialized when its
354
- * reference count goes from 0 to 1, and is deinitialized and destroyed when
355
- * its reference count goes from 1 to 0.
356
- *
357
- * You may be wondering why only a subset of libusb functions require a
358
- * context pointer in their function definition. Internally, libusb stores
359
- * context pointers in other objects (e.g. libusb_device instances) and hence
360
- * can infer the context from those objects.
361
- */
362
-
363
- /**
364
- * \page libusb_api Application Programming Interface
365
- *
366
- * This is the complete list of libusb functions, structures and
367
- * enumerations in alphabetical order.
368
- *
369
- * \section Functions
370
- * - libusb_alloc_streams()
371
- * - libusb_alloc_transfer()
372
- * - libusb_attach_kernel_driver()
373
- * - libusb_bulk_transfer()
374
- * - libusb_cancel_transfer()
375
- * - libusb_claim_interface()
376
- * - libusb_clear_halt()
377
- * - libusb_close()
378
- * - libusb_control_transfer()
379
- * - libusb_control_transfer_get_data()
380
- * - libusb_control_transfer_get_setup()
381
- * - libusb_cpu_to_le16()
382
- * - libusb_detach_kernel_driver()
383
- * - libusb_dev_mem_alloc()
384
- * - libusb_dev_mem_free()
385
- * - libusb_error_name()
386
- * - libusb_event_handler_active()
387
- * - libusb_event_handling_ok()
388
- * - libusb_exit()
389
- * - libusb_fill_bulk_stream_transfer()
390
- * - libusb_fill_bulk_transfer()
391
- * - libusb_fill_control_setup()
392
- * - libusb_fill_control_transfer()
393
- * - libusb_fill_interrupt_transfer()
394
- * - libusb_fill_iso_transfer()
395
- * - libusb_free_bos_descriptor()
396
- * - libusb_free_config_descriptor()
397
- * - libusb_free_container_id_descriptor()
398
- * - libusb_free_device_list()
399
- * - libusb_free_pollfds()
400
- * - libusb_free_ss_endpoint_companion_descriptor()
401
- * - libusb_free_ss_usb_device_capability_descriptor()
402
- * - libusb_free_streams()
403
- * - libusb_free_transfer()
404
- * - libusb_free_usb_2_0_extension_descriptor()
405
- * - libusb_get_active_config_descriptor()
406
- * - libusb_get_bos_descriptor()
407
- * - libusb_get_bus_number()
408
- * - libusb_get_config_descriptor()
409
- * - libusb_get_config_descriptor_by_value()
410
- * - libusb_get_configuration()
411
- * - libusb_get_container_id_descriptor()
412
- * - libusb_get_descriptor()
413
- * - libusb_get_device()
414
- * - libusb_get_device_address()
415
- * - libusb_get_device_descriptor()
416
- * - libusb_get_device_list()
417
- * - libusb_get_device_speed()
418
- * - libusb_get_iso_packet_buffer()
419
- * - libusb_get_iso_packet_buffer_simple()
420
- * - libusb_get_max_alt_packet_size()
421
- * - libusb_get_max_iso_packet_size()
422
- * - libusb_get_max_packet_size()
423
- * - libusb_get_next_timeout()
424
- * - libusb_get_parent()
425
- * - libusb_get_pollfds()
426
- * - libusb_get_port_number()
427
- * - libusb_get_port_numbers()
428
- * - libusb_get_port_path()
429
- * - libusb_get_ss_endpoint_companion_descriptor()
430
- * - libusb_get_ss_usb_device_capability_descriptor()
431
- * - libusb_get_string_descriptor()
432
- * - libusb_get_string_descriptor_ascii()
433
- * - libusb_get_usb_2_0_extension_descriptor()
434
- * - libusb_get_version()
435
- * - libusb_handle_events()
436
- * - libusb_handle_events_completed()
437
- * - libusb_handle_events_locked()
438
- * - libusb_handle_events_timeout()
439
- * - libusb_handle_events_timeout_completed()
440
- * - libusb_has_capability()
441
- * - libusb_hotplug_deregister_callback()
442
- * - libusb_hotplug_register_callback()
443
- * - libusb_init()
444
- * - libusb_init_context()
445
- * - libusb_interrupt_event_handler()
446
- * - libusb_interrupt_transfer()
447
- * - libusb_kernel_driver_active()
448
- * - libusb_lock_events()
449
- * - libusb_lock_event_waiters()
450
- * - libusb_open()
451
- * - libusb_open_device_with_vid_pid()
452
- * - libusb_pollfds_handle_timeouts()
453
- * - libusb_ref_device()
454
- * - libusb_release_interface()
455
- * - libusb_reset_device()
456
- * - libusb_set_auto_detach_kernel_driver()
457
- * - libusb_set_configuration()
458
- * - libusb_set_debug()
459
- * - libusb_set_log_cb()
460
- * - libusb_set_interface_alt_setting()
461
- * - libusb_set_iso_packet_lengths()
462
- * - libusb_set_option()
463
- * - libusb_setlocale()
464
- * - libusb_set_pollfd_notifiers()
465
- * - libusb_strerror()
466
- * - libusb_submit_transfer()
467
- * - libusb_transfer_get_stream_id()
468
- * - libusb_transfer_set_stream_id()
469
- * - libusb_try_lock_events()
470
- * - libusb_unlock_events()
471
- * - libusb_unlock_event_waiters()
472
- * - libusb_unref_device()
473
- * - libusb_wait_for_event()
474
- * - libusb_wrap_sys_device()
475
- *
476
- * \section Structures
477
- * - libusb_bos_descriptor
478
- * - libusb_bos_dev_capability_descriptor
479
- * - libusb_config_descriptor
480
- * - libusb_container_id_descriptor
481
- * - \ref libusb_context
482
- * - libusb_control_setup
483
- * - \ref libusb_device
484
- * - libusb_device_descriptor
485
- * - \ref libusb_device_handle
486
- * - libusb_endpoint_descriptor
487
- * - libusb_interface
488
- * - libusb_interface_descriptor
489
- * - libusb_iso_packet_descriptor
490
- * - libusb_pollfd
491
- * - libusb_ss_endpoint_companion_descriptor
492
- * - libusb_ss_usb_device_capability_descriptor
493
- * - libusb_transfer
494
- * - libusb_usb_2_0_extension_descriptor
495
- * - libusb_version
496
- *
497
- * \section Enums
498
- * - \ref libusb_bos_type
499
- * - \ref libusb_capability
500
- * - \ref libusb_class_code
501
- * - \ref libusb_descriptor_type
502
- * - \ref libusb_endpoint_direction
503
- * - \ref libusb_endpoint_transfer_type
504
- * - \ref libusb_error
505
- * - \ref libusb_iso_sync_type
506
- * - \ref libusb_iso_usage_type
507
- * - \ref libusb_log_level
508
- * - \ref libusb_option
509
- * - \ref libusb_request_recipient
510
- * - \ref libusb_request_type
511
- * - \ref libusb_speed
512
- * - \ref libusb_ss_usb_device_capability_attributes
513
- * - \ref libusb_standard_request
514
- * - \ref libusb_supported_speed
515
- * - \ref libusb_transfer_flags
516
- * - \ref libusb_transfer_status
517
- * - \ref libusb_transfer_type
518
- * - \ref libusb_usb_2_0_extension_attributes
519
- */
520
-
521
- /**
522
- * @defgroup libusb_lib Library initialization/deinitialization
523
- * This page details how to initialize and deinitialize libusb. Initialization
524
- * must be performed before using any libusb functionality, and similarly you
525
- * must not call any libusb functions after deinitialization.
526
- */
527
-
528
- /**
529
- * @defgroup libusb_dev Device handling and enumeration
530
- * The functionality documented below is designed to help with the following
531
- * operations:
532
- * - Enumerating the USB devices currently attached to the system
533
- * - Choosing a device to operate from your software
534
- * - Opening and closing the chosen device
535
- *
536
- * \section nutshell In a nutshell...
537
- *
538
- * The description below really makes things sound more complicated than they
539
- * actually are. The following sequence of function calls will be suitable
540
- * for almost all scenarios and does not require you to have such a deep
541
- * understanding of the resource management issues:
542
- * \code
543
- // discover devices
544
- libusb_device **list;
545
- libusb_device *found = NULL;
546
- ssize_t cnt = libusb_get_device_list(NULL, &list);
547
- ssize_t i = 0;
548
- int err = 0;
549
- if (cnt < 0)
550
- error();
551
-
552
- for (i = 0; i < cnt; i++) {
553
- libusb_device *device = list[i];
554
- if (is_interesting(device)) {
555
- found = device;
556
- break;
557
- }
558
- }
559
-
560
- if (found) {
561
- libusb_device_handle *handle;
562
-
563
- err = libusb_open(found, &handle);
564
- if (err)
565
- error();
566
- // etc
567
- }
568
-
569
- libusb_free_device_list(list, 1);
570
- \endcode
571
- *
572
- * The two important points:
573
- * - You asked libusb_free_device_list() to unreference the devices (2nd
574
- * parameter)
575
- * - You opened the device before freeing the list and unreferencing the
576
- * devices
577
- *
578
- * If you ended up with a handle, you can now proceed to perform I/O on the
579
- * device.
580
- *
581
- * \section devshandles Devices and device handles
582
- * libusb has a concept of a USB device, represented by the
583
- * \ref libusb_device opaque type. A device represents a USB device that
584
- * is currently or was previously connected to the system. Using a reference
585
- * to a device, you can determine certain information about the device (e.g.
586
- * you can read the descriptor data).
587
- *
588
- * The libusb_get_device_list() function can be used to obtain a list of
589
- * devices currently connected to the system. This is known as device
590
- * discovery. Devices can also be discovered with the hotplug mechanism,
591
- * whereby a callback function registered with libusb_hotplug_register_callback()
592
- * will be called when a device of interest is connected or disconnected.
593
- *
594
- * Just because you have a reference to a device does not mean it is
595
- * necessarily usable. The device may have been unplugged, you may not have
596
- * permission to operate such device, or another program or driver may be
597
- * using the device.
598
- *
599
- * When you've found a device that you'd like to operate, you must ask
600
- * libusb to open the device using the libusb_open() function. Assuming
601
- * success, libusb then returns you a <em>device handle</em>
602
- * (a \ref libusb_device_handle pointer). All "real" I/O operations then
603
- * operate on the handle rather than the original device pointer.
604
- *
605
- * \section devref Device discovery and reference counting
606
- *
607
- * Device discovery (i.e. calling libusb_get_device_list()) returns a
608
- * freshly-allocated list of devices. The list itself must be freed when
609
- * you are done with it. libusb also needs to know when it is OK to free
610
- * the contents of the list - the devices themselves.
611
- *
612
- * To handle these issues, libusb provides you with two separate items:
613
- * - A function to free the list itself
614
- * - A reference counting system for the devices inside
615
- *
616
- * New devices presented by the libusb_get_device_list() function all have a
617
- * reference count of 1. You can increase and decrease reference count using
618
- * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
619
- * its reference count reaches 0.
620
- *
621
- * With the above information in mind, the process of opening a device can
622
- * be viewed as follows:
623
- * -# Discover devices using libusb_get_device_list() or libusb_hotplug_register_callback().
624
- * -# Choose the device that you want to operate, and call libusb_open().
625
- * -# Unref all devices in the discovered device list.
626
- * -# Free the discovered device list.
627
- *
628
- * The order is important - you must not unreference the device before
629
- * attempting to open it, because unreferencing it may destroy the device.
630
- *
631
- * For convenience, the libusb_free_device_list() function includes a
632
- * parameter to optionally unreference all the devices in the list before
633
- * freeing the list itself. This combines steps 3 and 4 above.
634
- *
635
- * As an implementation detail, libusb_open() actually adds a reference to
636
- * the device in question. This is because the device remains available
637
- * through the handle via libusb_get_device(). The reference is deleted during
638
- * libusb_close().
639
- */
640
-
641
- /** @defgroup libusb_misc Miscellaneous */
642
-
643
- /* we traverse usbfs without knowing how many devices we are going to find.
644
- * so we create this discovered_devs model which is similar to a linked-list
645
- * which grows when required. it can be freed once discovery has completed,
646
- * eliminating the need for a list node in the libusb_device structure
647
- * itself. */
648
- #define DISCOVERED_DEVICES_SIZE_STEP 16
649
-
650
- static struct discovered_devs *discovered_devs_alloc(void)
651
- {
652
- struct discovered_devs *ret =
653
- malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
654
-
655
- if (ret) {
656
- ret->len = 0;
657
- ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
658
- }
659
- return ret;
660
- }
661
-
662
- static void discovered_devs_free(struct discovered_devs *discdevs)
663
- {
664
- size_t i;
665
-
666
- for (i = 0; i < discdevs->len; i++)
667
- libusb_unref_device(discdevs->devices[i]);
668
-
669
- free(discdevs);
670
- }
671
-
672
- /* append a device to the discovered devices collection. may realloc itself,
673
- * returning new discdevs. returns NULL on realloc failure. */
674
- struct discovered_devs *discovered_devs_append(
675
- struct discovered_devs *discdevs, struct libusb_device *dev)
676
- {
677
- size_t len = discdevs->len;
678
- size_t capacity;
679
- struct discovered_devs *new_discdevs;
680
-
681
- /* if there is space, just append the device */
682
- if (len < discdevs->capacity) {
683
- discdevs->devices[len] = libusb_ref_device(dev);
684
- discdevs->len++;
685
- return discdevs;
686
- }
687
-
688
- /* exceeded capacity, need to grow */
689
- usbi_dbg(DEVICE_CTX(dev), "need to increase capacity");
690
- capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
691
- /* can't use usbi_reallocf here because in failure cases it would
692
- * free the existing discdevs without unreferencing its devices. */
693
- new_discdevs = realloc(discdevs,
694
- sizeof(*discdevs) + (sizeof(void *) * capacity));
695
- if (!new_discdevs) {
696
- discovered_devs_free(discdevs);
697
- return NULL;
698
- }
699
-
700
- discdevs = new_discdevs;
701
- discdevs->capacity = capacity;
702
- discdevs->devices[len] = libusb_ref_device(dev);
703
- discdevs->len++;
704
-
705
- return discdevs;
706
- }
707
-
708
- /* Allocate a new device with a specific session ID. The returned device has
709
- * a reference count of 1. */
710
- struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
711
- unsigned long session_id)
712
- {
713
- size_t priv_size = usbi_backend.device_priv_size;
714
- struct libusb_device *dev = calloc(1, PTR_ALIGN(sizeof(*dev)) + priv_size);
715
-
716
- if (!dev)
717
- return NULL;
718
-
719
- usbi_atomic_store(&dev->refcnt, 1);
720
-
721
- dev->ctx = ctx;
722
- dev->session_data = session_id;
723
- dev->speed = LIBUSB_SPEED_UNKNOWN;
724
-
725
- if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
726
- usbi_connect_device(dev);
727
-
728
- return dev;
729
- }
730
-
731
- void usbi_connect_device(struct libusb_device *dev)
732
- {
733
- struct libusb_context *ctx = DEVICE_CTX(dev);
734
-
735
- usbi_atomic_store(&dev->attached, 1);
736
-
737
- usbi_mutex_lock(&dev->ctx->usb_devs_lock);
738
- list_add(&dev->list, &dev->ctx->usb_devs);
739
- usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
740
-
741
- usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED);
742
- }
743
-
744
- void usbi_disconnect_device(struct libusb_device *dev)
745
- {
746
- struct libusb_context *ctx = DEVICE_CTX(dev);
747
-
748
- usbi_atomic_store(&dev->attached, 0);
749
-
750
- usbi_mutex_lock(&ctx->usb_devs_lock);
751
- list_del(&dev->list);
752
- usbi_mutex_unlock(&ctx->usb_devs_lock);
753
-
754
- usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);
755
- }
756
-
757
- /* Perform some final sanity checks on a newly discovered device. If this
758
- * function fails (negative return code), the device should not be added
759
- * to the discovered device list. */
760
- int usbi_sanitize_device(struct libusb_device *dev)
761
- {
762
- uint8_t num_configurations;
763
-
764
- if (dev->device_descriptor.bLength != LIBUSB_DT_DEVICE_SIZE ||
765
- dev->device_descriptor.bDescriptorType != LIBUSB_DT_DEVICE) {
766
- usbi_err(DEVICE_CTX(dev), "invalid device descriptor");
767
- return LIBUSB_ERROR_IO;
768
- }
769
-
770
- num_configurations = dev->device_descriptor.bNumConfigurations;
771
- if (num_configurations > USB_MAXCONFIG) {
772
- usbi_err(DEVICE_CTX(dev), "too many configurations");
773
- return LIBUSB_ERROR_IO;
774
- } else if (0 == num_configurations) {
775
- usbi_dbg(DEVICE_CTX(dev), "zero configurations, maybe an unauthorized device");
776
- }
777
-
778
- return 0;
779
- }
780
-
781
- /* Examine libusb's internal list of known devices, looking for one with
782
- * a specific session ID. Returns the matching device if it was found, and
783
- * NULL otherwise. */
784
- struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
785
- unsigned long session_id)
786
- {
787
- struct libusb_device *dev;
788
- struct libusb_device *ret = NULL;
789
-
790
- usbi_mutex_lock(&ctx->usb_devs_lock);
791
- for_each_device(ctx, dev) {
792
- if (dev->session_data == session_id) {
793
- ret = libusb_ref_device(dev);
794
- break;
795
- }
796
- }
797
- usbi_mutex_unlock(&ctx->usb_devs_lock);
798
-
799
- return ret;
800
- }
801
-
802
- /** @ingroup libusb_dev
803
- * Returns a list of USB devices currently attached to the system. This is
804
- * your entry point into finding a USB device to operate.
805
- *
806
- * You are expected to unreference all the devices when you are done with
807
- * them, and then free the list with libusb_free_device_list(). Note that
808
- * libusb_free_device_list() can unref all the devices for you. Be careful
809
- * not to unreference a device you are about to open until after you have
810
- * opened it.
811
- *
812
- * This return value of this function indicates the number of devices in
813
- * the resultant list. The list is actually one element larger, as it is
814
- * NULL-terminated.
815
- *
816
- * \param ctx the context to operate on, or NULL for the default context
817
- * \param list output location for a list of devices. Must be later freed with
818
- * libusb_free_device_list().
819
- * \returns the number of devices in the outputted list, or any
820
- * \ref libusb_error according to errors encountered by the backend.
821
- */
822
- ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
823
- libusb_device ***list)
824
- {
825
- struct discovered_devs *discdevs = discovered_devs_alloc();
826
- struct libusb_device **ret;
827
- int r = 0;
828
- ssize_t i, len;
829
-
830
- usbi_dbg(ctx, " ");
831
-
832
- if (!discdevs)
833
- return LIBUSB_ERROR_NO_MEM;
834
-
835
- ctx = usbi_get_context(ctx);
836
-
837
- if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
838
- /* backend provides hotplug support */
839
- struct libusb_device *dev;
840
-
841
- if (usbi_backend.hotplug_poll)
842
- usbi_backend.hotplug_poll();
843
-
844
- usbi_mutex_lock(&ctx->usb_devs_lock);
845
- for_each_device(ctx, dev) {
846
- discdevs = discovered_devs_append(discdevs, dev);
847
-
848
- if (!discdevs) {
849
- r = LIBUSB_ERROR_NO_MEM;
850
- break;
851
- }
852
- }
853
- usbi_mutex_unlock(&ctx->usb_devs_lock);
854
- } else {
855
- /* backend does not provide hotplug support */
856
- r = usbi_backend.get_device_list(ctx, &discdevs);
857
- }
858
-
859
- if (r < 0) {
860
- len = r;
861
- goto out;
862
- }
863
-
864
- /* convert discovered_devs into a list */
865
- len = (ssize_t)discdevs->len;
866
- ret = calloc((size_t)len + 1, sizeof(struct libusb_device *));
867
- if (!ret) {
868
- len = LIBUSB_ERROR_NO_MEM;
869
- goto out;
870
- }
871
-
872
- ret[len] = NULL;
873
- for (i = 0; i < len; i++) {
874
- struct libusb_device *dev = discdevs->devices[i];
875
- ret[i] = libusb_ref_device(dev);
876
- }
877
- *list = ret;
878
-
879
- out:
880
- if (discdevs)
881
- discovered_devs_free(discdevs);
882
- return len;
883
- }
884
-
885
- /** \ingroup libusb_dev
886
- * Frees a list of devices previously discovered using
887
- * libusb_get_device_list(). If the unref_devices parameter is set, the
888
- * reference count of each device in the list is decremented by 1.
889
- * \param list the list to free
890
- * \param unref_devices whether to unref the devices in the list
891
- */
892
- void API_EXPORTED libusb_free_device_list(libusb_device **list,
893
- int unref_devices)
894
- {
895
- if (!list)
896
- return;
897
-
898
- if (unref_devices) {
899
- int i = 0;
900
- struct libusb_device *dev;
901
-
902
- while ((dev = list[i++]) != NULL)
903
- libusb_unref_device(dev);
904
- }
905
- free(list);
906
- }
907
-
908
- /** \ingroup libusb_dev
909
- * Get the number of the bus that a device is connected to.
910
- * \param dev a device
911
- * \returns the bus number
912
- */
913
- uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
914
- {
915
- return dev->bus_number;
916
- }
917
-
918
- /** \ingroup libusb_dev
919
- * Get the number of the port that a device is connected to.
920
- * Unless the OS does something funky, or you are hot-plugging USB extension cards,
921
- * the port number returned by this call is usually guaranteed to be uniquely tied
922
- * to a physical port, meaning that different devices plugged on the same physical
923
- * port should return the same port number.
924
- *
925
- * But outside of this, there is no guarantee that the port number returned by this
926
- * call will remain the same, or even match the order in which ports have been
927
- * numbered by the HUB/HCD manufacturer.
928
- *
929
- * \param dev a device
930
- * \returns the port number (0 if not available)
931
- */
932
- uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
933
- {
934
- return dev->port_number;
935
- }
936
-
937
- /** \ingroup libusb_dev
938
- * Get the list of all port numbers from root for the specified device
939
- *
940
- * Since version 1.0.16, \ref LIBUSBX_API_VERSION >= 0x01000102
941
- * \param dev a device
942
- * \param port_numbers the array that should contain the port numbers
943
- * \param port_numbers_len the maximum length of the array. As per the USB 3.0
944
- * specs, the current maximum limit for the depth is 7.
945
- * \returns the number of elements filled
946
- * \returns \ref LIBUSB_ERROR_OVERFLOW if the array is too small
947
- */
948
- int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
949
- uint8_t *port_numbers, int port_numbers_len)
950
- {
951
- int i = port_numbers_len;
952
- struct libusb_context *ctx = DEVICE_CTX(dev);
953
-
954
- if (port_numbers_len <= 0)
955
- return LIBUSB_ERROR_INVALID_PARAM;
956
-
957
- /* HCDs can be listed as devices with port #0 */
958
- while((dev) && (dev->port_number != 0)) {
959
- if (--i < 0) {
960
- usbi_warn(ctx, "port numbers array is too small");
961
- return LIBUSB_ERROR_OVERFLOW;
962
- }
963
- port_numbers[i] = dev->port_number;
964
- dev = dev->parent_dev;
965
- }
966
- if (i < port_numbers_len)
967
- memmove(port_numbers, &port_numbers[i], (size_t)(port_numbers_len - i));
968
- return port_numbers_len - i;
969
- }
970
-
971
- /** \ingroup libusb_dev
972
- * \deprecated Please use \ref libusb_get_port_numbers() instead.
973
- */
974
- int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
975
- uint8_t *port_numbers, uint8_t port_numbers_len)
976
- {
977
- UNUSED(ctx);
978
-
979
- return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
980
- }
981
-
982
- /** \ingroup libusb_dev
983
- * Get the the parent from the specified device.
984
- * \param dev a device
985
- * \returns the device parent or NULL if not available
986
- * You should issue a \ref libusb_get_device_list() before calling this
987
- * function and make sure that you only access the parent before issuing
988
- * \ref libusb_free_device_list(). The reason is that libusb currently does
989
- * not maintain a permanent list of device instances, and therefore can
990
- * only guarantee that parents are fully instantiated within a
991
- * libusb_get_device_list() - libusb_free_device_list() block.
992
- */
993
- DEFAULT_VISIBILITY
994
- libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
995
- {
996
- return dev->parent_dev;
997
- }
998
-
999
- /** \ingroup libusb_dev
1000
- * Get the address of the device on the bus it is connected to.
1001
- * \param dev a device
1002
- * \returns the device address
1003
- */
1004
- uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
1005
- {
1006
- return dev->device_address;
1007
- }
1008
-
1009
- /** \ingroup libusb_dev
1010
- * Get the negotiated connection speed for a device.
1011
- * \param dev a device
1012
- * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
1013
- * the OS doesn't know or doesn't support returning the negotiated speed.
1014
- */
1015
- int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
1016
- {
1017
- return (int)(dev->speed);
1018
- }
1019
-
1020
- static const struct libusb_endpoint_descriptor *find_endpoint(
1021
- struct libusb_config_descriptor *config, unsigned char endpoint)
1022
- {
1023
- int iface_idx;
1024
- for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
1025
- const struct libusb_interface *iface = &config->interface[iface_idx];
1026
- int altsetting_idx;
1027
-
1028
- for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
1029
- altsetting_idx++) {
1030
- const struct libusb_interface_descriptor *altsetting
1031
- = &iface->altsetting[altsetting_idx];
1032
- int ep_idx;
1033
-
1034
- for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
1035
- const struct libusb_endpoint_descriptor *ep =
1036
- &altsetting->endpoint[ep_idx];
1037
- if (ep->bEndpointAddress == endpoint)
1038
- return ep;
1039
- }
1040
- }
1041
- }
1042
- return NULL;
1043
- }
1044
-
1045
- /** \ingroup libusb_dev
1046
- * Convenience function to retrieve the wMaxPacketSize value for a particular
1047
- * endpoint in the active device configuration.
1048
- *
1049
- * This function was originally intended to be of assistance when setting up
1050
- * isochronous transfers, but a design mistake resulted in this function
1051
- * instead. It simply returns the wMaxPacketSize value without considering
1052
- * its contents. If you're dealing with isochronous transfers, you probably
1053
- * want libusb_get_max_iso_packet_size() instead.
1054
- *
1055
- * \param dev a device
1056
- * \param endpoint address of the endpoint in question
1057
- * \returns the wMaxPacketSize value
1058
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1059
- * \returns \ref LIBUSB_ERROR_OTHER on other failure
1060
- */
1061
- int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
1062
- unsigned char endpoint)
1063
- {
1064
- struct libusb_config_descriptor *config;
1065
- const struct libusb_endpoint_descriptor *ep;
1066
- int r;
1067
-
1068
- r = libusb_get_active_config_descriptor(dev, &config);
1069
- if (r < 0) {
1070
- usbi_err(DEVICE_CTX(dev),
1071
- "could not retrieve active config descriptor");
1072
- return LIBUSB_ERROR_OTHER;
1073
- }
1074
-
1075
- ep = find_endpoint(config, endpoint);
1076
- if (!ep) {
1077
- r = LIBUSB_ERROR_NOT_FOUND;
1078
- goto out;
1079
- }
1080
-
1081
- r = ep->wMaxPacketSize;
1082
-
1083
- out:
1084
- libusb_free_config_descriptor(config);
1085
- return r;
1086
- }
1087
-
1088
- static const struct libusb_endpoint_descriptor *find_alt_endpoint(
1089
- struct libusb_config_descriptor *config,
1090
- int iface_idx, int altsetting_idx, unsigned char endpoint)
1091
- {
1092
- if (iface_idx >= config->bNumInterfaces) {
1093
- return NULL;
1094
- }
1095
-
1096
- const struct libusb_interface *iface = &config->interface[iface_idx];
1097
-
1098
- if (altsetting_idx >= iface->num_altsetting) {
1099
- return NULL;
1100
- }
1101
-
1102
- const struct libusb_interface_descriptor *altsetting
1103
- = &iface->altsetting[altsetting_idx];
1104
- int ep_idx;
1105
-
1106
- for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
1107
- const struct libusb_endpoint_descriptor *ep =
1108
- &altsetting->endpoint[ep_idx];
1109
- if (ep->bEndpointAddress == endpoint)
1110
- return ep;
1111
- }
1112
- return NULL;
1113
- }
1114
-
1115
- static int get_endpoint_max_packet_size(libusb_device *dev,
1116
- const struct libusb_endpoint_descriptor *ep)
1117
- {
1118
- struct libusb_ss_endpoint_companion_descriptor *ss_ep_cmp;
1119
- enum libusb_endpoint_transfer_type ep_type;
1120
- uint16_t val;
1121
- int r = 0;
1122
- int speed;
1123
-
1124
- speed = libusb_get_device_speed(dev);
1125
- if (speed >= LIBUSB_SPEED_SUPER) {
1126
- r = libusb_get_ss_endpoint_companion_descriptor(dev->ctx, ep, &ss_ep_cmp);
1127
- if (r == LIBUSB_SUCCESS) {
1128
- r = ss_ep_cmp->wBytesPerInterval;
1129
- libusb_free_ss_endpoint_companion_descriptor(ss_ep_cmp);
1130
- }
1131
- }
1132
-
1133
- /* If the device isn't a SuperSpeed device or retrieving the SS endpoint didn't worked. */
1134
- if (speed < LIBUSB_SPEED_SUPER || r < 0) {
1135
- val = ep->wMaxPacketSize;
1136
- ep_type = (enum libusb_endpoint_transfer_type) (ep->bmAttributes & 0x3);
1137
-
1138
- r = val & 0x07ff;
1139
- if (ep_type == LIBUSB_ENDPOINT_TRANSFER_TYPE_ISOCHRONOUS
1140
- || ep_type == LIBUSB_ENDPOINT_TRANSFER_TYPE_INTERRUPT)
1141
- r *= (1 + ((val >> 11) & 3));
1142
- }
1143
-
1144
- return r;
1145
- }
1146
-
1147
- /** \ingroup libusb_dev
1148
- * Calculate the maximum packet size which a specific endpoint is capable is
1149
- * sending or receiving in the duration of 1 microframe
1150
- *
1151
- * Only the active configuration is examined. The calculation is based on the
1152
- * wMaxPacketSize field in the endpoint descriptor as described in section
1153
- * 9.6.6 in the USB 2.0 specifications.
1154
- *
1155
- * If acting on an isochronous or interrupt endpoint, this function will
1156
- * multiply the value found in bits 0:10 by the number of transactions per
1157
- * microframe (determined by bits 11:12). Otherwise, this function just
1158
- * returns the numeric value found in bits 0:10. For USB 3.0 device, it
1159
- * will attempts to retrieve the Endpoint Companion Descriptor to return
1160
- * wBytesPerInterval.
1161
- *
1162
- * This function is useful for setting up isochronous transfers, for example
1163
- * you might pass the return value from this function to
1164
- * libusb_set_iso_packet_lengths() in order to set the length field of every
1165
- * isochronous packet in a transfer.
1166
- *
1167
- * This function only considers the first alternate setting of the interface.
1168
- * If the endpoint has different maximum packet sizes for different alternate
1169
- * settings, you probably want libusb_get_max_alt_packet_size() instead.
1170
- *
1171
- * Since v1.0.3.
1172
- *
1173
- * \param dev a device
1174
- * \param endpoint address of the endpoint in question
1175
- * \returns the maximum packet size which can be sent/received on this endpoint
1176
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1177
- * \returns \ref LIBUSB_ERROR_OTHER on other failure
1178
- * \see libusb_get_max_alt_packet_size
1179
- */
1180
- int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
1181
- unsigned char endpoint)
1182
- {
1183
- struct libusb_config_descriptor *config;
1184
- const struct libusb_endpoint_descriptor *ep;
1185
- int r;
1186
-
1187
- r = libusb_get_active_config_descriptor(dev, &config);
1188
- if (r < 0) {
1189
- usbi_err(DEVICE_CTX(dev),
1190
- "could not retrieve active config descriptor");
1191
- return LIBUSB_ERROR_OTHER;
1192
- }
1193
-
1194
- ep = find_endpoint(config, endpoint);
1195
- if (!ep) {
1196
- r = LIBUSB_ERROR_NOT_FOUND;
1197
- goto out;
1198
- }
1199
-
1200
- r = get_endpoint_max_packet_size(dev, ep);
1201
-
1202
- out:
1203
- libusb_free_config_descriptor(config);
1204
- return r;
1205
- }
1206
-
1207
- /** \ingroup libusb_dev
1208
- * Calculate the maximum packet size which a specific endpoint is capable of
1209
- * sending or receiving in the duration of 1 microframe
1210
- *
1211
- * Only the active configuration is examined. The calculation is based on the
1212
- * wMaxPacketSize field in the endpoint descriptor as described in section
1213
- * 9.6.6 in the USB 2.0 specifications.
1214
- *
1215
- * If acting on an isochronous or interrupt endpoint, this function will
1216
- * multiply the value found in bits 0:10 by the number of transactions per
1217
- * microframe (determined by bits 11:12). Otherwise, this function just
1218
- * returns the numeric value found in bits 0:10. For USB 3.0 device, it
1219
- * will attempts to retrieve the Endpoint Companion Descriptor to return
1220
- * wBytesPerInterval.
1221
- *
1222
- * This function is useful for setting up isochronous transfers, for example
1223
- * you might pass the return value from this function to
1224
- * libusb_set_iso_packet_lengths() in order to set the length field of every
1225
- * isochronous packet in a transfer.
1226
- *
1227
- * Since version 1.0.27, \ref LIBUSB_API_VERSION >= 0x0100010A
1228
- *
1229
- * \param dev a device
1230
- * \param interface_number the <tt>bInterfaceNumber</tt> of the interface
1231
- * the endpoint belongs to
1232
- * \param alternate_setting the <tt>bAlternateSetting</tt> of the interface
1233
- * \param endpoint address of the endpoint in question
1234
- * \returns the maximum packet size which can be sent/received on this endpoint
1235
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1236
- * \returns \ref LIBUSB_ERROR_OTHER on other failure
1237
- * \see libusb_get_max_iso_packet_size
1238
- */
1239
- int API_EXPORTED libusb_get_max_alt_packet_size(libusb_device *dev,
1240
- int interface_number, int alternate_setting, unsigned char endpoint)
1241
- {
1242
- struct libusb_config_descriptor *config;
1243
- const struct libusb_endpoint_descriptor *ep;
1244
- int r;
1245
-
1246
- r = libusb_get_active_config_descriptor(dev, &config);
1247
- if (r < 0) {
1248
- usbi_err(DEVICE_CTX(dev),
1249
- "could not retrieve active config descriptor");
1250
- return LIBUSB_ERROR_OTHER;
1251
- }
1252
-
1253
- ep = find_alt_endpoint(config, interface_number,
1254
- alternate_setting, endpoint);
1255
- if (!ep) {
1256
- r = LIBUSB_ERROR_NOT_FOUND;
1257
- goto out;
1258
- }
1259
-
1260
- r = get_endpoint_max_packet_size(dev, ep);
1261
-
1262
- out:
1263
- libusb_free_config_descriptor(config);
1264
- return r;
1265
- }
1266
-
1267
- /** \ingroup libusb_dev
1268
- * Increment the reference count of a device.
1269
- * \param dev the device to reference
1270
- * \returns the same device
1271
- */
1272
- DEFAULT_VISIBILITY
1273
- libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
1274
- {
1275
- long refcnt;
1276
-
1277
- refcnt = usbi_atomic_inc(&dev->refcnt);
1278
- assert(refcnt >= 2);
1279
-
1280
- return dev;
1281
- }
1282
-
1283
- /** \ingroup libusb_dev
1284
- * Decrement the reference count of a device. If the decrement operation
1285
- * causes the reference count to reach zero, the device shall be destroyed.
1286
- * \param dev the device to unreference
1287
- */
1288
- void API_EXPORTED libusb_unref_device(libusb_device *dev)
1289
- {
1290
- long refcnt;
1291
-
1292
- if (!dev)
1293
- return;
1294
-
1295
- refcnt = usbi_atomic_dec(&dev->refcnt);
1296
- assert(refcnt >= 0);
1297
-
1298
- if (refcnt == 0) {
1299
- usbi_dbg(DEVICE_CTX(dev), "destroy device %d.%d", dev->bus_number, dev->device_address);
1300
-
1301
- libusb_unref_device(dev->parent_dev);
1302
-
1303
- if (usbi_backend.destroy_device)
1304
- usbi_backend.destroy_device(dev);
1305
-
1306
- if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1307
- /* backend does not support hotplug */
1308
- usbi_disconnect_device(dev);
1309
- }
1310
-
1311
- free(dev);
1312
- }
1313
- }
1314
-
1315
- /** \ingroup libusb_dev
1316
- * Wrap a platform-specific system device handle and obtain a libusb device
1317
- * handle for the underlying device. The handle allows you to use libusb to
1318
- * perform I/O on the device in question.
1319
- *
1320
- * Call libusb_init_context with the LIBUSB_OPTION_NO_DEVICE_DISCOVERY
1321
- * option if you want to skip enumeration of USB devices. In particular, this
1322
- * might be needed on Android if you don't have authority to access USB
1323
- * devices in general. Setting this option with libusb_set_option is deprecated.
1324
- *
1325
- * On Linux, the system device handle must be a valid file descriptor opened
1326
- * on the device node.
1327
- *
1328
- * The system device handle must remain open until libusb_close() is called.
1329
- * The system device handle will not be closed by libusb_close().
1330
- *
1331
- * Internally, this function creates a temporary device and makes it
1332
- * available to you through libusb_get_device(). This device is destroyed
1333
- * during libusb_close(). The device shall not be opened through libusb_open().
1334
- *
1335
- * This is a non-blocking function; no requests are sent over the bus.
1336
- *
1337
- * Since version 1.0.23, \ref LIBUSB_API_VERSION >= 0x01000107
1338
- *
1339
- * \param ctx the context to operate on, or NULL for the default context
1340
- * \param sys_dev the platform-specific system device handle
1341
- * \param dev_handle output location for the returned device handle pointer. Only
1342
- * populated when the return code is 0.
1343
- * \returns 0 on success
1344
- * \returns \ref LIBUSB_ERROR_NO_MEM on memory allocation failure
1345
- * \returns \ref LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1346
- * \returns \ref LIBUSB_ERROR_NOT_SUPPORTED if the operation is not supported on this
1347
- * platform
1348
- * \returns another LIBUSB_ERROR code on other failure
1349
- */
1350
- int API_EXPORTED libusb_wrap_sys_device(libusb_context *ctx, intptr_t sys_dev,
1351
- libusb_device_handle **dev_handle)
1352
- {
1353
- struct libusb_device_handle *_dev_handle;
1354
- size_t priv_size = usbi_backend.device_handle_priv_size;
1355
- int r;
1356
-
1357
- usbi_dbg(ctx, "wrap_sys_device 0x%" PRIxPTR, (uintptr_t)sys_dev);
1358
-
1359
- ctx = usbi_get_context(ctx);
1360
-
1361
- if (!usbi_backend.wrap_sys_device)
1362
- return LIBUSB_ERROR_NOT_SUPPORTED;
1363
-
1364
- _dev_handle = calloc(1, PTR_ALIGN(sizeof(*_dev_handle)) + priv_size);
1365
- if (!_dev_handle)
1366
- return LIBUSB_ERROR_NO_MEM;
1367
-
1368
- usbi_mutex_init(&_dev_handle->lock);
1369
-
1370
- r = usbi_backend.wrap_sys_device(ctx, _dev_handle, sys_dev);
1371
- if (r < 0) {
1372
- usbi_dbg(ctx, "wrap_sys_device 0x%" PRIxPTR " returns %d", (uintptr_t)sys_dev, r);
1373
- usbi_mutex_destroy(&_dev_handle->lock);
1374
- free(_dev_handle);
1375
- return r;
1376
- }
1377
-
1378
- usbi_mutex_lock(&ctx->open_devs_lock);
1379
- list_add(&_dev_handle->list, &ctx->open_devs);
1380
- usbi_mutex_unlock(&ctx->open_devs_lock);
1381
- *dev_handle = _dev_handle;
1382
-
1383
- return 0;
1384
- }
1385
-
1386
- /** \ingroup libusb_dev
1387
- * Open a device and obtain a device handle. A handle allows you to perform
1388
- * I/O on the device in question.
1389
- *
1390
- * Internally, this function adds a reference to the device and makes it
1391
- * available to you through libusb_get_device(). This reference is removed
1392
- * during libusb_close().
1393
- *
1394
- * This is a non-blocking function; no requests are sent over the bus.
1395
- *
1396
- * \param dev the device to open
1397
- * \param dev_handle output location for the returned device handle pointer. Only
1398
- * populated when the return code is 0.
1399
- * \returns 0 on success
1400
- * \returns \ref LIBUSB_ERROR_NO_MEM on memory allocation failure
1401
- * \returns \ref LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1402
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1403
- * \returns another LIBUSB_ERROR code on other failure
1404
- */
1405
- int API_EXPORTED libusb_open(libusb_device *dev,
1406
- libusb_device_handle **dev_handle)
1407
- {
1408
- struct libusb_context *ctx = DEVICE_CTX(dev);
1409
- struct libusb_device_handle *_dev_handle;
1410
- size_t priv_size = usbi_backend.device_handle_priv_size;
1411
- int r;
1412
-
1413
- usbi_dbg(DEVICE_CTX(dev), "open %d.%d", dev->bus_number, dev->device_address);
1414
-
1415
- if (!usbi_atomic_load(&dev->attached))
1416
- return LIBUSB_ERROR_NO_DEVICE;
1417
-
1418
- _dev_handle = calloc(1, PTR_ALIGN(sizeof(*_dev_handle)) + priv_size);
1419
- if (!_dev_handle)
1420
- return LIBUSB_ERROR_NO_MEM;
1421
-
1422
- usbi_mutex_init(&_dev_handle->lock);
1423
-
1424
- _dev_handle->dev = libusb_ref_device(dev);
1425
-
1426
- r = usbi_backend.open(_dev_handle);
1427
- if (r < 0) {
1428
- usbi_dbg(DEVICE_CTX(dev), "open %d.%d returns %d", dev->bus_number, dev->device_address, r);
1429
- libusb_unref_device(dev);
1430
- usbi_mutex_destroy(&_dev_handle->lock);
1431
- free(_dev_handle);
1432
- return r;
1433
- }
1434
-
1435
- usbi_mutex_lock(&ctx->open_devs_lock);
1436
- list_add(&_dev_handle->list, &ctx->open_devs);
1437
- usbi_mutex_unlock(&ctx->open_devs_lock);
1438
- *dev_handle = _dev_handle;
1439
-
1440
- return 0;
1441
- }
1442
-
1443
- /** \ingroup libusb_dev
1444
- * Convenience function for finding a device with a particular
1445
- * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1446
- * for those scenarios where you are using libusb to knock up a quick test
1447
- * application - it allows you to avoid calling libusb_get_device_list() and
1448
- * worrying about traversing/freeing the list.
1449
- *
1450
- * This function has limitations and is hence not intended for use in real
1451
- * applications: if multiple devices have the same IDs it will only
1452
- * give you the first one, etc.
1453
- *
1454
- * \param ctx the context to operate on, or NULL for the default context
1455
- * \param vendor_id the idVendor value to search for
1456
- * \param product_id the idProduct value to search for
1457
- * \returns a device handle for the first found device, or NULL on error
1458
- * or if the device could not be found. */
1459
- DEFAULT_VISIBILITY
1460
- libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1461
- libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
1462
- {
1463
- struct libusb_device **devs;
1464
- struct libusb_device *found = NULL;
1465
- struct libusb_device *dev;
1466
- struct libusb_device_handle *dev_handle = NULL;
1467
- size_t i = 0;
1468
- int r;
1469
-
1470
- if (libusb_get_device_list(ctx, &devs) < 0)
1471
- return NULL;
1472
-
1473
- while ((dev = devs[i++]) != NULL) {
1474
- struct libusb_device_descriptor desc;
1475
- r = libusb_get_device_descriptor(dev, &desc);
1476
- if (r < 0)
1477
- goto out;
1478
- if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1479
- found = dev;
1480
- break;
1481
- }
1482
- }
1483
-
1484
- if (found) {
1485
- r = libusb_open(found, &dev_handle);
1486
- if (r < 0)
1487
- dev_handle = NULL;
1488
- }
1489
-
1490
- out:
1491
- libusb_free_device_list(devs, 1);
1492
- return dev_handle;
1493
- }
1494
-
1495
- static void do_close(struct libusb_context *ctx,
1496
- struct libusb_device_handle *dev_handle)
1497
- {
1498
- struct usbi_transfer *itransfer;
1499
- struct usbi_transfer *tmp;
1500
-
1501
- /* remove any transfers in flight that are for this device */
1502
- usbi_mutex_lock(&ctx->flying_transfers_lock);
1503
-
1504
- /* safe iteration because transfers may be being deleted */
1505
- for_each_transfer_safe(ctx, itransfer, tmp) {
1506
- struct libusb_transfer *transfer =
1507
- USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1508
- uint32_t state_flags;
1509
-
1510
- if (transfer->dev_handle != dev_handle)
1511
- continue;
1512
-
1513
- usbi_mutex_lock(&itransfer->lock);
1514
- state_flags = itransfer->state_flags;
1515
- usbi_mutex_unlock(&itransfer->lock);
1516
- if (!(state_flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1517
- usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1518
-
1519
- if (state_flags & USBI_TRANSFER_CANCELLING)
1520
- usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1521
- else
1522
- usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1523
- }
1524
-
1525
- /* remove from the list of in-flight transfers and make sure
1526
- * we don't accidentally use the device handle in the future
1527
- * (or that such accesses will be easily caught and identified as a crash)
1528
- */
1529
- list_del(&itransfer->list);
1530
- transfer->dev_handle = NULL;
1531
-
1532
- /* it is up to the user to free up the actual transfer struct. this is
1533
- * just making sure that we don't attempt to process the transfer after
1534
- * the device handle is invalid
1535
- */
1536
- usbi_dbg(ctx, "Removed transfer %p from the in-flight list because device handle %p closed",
1537
- (void *) transfer, (void *) dev_handle);
1538
- }
1539
- usbi_mutex_unlock(&ctx->flying_transfers_lock);
1540
-
1541
- usbi_mutex_lock(&ctx->open_devs_lock);
1542
- list_del(&dev_handle->list);
1543
- usbi_mutex_unlock(&ctx->open_devs_lock);
1544
-
1545
- usbi_backend.close(dev_handle);
1546
- libusb_unref_device(dev_handle->dev);
1547
- usbi_mutex_destroy(&dev_handle->lock);
1548
- free(dev_handle);
1549
- }
1550
-
1551
- /** \ingroup libusb_dev
1552
- * Close a device handle. Should be called on all open handles before your
1553
- * application exits.
1554
- *
1555
- * Internally, this function destroys the reference that was added by
1556
- * libusb_open() on the given device.
1557
- *
1558
- * This is a non-blocking function; no requests are sent over the bus.
1559
- *
1560
- * \param dev_handle the device handle to close
1561
- */
1562
- void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
1563
- {
1564
- struct libusb_context *ctx;
1565
- unsigned int event_flags;
1566
- int handling_events;
1567
-
1568
- if (!dev_handle)
1569
- return;
1570
- ctx = HANDLE_CTX(dev_handle);
1571
- usbi_dbg(ctx, " ");
1572
-
1573
- handling_events = usbi_handling_events(ctx);
1574
-
1575
- /* Similarly to libusb_open(), we want to interrupt all event handlers
1576
- * at this point. More importantly, we want to perform the actual close of
1577
- * the device while holding the event handling lock (preventing any other
1578
- * thread from doing event handling) because we will be removing a file
1579
- * descriptor from the polling loop. If this is being called by the current
1580
- * event handler, we can bypass the interruption code because we already
1581
- * hold the event handling lock. */
1582
-
1583
- if (!handling_events) {
1584
- /* Record that we are closing a device.
1585
- * Only signal an event if there are no prior pending events. */
1586
- usbi_mutex_lock(&ctx->event_data_lock);
1587
- event_flags = ctx->event_flags;
1588
- if (!ctx->device_close++)
1589
- ctx->event_flags |= USBI_EVENT_DEVICE_CLOSE;
1590
- if (!event_flags)
1591
- usbi_signal_event(&ctx->event);
1592
- usbi_mutex_unlock(&ctx->event_data_lock);
1593
-
1594
- /* take event handling lock */
1595
- libusb_lock_events(ctx);
1596
- }
1597
-
1598
- /* Close the device */
1599
- do_close(ctx, dev_handle);
1600
-
1601
- if (!handling_events) {
1602
- /* We're done with closing this device.
1603
- * Clear the event pipe if there are no further pending events. */
1604
- usbi_mutex_lock(&ctx->event_data_lock);
1605
- if (!--ctx->device_close)
1606
- ctx->event_flags &= ~USBI_EVENT_DEVICE_CLOSE;
1607
- if (!ctx->event_flags)
1608
- usbi_clear_event(&ctx->event);
1609
- usbi_mutex_unlock(&ctx->event_data_lock);
1610
-
1611
- /* Release event handling lock and wake up event waiters */
1612
- libusb_unlock_events(ctx);
1613
- }
1614
- }
1615
-
1616
- /** \ingroup libusb_dev
1617
- * Get the underlying device for a device handle. This function does not modify
1618
- * the reference count of the returned device, so do not feel compelled to
1619
- * unreference it when you are done.
1620
- * \param dev_handle a device handle
1621
- * \returns the underlying device
1622
- */
1623
- DEFAULT_VISIBILITY
1624
- libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
1625
- {
1626
- return dev_handle->dev;
1627
- }
1628
-
1629
- /** \ingroup libusb_dev
1630
- * Determine the bConfigurationValue of the currently active configuration.
1631
- *
1632
- * You could formulate your own control request to obtain this information,
1633
- * but this function has the advantage that it may be able to retrieve the
1634
- * information from operating system caches (no I/O involved).
1635
- *
1636
- * If the OS does not cache this information, then this function will block
1637
- * while a control transfer is submitted to retrieve the information.
1638
- *
1639
- * This function will return a value of 0 in the <tt>config</tt> output
1640
- * parameter if the device is in unconfigured state.
1641
- *
1642
- * \param dev_handle a device handle
1643
- * \param config output location for the bConfigurationValue of the active
1644
- * configuration (only valid for return code 0)
1645
- * \returns 0 on success
1646
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1647
- * \returns another LIBUSB_ERROR code on other failure
1648
- */
1649
- int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev_handle,
1650
- int *config)
1651
- {
1652
- int r = LIBUSB_ERROR_NOT_SUPPORTED;
1653
- uint8_t tmp = 0;
1654
- struct libusb_context *ctx = HANDLE_CTX(dev_handle);
1655
-
1656
- usbi_dbg(ctx, " ");
1657
- if (usbi_backend.get_configuration)
1658
- r = usbi_backend.get_configuration(dev_handle, &tmp);
1659
-
1660
- if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1661
- usbi_dbg(ctx, "falling back to control message");
1662
- r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN,
1663
- LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1664
- if (r == 1) {
1665
- r = 0;
1666
- } else if (r == 0) {
1667
- usbi_err(ctx, "zero bytes returned in ctrl transfer?");
1668
- r = LIBUSB_ERROR_IO;
1669
- } else {
1670
- usbi_dbg(ctx, "control failed, error %d", r);
1671
- }
1672
- }
1673
-
1674
- if (r == 0) {
1675
- usbi_dbg(ctx, "active config %u", tmp);
1676
- *config = (int)tmp;
1677
- }
1678
-
1679
- return r;
1680
- }
1681
-
1682
- /** \ingroup libusb_dev
1683
- * Set the active configuration for a device.
1684
- *
1685
- * The operating system may or may not have already set an active
1686
- * configuration on the device. It is up to your application to ensure the
1687
- * correct configuration is selected before you attempt to claim interfaces
1688
- * and perform other operations.
1689
- *
1690
- * If you call this function on a device already configured with the selected
1691
- * configuration, then this function will act as a lightweight device reset:
1692
- * it will issue a SET_CONFIGURATION request using the current configuration,
1693
- * causing most USB-related device state to be reset (altsetting reset to zero,
1694
- * endpoint halts cleared, toggles reset).
1695
- *
1696
- * Not all backends support setting the configuration from user space, which
1697
- * will be indicated by the return code \ref LIBUSB_ERROR_NOT_SUPPORTED. As this
1698
- * suggests that the platform is handling the device configuration itself,
1699
- * this error should generally be safe to ignore.
1700
- *
1701
- * You cannot change/reset configuration if your application has claimed
1702
- * interfaces. It is advised to set the desired configuration before claiming
1703
- * interfaces.
1704
- *
1705
- * Alternatively you can call libusb_release_interface() first. Note if you
1706
- * do things this way you must ensure that auto_detach_kernel_driver for
1707
- * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
1708
- * release the interface(s).
1709
- *
1710
- * You cannot change/reset configuration if other applications or drivers have
1711
- * claimed interfaces.
1712
- *
1713
- * A configuration value of -1 will put the device in unconfigured state.
1714
- * The USB specifications state that a configuration value of 0 does this,
1715
- * however buggy devices exist which actually have a configuration 0.
1716
- *
1717
- * You should always use this function rather than formulating your own
1718
- * SET_CONFIGURATION control request. This is because the underlying operating
1719
- * system needs to know when such changes happen.
1720
- *
1721
- * This is a blocking function.
1722
- *
1723
- * \param dev_handle a device handle
1724
- * \param configuration the bConfigurationValue of the configuration you
1725
- * wish to activate, or -1 if you wish to put the device in an unconfigured
1726
- * state
1727
- * \returns 0 on success
1728
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1729
- * \returns \ref LIBUSB_ERROR_BUSY if interfaces are currently claimed
1730
- * \returns \ref LIBUSB_ERROR_NOT_SUPPORTED if setting or changing the configuration
1731
- * is not supported by the backend
1732
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1733
- * \returns another LIBUSB_ERROR code on other failure
1734
- * \see libusb_set_auto_detach_kernel_driver()
1735
- */
1736
- int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev_handle,
1737
- int configuration)
1738
- {
1739
- usbi_dbg(HANDLE_CTX(dev_handle), "configuration %d", configuration);
1740
- if (configuration < -1 || configuration > (int)UINT8_MAX)
1741
- return LIBUSB_ERROR_INVALID_PARAM;
1742
- return usbi_backend.set_configuration(dev_handle, configuration);
1743
- }
1744
-
1745
- /** \ingroup libusb_dev
1746
- * Claim an interface on a given device handle. You must claim the interface
1747
- * you wish to use before you can perform I/O on any of its endpoints.
1748
- *
1749
- * It is legal to attempt to claim an already-claimed interface, in which
1750
- * case libusb just returns 0 without doing anything.
1751
- *
1752
- * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
1753
- * will be detached if necessary, on failure the detach error is returned.
1754
- *
1755
- * Claiming of interfaces is a purely logical operation; it does not cause
1756
- * any requests to be sent over the bus. Interface claiming is used to
1757
- * instruct the underlying operating system that your application wishes
1758
- * to take ownership of the interface.
1759
- *
1760
- * This is a non-blocking function.
1761
- *
1762
- * \param dev_handle a device handle
1763
- * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1764
- * wish to claim
1765
- * \returns 0 on success
1766
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1767
- * \returns \ref LIBUSB_ERROR_BUSY if another program or driver has claimed the
1768
- * interface
1769
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1770
- * \returns a LIBUSB_ERROR code on other failure
1771
- * \see libusb_set_auto_detach_kernel_driver()
1772
- */
1773
- int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev_handle,
1774
- int interface_number)
1775
- {
1776
- int r = 0;
1777
-
1778
- usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
1779
- if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
1780
- return LIBUSB_ERROR_INVALID_PARAM;
1781
-
1782
- if (!usbi_atomic_load(&dev_handle->dev->attached))
1783
- return LIBUSB_ERROR_NO_DEVICE;
1784
-
1785
- usbi_mutex_lock(&dev_handle->lock);
1786
- if (dev_handle->claimed_interfaces & (1U << interface_number))
1787
- goto out;
1788
-
1789
- r = usbi_backend.claim_interface(dev_handle, (uint8_t)interface_number);
1790
- if (r == 0)
1791
- dev_handle->claimed_interfaces |= 1U << interface_number;
1792
-
1793
- out:
1794
- usbi_mutex_unlock(&dev_handle->lock);
1795
- return r;
1796
- }
1797
-
1798
- /** \ingroup libusb_dev
1799
- * Release an interface previously claimed with libusb_claim_interface(). You
1800
- * should release all claimed interfaces before closing a device handle.
1801
- *
1802
- * This is a blocking function. A SET_INTERFACE control request will be sent
1803
- * to the device, resetting interface state to the first alternate setting.
1804
- *
1805
- * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
1806
- * driver will be re-attached after releasing the interface.
1807
- *
1808
- * \param dev_handle a device handle
1809
- * \param interface_number the <tt>bInterfaceNumber</tt> of the
1810
- * previously-claimed interface
1811
- * \returns 0 on success
1812
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1813
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1814
- * \returns another LIBUSB_ERROR code on other failure
1815
- * \see libusb_set_auto_detach_kernel_driver()
1816
- */
1817
- int API_EXPORTED libusb_release_interface(libusb_device_handle *dev_handle,
1818
- int interface_number)
1819
- {
1820
- int r;
1821
-
1822
- usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
1823
- if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
1824
- return LIBUSB_ERROR_INVALID_PARAM;
1825
-
1826
- usbi_mutex_lock(&dev_handle->lock);
1827
- if (!(dev_handle->claimed_interfaces & (1U << interface_number))) {
1828
- r = LIBUSB_ERROR_NOT_FOUND;
1829
- goto out;
1830
- }
1831
-
1832
- r = usbi_backend.release_interface(dev_handle, (uint8_t)interface_number);
1833
- if (r == 0)
1834
- dev_handle->claimed_interfaces &= ~(1U << interface_number);
1835
-
1836
- out:
1837
- usbi_mutex_unlock(&dev_handle->lock);
1838
- return r;
1839
- }
1840
-
1841
- /** \ingroup libusb_dev
1842
- * Activate an alternate setting for an interface. The interface must have
1843
- * been previously claimed with libusb_claim_interface().
1844
- *
1845
- * You should always use this function rather than formulating your own
1846
- * SET_INTERFACE control request. This is because the underlying operating
1847
- * system needs to know when such changes happen.
1848
- *
1849
- * This is a blocking function.
1850
- *
1851
- * \param dev_handle a device handle
1852
- * \param interface_number the <tt>bInterfaceNumber</tt> of the
1853
- * previously-claimed interface
1854
- * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1855
- * setting to activate
1856
- * \returns 0 on success
1857
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1858
- * requested alternate setting does not exist
1859
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1860
- * \returns another LIBUSB_ERROR code on other failure
1861
- */
1862
- int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev_handle,
1863
- int interface_number, int alternate_setting)
1864
- {
1865
- usbi_dbg(HANDLE_CTX(dev_handle), "interface %d altsetting %d",
1866
- interface_number, alternate_setting);
1867
- if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
1868
- return LIBUSB_ERROR_INVALID_PARAM;
1869
- if (alternate_setting < 0 || alternate_setting > (int)UINT8_MAX)
1870
- return LIBUSB_ERROR_INVALID_PARAM;
1871
-
1872
- if (!usbi_atomic_load(&dev_handle->dev->attached)) {
1873
- return LIBUSB_ERROR_NO_DEVICE;
1874
- }
1875
-
1876
- usbi_mutex_lock(&dev_handle->lock);
1877
- if (!(dev_handle->claimed_interfaces & (1U << interface_number))) {
1878
- usbi_mutex_unlock(&dev_handle->lock);
1879
- return LIBUSB_ERROR_NOT_FOUND;
1880
- }
1881
- usbi_mutex_unlock(&dev_handle->lock);
1882
-
1883
- return usbi_backend.set_interface_altsetting(dev_handle,
1884
- (uint8_t)interface_number, (uint8_t)alternate_setting);
1885
- }
1886
-
1887
- /** \ingroup libusb_dev
1888
- * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1889
- * are unable to receive or transmit data until the halt condition is stalled.
1890
- *
1891
- * You should cancel all pending transfers before attempting to clear the halt
1892
- * condition.
1893
- *
1894
- * This is a blocking function.
1895
- *
1896
- * \param dev_handle a device handle
1897
- * \param endpoint the endpoint to clear halt status
1898
- * \returns 0 on success
1899
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1900
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1901
- * \returns another LIBUSB_ERROR code on other failure
1902
- */
1903
- int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev_handle,
1904
- unsigned char endpoint)
1905
- {
1906
- usbi_dbg(HANDLE_CTX(dev_handle), "endpoint 0x%x", endpoint);
1907
- if (!usbi_atomic_load(&dev_handle->dev->attached))
1908
- return LIBUSB_ERROR_NO_DEVICE;
1909
-
1910
- return usbi_backend.clear_halt(dev_handle, endpoint);
1911
- }
1912
-
1913
- /** \ingroup libusb_dev
1914
- * Perform a USB port reset to reinitialize a device. The system will attempt
1915
- * to restore the previous configuration and alternate settings after the
1916
- * reset has completed.
1917
- *
1918
- * If the reset fails, the descriptors change, or the previous state cannot be
1919
- * restored, the device will appear to be disconnected and reconnected. This
1920
- * means that the device handle is no longer valid (you should close it) and
1921
- * rediscover the device. A return code of \ref LIBUSB_ERROR_NOT_FOUND indicates
1922
- * when this is the case.
1923
- *
1924
- * This is a blocking function which usually incurs a noticeable delay.
1925
- *
1926
- * \param dev_handle a handle of the device to reset
1927
- * \returns 0 on success
1928
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1929
- * device has been disconnected
1930
- * \returns another LIBUSB_ERROR code on other failure
1931
- */
1932
- int API_EXPORTED libusb_reset_device(libusb_device_handle *dev_handle)
1933
- {
1934
- usbi_dbg(HANDLE_CTX(dev_handle), " ");
1935
- if (!usbi_atomic_load(&dev_handle->dev->attached))
1936
- return LIBUSB_ERROR_NO_DEVICE;
1937
-
1938
- if (usbi_backend.reset_device)
1939
- return usbi_backend.reset_device(dev_handle);
1940
- else
1941
- return LIBUSB_ERROR_NOT_SUPPORTED;
1942
- }
1943
-
1944
- /** \ingroup libusb_asyncio
1945
- * Allocate up to num_streams usb bulk streams on the specified endpoints. This
1946
- * function takes an array of endpoints rather then a single endpoint because
1947
- * some protocols require that endpoints are setup with similar stream ids.
1948
- * All endpoints passed in must belong to the same interface.
1949
- *
1950
- * Note this function may return less streams then requested. Also note that the
1951
- * same number of streams are allocated for each endpoint in the endpoint array.
1952
- *
1953
- * Stream id 0 is reserved, and should not be used to communicate with devices.
1954
- * If libusb_alloc_streams() returns with a value of N, you may use stream ids
1955
- * 1 to N.
1956
- *
1957
- * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1958
- *
1959
- * \param dev_handle a device handle
1960
- * \param num_streams number of streams to try to allocate
1961
- * \param endpoints array of endpoints to allocate streams on
1962
- * \param num_endpoints length of the endpoints array
1963
- * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
1964
- */
1965
- int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev_handle,
1966
- uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1967
- {
1968
- usbi_dbg(HANDLE_CTX(dev_handle), "streams %u eps %d", (unsigned)num_streams, num_endpoints);
1969
-
1970
- if (!num_streams || !endpoints || num_endpoints <= 0)
1971
- return LIBUSB_ERROR_INVALID_PARAM;
1972
-
1973
- if (!usbi_atomic_load(&dev_handle->dev->attached))
1974
- return LIBUSB_ERROR_NO_DEVICE;
1975
-
1976
- if (usbi_backend.alloc_streams)
1977
- return usbi_backend.alloc_streams(dev_handle, num_streams, endpoints,
1978
- num_endpoints);
1979
- else
1980
- return LIBUSB_ERROR_NOT_SUPPORTED;
1981
- }
1982
-
1983
- /** \ingroup libusb_asyncio
1984
- * Free usb bulk streams allocated with libusb_alloc_streams().
1985
- *
1986
- * Note streams are automatically free-ed when releasing an interface.
1987
- *
1988
- * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1989
- *
1990
- * \param dev_handle a device handle
1991
- * \param endpoints array of endpoints to free streams on
1992
- * \param num_endpoints length of the endpoints array
1993
- * \returns \ref LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1994
- */
1995
- int API_EXPORTED libusb_free_streams(libusb_device_handle *dev_handle,
1996
- unsigned char *endpoints, int num_endpoints)
1997
- {
1998
- usbi_dbg(HANDLE_CTX(dev_handle), "eps %d", num_endpoints);
1999
-
2000
- if (!endpoints || num_endpoints <= 0)
2001
- return LIBUSB_ERROR_INVALID_PARAM;
2002
-
2003
- if (!usbi_atomic_load(&dev_handle->dev->attached))
2004
- return LIBUSB_ERROR_NO_DEVICE;
2005
-
2006
- if (usbi_backend.free_streams)
2007
- return usbi_backend.free_streams(dev_handle, endpoints,
2008
- num_endpoints);
2009
- else
2010
- return LIBUSB_ERROR_NOT_SUPPORTED;
2011
- }
2012
-
2013
- /** \ingroup libusb_asyncio
2014
- * Attempts to allocate a block of persistent DMA memory suitable for transfers
2015
- * against the given device. If successful, will return a block of memory
2016
- * that is suitable for use as "buffer" in \ref libusb_transfer against this
2017
- * device. Using this memory instead of regular memory means that the host
2018
- * controller can use DMA directly into the buffer to increase performance, and
2019
- * also that transfers can no longer fail due to kernel memory fragmentation.
2020
- *
2021
- * Note that this means you should not modify this memory (or even data on
2022
- * the same cache lines) when a transfer is in progress, although it is legal
2023
- * to have several transfers going on within the same memory block.
2024
- *
2025
- * Will return NULL on failure. Many systems do not support such zero-copy
2026
- * and will always return NULL. Memory allocated with this function must be
2027
- * freed with \ref libusb_dev_mem_free. Specifically, this means that the
2028
- * flag \ref LIBUSB_TRANSFER_FREE_BUFFER cannot be used to free memory allocated
2029
- * with this function.
2030
- *
2031
- * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105
2032
- *
2033
- * \param dev_handle a device handle
2034
- * \param length size of desired data buffer
2035
- * \returns a pointer to the newly allocated memory, or NULL on failure
2036
- */
2037
- DEFAULT_VISIBILITY
2038
- unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle,
2039
- size_t length)
2040
- {
2041
- if (!usbi_atomic_load(&dev_handle->dev->attached))
2042
- return NULL;
2043
-
2044
- if (usbi_backend.dev_mem_alloc)
2045
- return usbi_backend.dev_mem_alloc(dev_handle, length);
2046
- else
2047
- return NULL;
2048
- }
2049
-
2050
- /** \ingroup libusb_asyncio
2051
- * Free device memory allocated with libusb_dev_mem_alloc().
2052
- *
2053
- * \param dev_handle a device handle
2054
- * \param buffer pointer to the previously allocated memory
2055
- * \param length size of previously allocated memory
2056
- * \returns \ref LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
2057
- */
2058
- int API_EXPORTED libusb_dev_mem_free(libusb_device_handle *dev_handle,
2059
- unsigned char *buffer, size_t length)
2060
- {
2061
- if (usbi_backend.dev_mem_free)
2062
- return usbi_backend.dev_mem_free(dev_handle, buffer, length);
2063
- else
2064
- return LIBUSB_ERROR_NOT_SUPPORTED;
2065
- }
2066
-
2067
- /** \ingroup libusb_dev
2068
- * Determine if a kernel driver is active on an interface. If a kernel driver
2069
- * is active, you cannot claim the interface, and libusb will be unable to
2070
- * perform I/O.
2071
- *
2072
- * This functionality is not available on Windows.
2073
- *
2074
- * \param dev_handle a device handle
2075
- * \param interface_number the interface to check
2076
- * \returns 0 if no kernel driver is active
2077
- * \returns 1 if a kernel driver is active
2078
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
2079
- * \returns \ref LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
2080
- * is not available
2081
- * \returns another LIBUSB_ERROR code on other failure
2082
- * \see libusb_detach_kernel_driver()
2083
- */
2084
- int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev_handle,
2085
- int interface_number)
2086
- {
2087
- usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
2088
-
2089
- if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
2090
- return LIBUSB_ERROR_INVALID_PARAM;
2091
-
2092
- if (!usbi_atomic_load(&dev_handle->dev->attached))
2093
- return LIBUSB_ERROR_NO_DEVICE;
2094
-
2095
- if (usbi_backend.kernel_driver_active)
2096
- return usbi_backend.kernel_driver_active(dev_handle, (uint8_t)interface_number);
2097
- else
2098
- return LIBUSB_ERROR_NOT_SUPPORTED;
2099
- }
2100
-
2101
- /** \ingroup libusb_dev
2102
- * Detach a kernel driver from an interface. If successful, you will then be
2103
- * able to claim the interface and perform I/O.
2104
- *
2105
- * This functionality is not available on Windows.
2106
- *
2107
- * Note that libusb itself also talks to the device through a special kernel
2108
- * driver, if this driver is already attached to the device, this call will
2109
- * not detach it and return \ref LIBUSB_ERROR_NOT_FOUND.
2110
- *
2111
- * \param dev_handle a device handle
2112
- * \param interface_number the interface to detach the driver from
2113
- * \returns 0 on success
2114
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
2115
- * \returns \ref LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
2116
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
2117
- * \returns \ref LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
2118
- * is not available
2119
- * \returns another LIBUSB_ERROR code on other failure
2120
- * \see libusb_kernel_driver_active()
2121
- */
2122
- int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev_handle,
2123
- int interface_number)
2124
- {
2125
- usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
2126
-
2127
- if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
2128
- return LIBUSB_ERROR_INVALID_PARAM;
2129
-
2130
- if (!usbi_atomic_load(&dev_handle->dev->attached))
2131
- return LIBUSB_ERROR_NO_DEVICE;
2132
-
2133
- if (usbi_backend.detach_kernel_driver)
2134
- return usbi_backend.detach_kernel_driver(dev_handle, (uint8_t)interface_number);
2135
- else
2136
- return LIBUSB_ERROR_NOT_SUPPORTED;
2137
- }
2138
-
2139
- /** \ingroup libusb_dev
2140
- * Re-attach an interface's kernel driver, which was previously detached
2141
- * using libusb_detach_kernel_driver().
2142
- *
2143
- * This functionality is not available on Windows.
2144
- *
2145
- * \param dev_handle a device handle
2146
- * \param interface_number the interface to attach the driver from
2147
- * \returns 0 on success
2148
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
2149
- * \returns \ref LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
2150
- * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
2151
- * \returns \ref LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
2152
- * is not available
2153
- * \returns \ref LIBUSB_ERROR_BUSY if the driver cannot be attached because the
2154
- * interface is claimed by a program or driver
2155
- * \returns another LIBUSB_ERROR code on other failure
2156
- * \see libusb_kernel_driver_active()
2157
- */
2158
- int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev_handle,
2159
- int interface_number)
2160
- {
2161
- usbi_dbg(HANDLE_CTX(dev_handle), "interface %d", interface_number);
2162
-
2163
- if (interface_number < 0 || interface_number >= USB_MAXINTERFACES)
2164
- return LIBUSB_ERROR_INVALID_PARAM;
2165
-
2166
- if (!usbi_atomic_load(&dev_handle->dev->attached))
2167
- return LIBUSB_ERROR_NO_DEVICE;
2168
-
2169
- if (usbi_backend.attach_kernel_driver)
2170
- return usbi_backend.attach_kernel_driver(dev_handle, (uint8_t)interface_number);
2171
- else
2172
- return LIBUSB_ERROR_NOT_SUPPORTED;
2173
- }
2174
-
2175
- /** \ingroup libusb_dev
2176
- * Enable/disable libusb's automatic kernel driver detachment. When this is
2177
- * enabled libusb will automatically detach the kernel driver on an interface
2178
- * when claiming the interface, and attach it when releasing the interface.
2179
- *
2180
- * Automatic kernel driver detachment is disabled on newly opened device
2181
- * handles by default.
2182
- *
2183
- * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
2184
- * this function will return \ref LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
2185
- * continue as if this function was never called.
2186
- *
2187
- * \param dev_handle a device handle
2188
- * \param enable whether to enable or disable auto kernel driver detachment
2189
- *
2190
- * \returns \ref LIBUSB_SUCCESS on success
2191
- * \returns \ref LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
2192
- * is not available
2193
- * \see libusb_claim_interface()
2194
- * \see libusb_release_interface()
2195
- * \see libusb_set_configuration()
2196
- */
2197
- int API_EXPORTED libusb_set_auto_detach_kernel_driver(
2198
- libusb_device_handle *dev_handle, int enable)
2199
- {
2200
- if (!(usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
2201
- return LIBUSB_ERROR_NOT_SUPPORTED;
2202
-
2203
- dev_handle->auto_detach_kernel_driver = enable;
2204
- return LIBUSB_SUCCESS;
2205
- }
2206
-
2207
- /** \ingroup libusb_lib
2208
- * Deprecated. Use libusb_set_option() or libusb_init_context() instead,
2209
- * with the \ref LIBUSB_OPTION_LOG_LEVEL option.
2210
- */
2211
- void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
2212
- {
2213
- libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level);
2214
- }
2215
-
2216
- static void libusb_set_log_cb_internal(libusb_context *ctx, libusb_log_cb cb,
2217
- int mode)
2218
- {
2219
- #if defined(ENABLE_LOGGING) && (!defined(ENABLE_DEBUG_LOGGING) || !defined(USE_SYSTEM_LOGGING_FACILITY))
2220
- #if !defined(USE_SYSTEM_LOGGING_FACILITY)
2221
- if (mode & LIBUSB_LOG_CB_GLOBAL)
2222
- log_handler = cb;
2223
- #endif
2224
- #if !defined(ENABLE_DEBUG_LOGGING)
2225
- if (mode & LIBUSB_LOG_CB_CONTEXT) {
2226
- ctx = usbi_get_context(ctx);
2227
- ctx->log_handler = cb;
2228
- }
2229
- #else
2230
- UNUSED(ctx);
2231
- #endif
2232
- #else
2233
- UNUSED(ctx);
2234
- UNUSED(cb);
2235
- UNUSED(mode);
2236
- #endif
2237
- }
2238
-
2239
- /** \ingroup libusb_lib
2240
- * Set log handler.
2241
- *
2242
- * libusb will redirect its log messages to the provided callback function.
2243
- * libusb supports redirection of per context and global log messages.
2244
- * Log messages sent to the context will be sent to the global log handler too.
2245
- *
2246
- * If libusb is compiled without message logging or USE_SYSTEM_LOGGING_FACILITY
2247
- * is defined then global callback function will never be called.
2248
- * If ENABLE_DEBUG_LOGGING is defined then per context callback function will
2249
- * never be called.
2250
- *
2251
- * Since version 1.0.23, \ref LIBUSB_API_VERSION >= 0x01000107
2252
- *
2253
- * \param ctx context on which to assign log handler, or NULL for the default
2254
- * context. Parameter ignored if only LIBUSB_LOG_CB_GLOBAL mode is requested.
2255
- * \param cb pointer to the callback function, or NULL to stop log
2256
- * messages redirection
2257
- * \param mode mode of callback function operation. Several modes can be
2258
- * selected for a single callback function, see \ref libusb_log_cb_mode for
2259
- * a description.
2260
- * \see libusb_log_cb, libusb_log_cb_mode
2261
- */
2262
- void API_EXPORTED libusb_set_log_cb(libusb_context *ctx, libusb_log_cb cb,
2263
- int mode)
2264
- {
2265
- libusb_set_log_cb_internal(ctx, cb, mode);
2266
- }
2267
-
2268
- /** \ingroup libusb_lib
2269
- * Set an option in the library.
2270
- *
2271
- * Use this function to configure a specific option within the library.
2272
- *
2273
- * Some options require one or more arguments to be provided. Consult each
2274
- * option's documentation for specific requirements.
2275
- *
2276
- * If the context ctx is NULL, the option will be added to a list of default
2277
- * options that will be applied to all subsequently created contexts.
2278
- *
2279
- * Since version 1.0.22, \ref LIBUSB_API_VERSION >= 0x01000106
2280
- *
2281
- * \param ctx context on which to operate
2282
- * \param option which option to set
2283
- * \param ... any required arguments for the specified option
2284
- *
2285
- * \returns \ref LIBUSB_SUCCESS on success
2286
- * \returns \ref LIBUSB_ERROR_INVALID_PARAM if the option or arguments are invalid
2287
- * \returns \ref LIBUSB_ERROR_NOT_SUPPORTED if the option is valid but not supported
2288
- * on this platform
2289
- * \returns \ref LIBUSB_ERROR_NOT_FOUND if LIBUSB_OPTION_USE_USBDK is valid on this platform but UsbDk is not available
2290
- */
2291
- int API_EXPORTEDV libusb_set_option(libusb_context *ctx,
2292
- enum libusb_option option, ...)
2293
- {
2294
- int arg = 0, r = LIBUSB_SUCCESS;
2295
- libusb_log_cb log_cb = NULL;
2296
- va_list ap;
2297
- #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2298
- int is_default_context = (NULL == ctx);
2299
- #endif
2300
-
2301
- va_start(ap, option);
2302
-
2303
- if (LIBUSB_OPTION_LOG_LEVEL == option) {
2304
- arg = va_arg(ap, int);
2305
- if (arg < LIBUSB_LOG_LEVEL_NONE || arg > LIBUSB_LOG_LEVEL_DEBUG) {
2306
- r = LIBUSB_ERROR_INVALID_PARAM;
2307
- }
2308
- }
2309
- if (LIBUSB_OPTION_LOG_CB == option) {
2310
- log_cb = (libusb_log_cb) va_arg(ap, libusb_log_cb);
2311
- }
2312
-
2313
- do {
2314
- if (LIBUSB_SUCCESS != r) {
2315
- break;
2316
- }
2317
-
2318
- if (option >= LIBUSB_OPTION_MAX) {
2319
- r = LIBUSB_ERROR_INVALID_PARAM;
2320
- break;
2321
- }
2322
-
2323
- if (NULL == ctx) {
2324
- usbi_mutex_static_lock(&default_context_lock);
2325
- default_context_options[option].is_set = 1;
2326
- if (LIBUSB_OPTION_LOG_LEVEL == option) {
2327
- default_context_options[option].arg.ival = arg;
2328
- } else if (LIBUSB_OPTION_LOG_CB == option) {
2329
- default_context_options[option].arg.log_cbval = log_cb;
2330
- libusb_set_log_cb_internal(NULL, log_cb, LIBUSB_LOG_CB_GLOBAL);
2331
- }
2332
- usbi_mutex_static_unlock(&default_context_lock);
2333
- }
2334
-
2335
- ctx = usbi_get_context(ctx);
2336
- if (NULL == ctx)
2337
- break;
2338
-
2339
- switch (option) {
2340
- case LIBUSB_OPTION_LOG_LEVEL:
2341
- #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2342
- if (!ctx->debug_fixed) {
2343
- ctx->debug = (enum libusb_log_level)arg;
2344
- if (is_default_context)
2345
- usbi_atomic_store(&default_debug_level, CLAMP(arg, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG));
2346
- }
2347
- #endif
2348
- break;
2349
-
2350
- /* Handle all backend-specific options here */
2351
- case LIBUSB_OPTION_USE_USBDK:
2352
- case LIBUSB_OPTION_NO_DEVICE_DISCOVERY:
2353
- if (usbi_backend.set_option) {
2354
- r = usbi_backend.set_option(ctx, option, ap);
2355
- break;
2356
- }
2357
-
2358
- r = LIBUSB_ERROR_NOT_SUPPORTED;
2359
- break;
2360
-
2361
- case LIBUSB_OPTION_LOG_CB:
2362
- libusb_set_log_cb_internal(ctx, log_cb, LIBUSB_LOG_CB_CONTEXT);
2363
- break;
2364
-
2365
- case LIBUSB_OPTION_MAX: /* unreachable */
2366
- default:
2367
- r = LIBUSB_ERROR_INVALID_PARAM;
2368
- }
2369
- } while (0);
2370
-
2371
- va_end(ap);
2372
-
2373
- return r;
2374
- }
2375
-
2376
- #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2377
- /* returns the log level as defined in the LIBUSB_DEBUG environment variable.
2378
- * if LIBUSB_DEBUG is not present or not a number, returns LIBUSB_LOG_LEVEL_NONE.
2379
- * value is clamped to ensure it is within the valid range of possibilities.
2380
- */
2381
- static enum libusb_log_level get_env_debug_level(void)
2382
- {
2383
- enum libusb_log_level level = LIBUSB_LOG_LEVEL_NONE;
2384
- const char *dbg = getenv("LIBUSB_DEBUG");
2385
- if (dbg) {
2386
- long dbg_level = strtol(dbg, NULL, 10);
2387
- dbg_level = CLAMP(dbg_level, LIBUSB_LOG_LEVEL_NONE, LIBUSB_LOG_LEVEL_DEBUG);
2388
- level = (enum libusb_log_level)dbg_level;
2389
- }
2390
- return level;
2391
- }
2392
- #endif
2393
-
2394
- /** \ingroup libusb_lib
2395
- * Deprecated initialization function. Equivalent to calling libusb_init_context with no options.
2396
- *
2397
- * \see libusb_init_context
2398
- */
2399
- int API_EXPORTED libusb_init(libusb_context **ctx)
2400
- {
2401
- return libusb_init_context(ctx, NULL, 0);
2402
- }
2403
-
2404
- /** \ingroup libusb_lib
2405
- * Initialize libusb. This function must be called before calling any other
2406
- * libusb function.
2407
- *
2408
- * If you do not provide an output location for a context pointer, a default
2409
- * context will be created. If there was already a default context, it will
2410
- * be reused (and nothing will be initialized/reinitialized and options will
2411
- * be ignored). If num_options is 0 then options is ignored and may be NULL.
2412
- *
2413
- * Since version 1.0.27, \ref LIBUSB_API_VERSION >= 0x0100010A
2414
- *
2415
- * \param ctx Optional output location for context pointer.
2416
- * Only valid on return code 0.
2417
- * \param options Optional array of options to set on the new context.
2418
- * \param num_options Number of elements in the options array.
2419
- * \returns 0 on success, or a LIBUSB_ERROR code on failure
2420
- * \see libusb_contexts
2421
- */
2422
- int API_EXPORTED libusb_init_context(libusb_context **ctx, const struct libusb_init_option options[], int num_options)
2423
- {
2424
- size_t priv_size = usbi_backend.context_priv_size;
2425
- struct libusb_context *_ctx;
2426
- int r;
2427
-
2428
- usbi_mutex_static_lock(&default_context_lock);
2429
-
2430
- if (!ctx && default_context_refcnt > 0) {
2431
- usbi_dbg(usbi_default_context, "reusing default context");
2432
- default_context_refcnt++;
2433
- usbi_mutex_static_unlock(&default_context_lock);
2434
- return 0;
2435
- }
2436
-
2437
- /* check for first init */
2438
- usbi_mutex_static_lock(&active_contexts_lock);
2439
- if (!active_contexts_list.next) {
2440
- list_init(&active_contexts_list);
2441
- usbi_get_monotonic_time(&timestamp_origin);
2442
- }
2443
- usbi_mutex_static_unlock(&active_contexts_lock);
2444
-
2445
- _ctx = calloc(1, PTR_ALIGN(sizeof(*_ctx)) + priv_size);
2446
- if (!_ctx) {
2447
- usbi_mutex_static_unlock(&default_context_lock);
2448
- return LIBUSB_ERROR_NO_MEM;
2449
- }
2450
-
2451
- #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2452
- _ctx->debug = LIBUSB_LOG_LEVEL_NONE;
2453
- if (getenv("LIBUSB_DEBUG")) {
2454
- _ctx->debug = get_env_debug_level();
2455
- _ctx->debug_fixed = 1;
2456
- } else if (default_context_options[LIBUSB_OPTION_LOG_LEVEL].is_set) {
2457
- _ctx->debug = (enum libusb_log_level)default_context_options[LIBUSB_OPTION_LOG_LEVEL].arg.ival;
2458
- }
2459
- #endif
2460
-
2461
- usbi_mutex_init(&_ctx->usb_devs_lock);
2462
- usbi_mutex_init(&_ctx->open_devs_lock);
2463
- list_init(&_ctx->usb_devs);
2464
- list_init(&_ctx->open_devs);
2465
-
2466
- /* apply default options to all new contexts */
2467
- for (enum libusb_option option = 0 ; option < LIBUSB_OPTION_MAX ; option++) {
2468
- if (LIBUSB_OPTION_LOG_LEVEL == option || !default_context_options[option].is_set) {
2469
- continue;
2470
- }
2471
- if (LIBUSB_OPTION_LOG_CB != option) {
2472
- r = libusb_set_option(_ctx, option);
2473
- } else {
2474
- r = libusb_set_option(_ctx, option, default_context_options[option].arg.log_cbval);
2475
- }
2476
- if (LIBUSB_SUCCESS != r)
2477
- goto err_free_ctx;
2478
- }
2479
-
2480
- /* apply any options provided by the user */
2481
- for (int i = 0 ; i < num_options ; ++i) {
2482
- switch(options[i].option) {
2483
- case LIBUSB_OPTION_LOG_CB:
2484
- r = libusb_set_option(_ctx, options[i].option, options[i].value.log_cbval);
2485
- break;
2486
-
2487
- case LIBUSB_OPTION_LOG_LEVEL:
2488
- case LIBUSB_OPTION_USE_USBDK:
2489
- case LIBUSB_OPTION_NO_DEVICE_DISCOVERY:
2490
- case LIBUSB_OPTION_MAX:
2491
- default:
2492
- r = libusb_set_option(_ctx, options[i].option, options[i].value.ival);
2493
- }
2494
- if (LIBUSB_SUCCESS != r)
2495
- goto err_free_ctx;
2496
- }
2497
-
2498
- /* default context must be initialized before calling usbi_dbg */
2499
- if (!ctx) {
2500
- usbi_default_context = _ctx;
2501
- default_context_refcnt = 1;
2502
- #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2503
- usbi_atomic_store(&default_debug_level, _ctx->debug);
2504
- #endif
2505
- usbi_dbg(usbi_default_context, "created default context");
2506
- }
2507
-
2508
- usbi_dbg(_ctx, "libusb v%u.%u.%u.%u%s", libusb_version_internal.major, libusb_version_internal.minor,
2509
- libusb_version_internal.micro, libusb_version_internal.nano, libusb_version_internal.rc);
2510
-
2511
- r = usbi_io_init(_ctx);
2512
- if (r < 0)
2513
- goto err_free_ctx;
2514
-
2515
- usbi_mutex_static_lock(&active_contexts_lock);
2516
- list_add(&_ctx->list, &active_contexts_list);
2517
- usbi_mutex_static_unlock(&active_contexts_lock);
2518
-
2519
- if (usbi_backend.init) {
2520
- r = usbi_backend.init(_ctx);
2521
- if (r)
2522
- goto err_io_exit;
2523
- }
2524
-
2525
- /* Initialize hotplug after the initial enumeration is done. */
2526
- usbi_hotplug_init(_ctx);
2527
-
2528
- if (ctx) {
2529
- *ctx = _ctx;
2530
-
2531
- if (!usbi_fallback_context) {
2532
- #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
2533
- if (usbi_atomic_load(&default_debug_level) == -1)
2534
- usbi_atomic_store(&default_debug_level, _ctx->debug);
2535
- #endif
2536
- usbi_fallback_context = _ctx;
2537
- usbi_dbg(usbi_fallback_context, "installing new context as implicit default");
2538
- }
2539
- }
2540
-
2541
- usbi_mutex_static_unlock(&default_context_lock);
2542
-
2543
- return 0;
2544
-
2545
- err_io_exit:
2546
- usbi_mutex_static_lock(&active_contexts_lock);
2547
- list_del(&_ctx->list);
2548
- usbi_mutex_static_unlock(&active_contexts_lock);
2549
-
2550
- usbi_hotplug_exit(_ctx);
2551
- usbi_io_exit(_ctx);
2552
-
2553
- err_free_ctx:
2554
- if (!ctx) {
2555
- /* clear default context that was not fully initialized */
2556
- usbi_default_context = NULL;
2557
- default_context_refcnt = 0;
2558
- }
2559
-
2560
- usbi_mutex_destroy(&_ctx->open_devs_lock);
2561
- usbi_mutex_destroy(&_ctx->usb_devs_lock);
2562
-
2563
- free(_ctx);
2564
-
2565
- usbi_mutex_static_unlock(&default_context_lock);
2566
-
2567
- return r;
2568
- }
2569
-
2570
- /** \ingroup libusb_lib
2571
- * Deinitialize libusb. Should be called after closing all open devices and
2572
- * before your application terminates.
2573
- * \param ctx the context to deinitialize, or NULL for the default context
2574
- */
2575
- void API_EXPORTED libusb_exit(libusb_context *ctx)
2576
- {
2577
- struct libusb_context *_ctx;
2578
- struct libusb_device *dev;
2579
-
2580
- usbi_mutex_static_lock(&default_context_lock);
2581
-
2582
- /* if working with default context, only actually do the deinitialization
2583
- * if we're the last user */
2584
- if (!ctx) {
2585
- if (!usbi_default_context) {
2586
- usbi_dbg(ctx, "no default context, not initialized?");
2587
- usbi_mutex_static_unlock(&default_context_lock);
2588
- return;
2589
- }
2590
-
2591
- if (--default_context_refcnt > 0) {
2592
- usbi_dbg(ctx, "not destroying default context");
2593
- usbi_mutex_static_unlock(&default_context_lock);
2594
- return;
2595
- }
2596
-
2597
- usbi_dbg(ctx, "destroying default context");
2598
- _ctx = usbi_default_context;
2599
- } else {
2600
- usbi_dbg(ctx, " ");
2601
- _ctx = ctx;
2602
- }
2603
-
2604
- usbi_mutex_static_lock(&active_contexts_lock);
2605
- list_del(&_ctx->list);
2606
- usbi_mutex_static_unlock(&active_contexts_lock);
2607
-
2608
- /* Exit hotplug before backend dependency */
2609
- usbi_hotplug_exit(_ctx);
2610
-
2611
- if (usbi_backend.exit)
2612
- usbi_backend.exit(_ctx);
2613
-
2614
- if (!ctx)
2615
- usbi_default_context = NULL;
2616
- if (ctx == usbi_fallback_context)
2617
- usbi_fallback_context = NULL;
2618
-
2619
- usbi_mutex_static_unlock(&default_context_lock);
2620
-
2621
- /* Don't bother with locking after this point because unless there is
2622
- * an application bug, nobody will be accessing the context. */
2623
-
2624
- usbi_io_exit(_ctx);
2625
-
2626
- for_each_device(_ctx, dev) {
2627
- usbi_warn(_ctx, "device %d.%d still referenced",
2628
- dev->bus_number, dev->device_address);
2629
- DEVICE_CTX(dev) = NULL;
2630
- }
2631
-
2632
- if (!list_empty(&_ctx->open_devs))
2633
- usbi_warn(_ctx, "application left some devices open");
2634
-
2635
- usbi_mutex_destroy(&_ctx->open_devs_lock);
2636
- usbi_mutex_destroy(&_ctx->usb_devs_lock);
2637
-
2638
- free(_ctx);
2639
- }
2640
-
2641
- /** \ingroup libusb_misc
2642
- * Check at runtime if the loaded library has a given capability.
2643
- * This call should be performed after \ref libusb_init_context(), to ensure the
2644
- * backend has updated its capability set.
2645
- *
2646
- * \param capability the \ref libusb_capability to check for
2647
- * \returns nonzero if the running library has the capability, 0 otherwise
2648
- */
2649
- int API_EXPORTED libusb_has_capability(uint32_t capability)
2650
- {
2651
- switch (capability) {
2652
- case LIBUSB_CAP_HAS_CAPABILITY:
2653
- return 1;
2654
- case LIBUSB_CAP_HAS_HOTPLUG:
2655
- return !(usbi_backend.get_device_list);
2656
- case LIBUSB_CAP_HAS_HID_ACCESS:
2657
- return (usbi_backend.caps & USBI_CAP_HAS_HID_ACCESS);
2658
- case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
2659
- return (usbi_backend.caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
2660
- }
2661
- return 0;
2662
- }
2663
-
2664
- #ifdef ENABLE_LOGGING
2665
-
2666
- /* this is defined in libusbi.h if needed */
2667
- #ifdef LIBUSB_PRINTF_WIN32
2668
- /*
2669
- * Prior to VS2015, Microsoft did not provide the snprintf() function and
2670
- * provided a vsnprintf() that did not guarantee NUL-terminated output.
2671
- * Microsoft did provide a _snprintf() function, but again it did not
2672
- * guarantee NULL-terminated output.
2673
- *
2674
- * The below implementations guarantee NUL-terminated output and are
2675
- * C99 compliant.
2676
- */
2677
-
2678
- int usbi_snprintf(char *str, size_t size, const char *format, ...)
2679
- {
2680
- va_list args;
2681
- int ret;
2682
-
2683
- va_start(args, format);
2684
- ret = usbi_vsnprintf(str, size, format, args);
2685
- va_end(args);
2686
-
2687
- return ret;
2688
- }
2689
-
2690
- int usbi_vsnprintf(char *str, size_t size, const char *format, va_list args)
2691
- {
2692
- int ret;
2693
-
2694
- ret = _vsnprintf(str, size, format, args);
2695
- if (ret < 0 || ret == (int)size) {
2696
- /* Output is truncated, ensure buffer is NUL-terminated and
2697
- * determine how many characters would have been written. */
2698
- str[size - 1] = '\0';
2699
- if (ret < 0)
2700
- ret = _vsnprintf(NULL, 0, format, args);
2701
- }
2702
-
2703
- return ret;
2704
- }
2705
- #endif /* LIBUSB_PRINTF_WIN32 */
2706
-
2707
- static void log_str(enum libusb_log_level level, const char *str)
2708
- {
2709
- #if defined(USE_SYSTEM_LOGGING_FACILITY)
2710
- #if defined(__ANDROID__)
2711
- int priority;
2712
- switch (level) {
2713
- case LIBUSB_LOG_LEVEL_NONE: return; /* Impossible, but keeps compiler happy */
2714
- case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
2715
- case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
2716
- case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
2717
- case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
2718
- default: priority = ANDROID_LOG_UNKNOWN;
2719
- }
2720
- __android_log_write(priority, "libusb", str);
2721
- #elif defined(_WIN32)
2722
- UNUSED(level);
2723
- OutputDebugStringA(str);
2724
- #elif defined(HAVE_SYSLOG)
2725
- int syslog_level;
2726
- switch (level) {
2727
- case LIBUSB_LOG_LEVEL_NONE: return; /* Impossible, but keeps compiler happy */
2728
- case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
2729
- case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
2730
- case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
2731
- case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
2732
- default: syslog_level = LOG_INFO;
2733
- }
2734
- syslog(syslog_level, "%s", str);
2735
- #else /* All of gcc, Clang, Xcode seem to use #warning */
2736
- #warning System logging is not supported on this platform. Logging to stderr will be used instead.
2737
- UNUSED(level);
2738
- fputs(str, stderr);
2739
- #endif
2740
- #else
2741
- /* Global log handler */
2742
- if (log_handler)
2743
- log_handler(NULL, level, str);
2744
- else
2745
- fputs(str, stderr);
2746
- #endif /* USE_SYSTEM_LOGGING_FACILITY */
2747
- }
2748
-
2749
- static void log_v(struct libusb_context *ctx, enum libusb_log_level level,
2750
- const char *function, const char *format, va_list args)
2751
- {
2752
- const char *prefix;
2753
- char buf[USBI_MAX_LOG_LEN];
2754
- int global_debug, header_len, text_len;
2755
- static int has_debug_header_been_displayed = 0;
2756
-
2757
- #ifdef ENABLE_DEBUG_LOGGING
2758
- global_debug = 1;
2759
- UNUSED(ctx);
2760
- #else
2761
- enum libusb_log_level ctx_level;
2762
- long default_level_value;
2763
-
2764
- if (ctx) {
2765
- ctx_level = ctx->debug;
2766
- } else {
2767
- default_level_value = usbi_atomic_load(&default_debug_level);
2768
- ctx_level = default_level_value < 0 ? get_env_debug_level() : (enum libusb_log_level)default_level_value;
2769
- }
2770
-
2771
- if (ctx_level < level)
2772
- return;
2773
-
2774
- global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
2775
- #endif
2776
-
2777
- switch (level) {
2778
- case LIBUSB_LOG_LEVEL_NONE: /* Impossible, but keeps compiler happy */
2779
- return;
2780
- case LIBUSB_LOG_LEVEL_ERROR:
2781
- prefix = "error";
2782
- break;
2783
- case LIBUSB_LOG_LEVEL_WARNING:
2784
- prefix = "warning";
2785
- break;
2786
- case LIBUSB_LOG_LEVEL_INFO:
2787
- prefix = "info";
2788
- break;
2789
- case LIBUSB_LOG_LEVEL_DEBUG:
2790
- prefix = "debug";
2791
- break;
2792
- default:
2793
- prefix = "unknown";
2794
- break;
2795
- }
2796
-
2797
- if (global_debug) {
2798
- struct timespec timestamp;
2799
-
2800
- if (!has_debug_header_been_displayed) {
2801
- has_debug_header_been_displayed = 1;
2802
- log_str(LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>" USBI_LOG_LINE_END);
2803
- log_str(LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END);
2804
- }
2805
-
2806
- usbi_get_monotonic_time(&timestamp);
2807
- TIMESPEC_SUB(&timestamp, &timestamp_origin, &timestamp);
2808
-
2809
- header_len = snprintf(buf, sizeof(buf),
2810
- "[%2ld.%06ld] [%08lx] libusb: %s [%s] ",
2811
- (long)timestamp.tv_sec, (long)(timestamp.tv_nsec / 1000L), usbi_get_tid(), prefix, function);
2812
- } else {
2813
- header_len = snprintf(buf, sizeof(buf),
2814
- "libusb: %s [%s] ", prefix, function);
2815
- }
2816
-
2817
- if (header_len < 0 || header_len >= (int)sizeof(buf)) {
2818
- /* Somehow snprintf() failed to write to the buffer,
2819
- * remove the header so something useful is output. */
2820
- header_len = 0;
2821
- }
2822
-
2823
- text_len = vsnprintf(buf + header_len, sizeof(buf) - (size_t)header_len,
2824
- format, args);
2825
- if (text_len < 0 || text_len + header_len >= (int)sizeof(buf)) {
2826
- /* Truncated log output. On some platforms a -1 return value means
2827
- * that the output was truncated. */
2828
- text_len = (int)sizeof(buf) - header_len;
2829
- }
2830
- if (header_len + text_len + (int)sizeof(USBI_LOG_LINE_END) >= (int)sizeof(buf)) {
2831
- /* Need to truncate the text slightly to fit on the terminator. */
2832
- text_len -= (header_len + text_len + (int)sizeof(USBI_LOG_LINE_END)) - (int)sizeof(buf);
2833
- }
2834
- strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
2835
-
2836
- log_str(level, buf);
2837
-
2838
- /* Per-context log handler */
2839
- #ifndef ENABLE_DEBUG_LOGGING
2840
- if (ctx && ctx->log_handler)
2841
- ctx->log_handler(ctx, level, buf);
2842
- #endif
2843
- }
2844
-
2845
- void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
2846
- const char *function, const char *format, ...)
2847
- {
2848
- va_list args;
2849
-
2850
- va_start(args, format);
2851
- log_v(ctx, level, function, format, args);
2852
- va_end(args);
2853
- }
2854
-
2855
- #endif /* ENABLE_LOGGING */
2856
-
2857
- /** \ingroup libusb_misc
2858
- * Returns a constant NULL-terminated string with the ASCII name of a libusb
2859
- * error or transfer status code. The caller must not free() the returned
2860
- * string.
2861
- *
2862
- * \param error_code The \ref libusb_error or libusb_transfer_status code to
2863
- * return the name of.
2864
- * \returns The error name, or the string **UNKNOWN** if the value of
2865
- * error_code is not a known error / status code.
2866
- */
2867
- DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
2868
- {
2869
- switch (error_code) {
2870
- case LIBUSB_ERROR_IO:
2871
- return "LIBUSB_ERROR_IO";
2872
- case LIBUSB_ERROR_INVALID_PARAM:
2873
- return "LIBUSB_ERROR_INVALID_PARAM";
2874
- case LIBUSB_ERROR_ACCESS:
2875
- return "LIBUSB_ERROR_ACCESS";
2876
- case LIBUSB_ERROR_NO_DEVICE:
2877
- return "LIBUSB_ERROR_NO_DEVICE";
2878
- case LIBUSB_ERROR_NOT_FOUND:
2879
- return "LIBUSB_ERROR_NOT_FOUND";
2880
- case LIBUSB_ERROR_BUSY:
2881
- return "LIBUSB_ERROR_BUSY";
2882
- case LIBUSB_ERROR_TIMEOUT:
2883
- return "LIBUSB_ERROR_TIMEOUT";
2884
- case LIBUSB_ERROR_OVERFLOW:
2885
- return "LIBUSB_ERROR_OVERFLOW";
2886
- case LIBUSB_ERROR_PIPE:
2887
- return "LIBUSB_ERROR_PIPE";
2888
- case LIBUSB_ERROR_INTERRUPTED:
2889
- return "LIBUSB_ERROR_INTERRUPTED";
2890
- case LIBUSB_ERROR_NO_MEM:
2891
- return "LIBUSB_ERROR_NO_MEM";
2892
- case LIBUSB_ERROR_NOT_SUPPORTED:
2893
- return "LIBUSB_ERROR_NOT_SUPPORTED";
2894
- case LIBUSB_ERROR_OTHER:
2895
- return "LIBUSB_ERROR_OTHER";
2896
-
2897
- case LIBUSB_TRANSFER_ERROR:
2898
- return "LIBUSB_TRANSFER_ERROR";
2899
- case LIBUSB_TRANSFER_TIMED_OUT:
2900
- return "LIBUSB_TRANSFER_TIMED_OUT";
2901
- case LIBUSB_TRANSFER_CANCELLED:
2902
- return "LIBUSB_TRANSFER_CANCELLED";
2903
- case LIBUSB_TRANSFER_STALL:
2904
- return "LIBUSB_TRANSFER_STALL";
2905
- case LIBUSB_TRANSFER_NO_DEVICE:
2906
- return "LIBUSB_TRANSFER_NO_DEVICE";
2907
- case LIBUSB_TRANSFER_OVERFLOW:
2908
- return "LIBUSB_TRANSFER_OVERFLOW";
2909
-
2910
- case 0:
2911
- return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
2912
- default:
2913
- return "**UNKNOWN**";
2914
- }
2915
- }
2916
-
2917
- /** \ingroup libusb_misc
2918
- * Returns a pointer to const struct libusb_version with the version
2919
- * (major, minor, micro, nano and rc) of the running library.
2920
- */
2921
- DEFAULT_VISIBILITY
2922
- const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
2923
- {
2924
- return &libusb_version_internal;
2925
- }