1 /*
2 * libusb multi-thread test program
3 * Copyright 2022-2023 Tormod Volden
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 #include <config.h>
21
22 #include <libusb.h>
23 #include <stdio.h>
24 #include <stdbool.h>
25
26 #if defined(PLATFORM_POSIX)
27
28 #include <pthread.h>
29 typedef pthread_t thread_t;
30 typedef void * thread_return_t;
31 #define THREAD_RETURN_VALUE NULL
32 #define THREAD_CALL_TYPE
33
thread_create(thread_t * thread,thread_return_t (* thread_entry)(void * arg),void * arg)34 static inline int thread_create(thread_t *thread,
35 thread_return_t (*thread_entry)(void *arg), void *arg)
36 {
37 return pthread_create(thread, NULL, thread_entry, arg) == 0 ? 0 : -1;
38 }
39
thread_join(thread_t thread)40 static inline void thread_join(thread_t thread)
41 {
42 (void)pthread_join(thread, NULL);
43 }
44
45 #include <stdatomic.h>
46
47 #elif defined(PLATFORM_WINDOWS)
48
49 typedef HANDLE thread_t;
50 #define THREAD_RETURN_VALUE 0
51 #define THREAD_CALL_TYPE __stdcall
52
53 #if defined(__CYGWIN__)
54 typedef DWORD thread_return_t;
55 #else
56 #include <process.h>
57 typedef unsigned thread_return_t;
58 #endif
59
thread_create(thread_t * thread,thread_return_t (__stdcall * thread_entry)(void * arg),void * arg)60 static inline int thread_create(thread_t *thread,
61 thread_return_t (__stdcall *thread_entry)(void *arg), void *arg)
62 {
63 #if defined(__CYGWIN__)
64 *thread = CreateThread(NULL, 0, thread_entry, arg, 0, NULL);
65 #else
66 *thread = (HANDLE)_beginthreadex(NULL, 0, thread_entry, arg, 0, NULL);
67 #endif
68 return *thread != NULL ? 0 : -1;
69 }
70
thread_join(thread_t thread)71 static inline void thread_join(thread_t thread)
72 {
73 (void)WaitForSingleObject(thread, INFINITE);
74 (void)CloseHandle(thread);
75 }
76
77 typedef volatile LONG atomic_bool;
78
79 #define atomic_exchange InterlockedExchange
80 #endif /* PLATFORM_WINDOWS */
81
82 /* Test that creates and destroys contexts repeatedly */
83
84 #define NTHREADS 8
85 #define ITERS 64
86 #define MAX_DEVCOUNT 128
87
88 struct thread_info {
89 int number;
90 int enumerate;
91 ssize_t devcount;
92 int err;
93 int iteration;
94 } tinfo[NTHREADS];
95
96 atomic_bool no_access[MAX_DEVCOUNT];
97
98 /* Function called by backend during device initialization to convert
99 * multi-byte fields in the device descriptor to host-endian format.
100 * Copied from libusbi.h as we want test to be realistic and not depend on internals.
101 */
usbi_localize_device_descriptor(struct libusb_device_descriptor * desc)102 static inline void usbi_localize_device_descriptor(struct libusb_device_descriptor *desc)
103 {
104 desc->bcdUSB = libusb_le16_to_cpu(desc->bcdUSB);
105 desc->idVendor = libusb_le16_to_cpu(desc->idVendor);
106 desc->idProduct = libusb_le16_to_cpu(desc->idProduct);
107 desc->bcdDevice = libusb_le16_to_cpu(desc->bcdDevice);
108 }
109
init_and_exit(void * arg)110 static thread_return_t THREAD_CALL_TYPE init_and_exit(void * arg)
111 {
112 struct thread_info *ti = (struct thread_info *) arg;
113
114 for (ti->iteration = 0; ti->iteration < ITERS && !ti->err; ti->iteration++) {
115 libusb_context *ctx = NULL;
116
117 if ((ti->err = libusb_init_context(&ctx, /*options=*/NULL, /*num_options=*/0)) != 0) {
118 break;
119 }
120 if (ti->enumerate) {
121 libusb_device **devs;
122 ti->devcount = libusb_get_device_list(ctx, &devs);
123 if (ti->devcount < 0) {
124 ti->err = (int)ti->devcount;
125 break;
126 }
127 for (int i = 0; i < ti->devcount && ti->err == 0; i++) {
128 libusb_device *dev = devs[i];
129 struct libusb_device_descriptor desc;
130 if ((ti->err = libusb_get_device_descriptor(dev, &desc)) != 0) {
131 break;
132 }
133 if (no_access[i]) {
134 continue;
135 }
136 libusb_device_handle *dev_handle;
137 int open_err = libusb_open(dev, &dev_handle);
138 if (open_err == LIBUSB_ERROR_ACCESS
139 #if defined(PLATFORM_WINDOWS)
140 || open_err == LIBUSB_ERROR_NOT_SUPPORTED
141 || open_err == LIBUSB_ERROR_NOT_FOUND
142 #endif
143 ) {
144 /* Use atomic swap to ensure we print warning only once across all threads.
145 This is a warning and not a hard error because it should be fine to run tests
146 even if we don't have access to some devices. */
147 if (!atomic_exchange(&no_access[i], true)) {
148 fprintf(stderr, "No access to device %04x:%04x, skipping transfer tests.\n", desc.idVendor, desc.idProduct);
149 }
150 continue;
151 }
152 if (open_err != 0) {
153 ti->err = open_err;
154 break;
155 }
156 /* Request raw descriptor via control transfer.
157 This tests opening, transferring and closing from multiple threads in parallel. */
158 struct libusb_device_descriptor raw_desc;
159 int raw_desc_len = libusb_get_descriptor(dev_handle, LIBUSB_DT_DEVICE, 0, (unsigned char *)&raw_desc, sizeof(raw_desc));
160 if (raw_desc_len < 0) {
161 ti->err = raw_desc_len;
162 goto close;
163 }
164 if (raw_desc_len != sizeof(raw_desc)) {
165 fprintf(stderr, "Thread %d: device %d: unexpected raw descriptor length %d\n",
166 ti->number, i, raw_desc_len);
167 ti->err = LIBUSB_ERROR_OTHER;
168 goto close;
169 }
170 usbi_localize_device_descriptor(&raw_desc);
171 #define ASSERT_EQ(field) if (raw_desc.field != desc.field) { \
172 fprintf(stderr, "Thread %d: device %d: mismatch in field " #field ": %d != %d\n", \
173 ti->number, i, raw_desc.field, desc.field); \
174 ti->err = LIBUSB_ERROR_OTHER; \
175 goto close; \
176 }
177 ASSERT_EQ(bLength);
178 ASSERT_EQ(bDescriptorType);
179 #if !defined(PLATFORM_WINDOWS)
180 /* these are hardcoded by the winusbx HID backend */
181 ASSERT_EQ(bcdUSB);
182 ASSERT_EQ(bDeviceClass);
183 ASSERT_EQ(bDeviceSubClass);
184 ASSERT_EQ(bDeviceProtocol);
185 ASSERT_EQ(bMaxPacketSize0);
186 ASSERT_EQ(bcdDevice);
187 #endif
188 ASSERT_EQ(idVendor);
189 ASSERT_EQ(idProduct);
190 ASSERT_EQ(iManufacturer);
191 ASSERT_EQ(iProduct);
192 ASSERT_EQ(iSerialNumber);
193 ASSERT_EQ(bNumConfigurations);
194 close:
195 libusb_close(dev_handle);
196 }
197 libusb_free_device_list(devs, 1);
198 }
199
200 libusb_exit(ctx);
201 }
202 return (thread_return_t) THREAD_RETURN_VALUE;
203 }
204
test_multi_init(int enumerate)205 static int test_multi_init(int enumerate)
206 {
207 thread_t threadId[NTHREADS];
208 int errs = 0;
209 int t, i;
210 ssize_t last_devcount = 0;
211 int devcount_mismatch = 0;
212 int access_failures = 0;
213
214 printf("Starting %d threads\n", NTHREADS);
215 for (t = 0; t < NTHREADS; t++) {
216 tinfo[t].err = 0;
217 tinfo[t].number = t;
218 tinfo[t].enumerate = enumerate;
219 thread_create(&threadId[t], &init_and_exit, (void *) &tinfo[t]);
220 }
221
222 for (t = 0; t < NTHREADS; t++) {
223 thread_join(threadId[t]);
224 if (tinfo[t].err) {
225 errs++;
226 fprintf(stderr,
227 "Thread %d failed (iteration %d): %s\n",
228 tinfo[t].number,
229 tinfo[t].iteration,
230 libusb_error_name(tinfo[t].err));
231 } else if (enumerate) {
232 if (t > 0 && tinfo[t].devcount != last_devcount) {
233 devcount_mismatch++;
234 printf("Device count mismatch: Thread %d discovered %ld devices instead of %ld\n",
235 tinfo[t].number,
236 (long int) tinfo[t].devcount,
237 (long int) last_devcount);
238 }
239 last_devcount = tinfo[t].devcount;
240 }
241 }
242
243 for (i = 0; i < MAX_DEVCOUNT; i++)
244 if (no_access[i])
245 access_failures++;
246
247 if (enumerate && !devcount_mismatch)
248 printf("All threads discovered %ld devices (%i not opened)\n",
249 (long int) last_devcount, access_failures);
250
251 return errs + devcount_mismatch;
252 }
253
main(void)254 int main(void)
255 {
256 int errs = 0;
257
258 printf("Running multithreaded init/exit test...\n");
259 errs += test_multi_init(0);
260 printf("Running multithreaded init/exit test with enumeration...\n");
261 errs += test_multi_init(1);
262 printf("All done, %d errors\n", errs);
263
264 return errs != 0;
265 }
266