Debian Codegraph @

libusb/os/windows_common.c

raw
1 /*
2 * windows backend for libusb 1.0
3 * Copyright © 2009-2012 Pete Batard <[email protected]>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6 * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
7 * Hash table functions adapted from glibc, by Ulrich Drepper et al.
8 * Major code testing contribution by Xiaofan Chen
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 */
24
25 #include <config.h>
26
27 #include <stdio.h>
28
29 #include "libusbi.h"
30 #include "windows_common.h"
31
32 #if defined(LIBUSB_WINDOWS_HOTPLUG)
33 #include "windows_hotplug.h"
34 #endif
35
36 #define EPOCH_TIME UINT64_C(116444736000000000) // 1970.01.01 00:00:000 in MS Filetime
37
38 #define STATUS_SUCCESS ((ULONG_PTR)0UL)
39
40 // Public
41 enum windows_version windows_version = WINDOWS_UNDEFINED;
42
43 // Global variables for init/exit
44 static unsigned int init_count;
45 static bool usbdk_available;
46
47 /*
48 * Converts a windows error to human readable string
49 * uses retval as errorcode, or, if 0, use GetLastError()
50 */
51 #if defined(ENABLE_LOGGING)
52 const char *windows_error_str(DWORD error_code)
53 {
54 static char err_string[256];
55
56 DWORD size;
57 int len;
58
59 if (error_code == 0)
60 error_code = GetLastError();
61
62 len = sprintf(err_string, "[%lu] ", ULONG_CAST(error_code));
63
64 // Translate codes returned by SetupAPI. The ones we are dealing with are either
65 // in 0x0000xxxx or 0xE000xxxx and can be distinguished from standard error codes.
66 // See http://msdn.microsoft.com/en-us/library/windows/hardware/ff545011.aspx
67 switch (error_code & 0xE0000000) {
68 case 0:
69 error_code = HRESULT_FROM_WIN32(error_code); // Still leaves ERROR_SUCCESS unmodified
70 break;
71 case 0xE0000000:
72 error_code = 0x80000000 | (FACILITY_SETUPAPI << 16) | (error_code & 0x0000FFFF);
73 break;
74 default:
75 break;
76 }
77
78 size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
79 NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
80 &err_string[len], sizeof(err_string) - len, NULL);
81 if (size == 0) {
82 DWORD format_error = GetLastError();
83 if (format_error)
84 snprintf(err_string, sizeof(err_string),
85 "Windows error code %lu (FormatMessage error code %lu)",
86 ULONG_CAST(error_code), ULONG_CAST(format_error));
87 else
88 snprintf(err_string, sizeof(err_string), "Unknown error code %lu",
89 ULONG_CAST(error_code));
90 } else {
91 // Remove CRLF from end of message, if present
92 size_t pos = len + size - 2;
93 if (err_string[pos] == '\r')
94 err_string[pos] = '\0';
95 }
96
97 return err_string;
98 }
99 #endif
100
101 /*
102 * Dynamically loads a DLL from the Windows system directory. Unlike the
103 * LoadLibraryA() function, this function will not search through any
104 * directories to try and find the library.
105 */
106 HMODULE load_system_library(struct libusb_context *ctx, const char *name)
107 {
108 char library_path[MAX_PATH];
109 char *filename_start;
110 UINT length;
111
112 length = GetSystemDirectoryA(library_path, sizeof(library_path));
113 if ((length == 0) || (length >= (UINT)sizeof(library_path))) {
114 usbi_err(ctx, "program assertion failed - could not get system directory");
115 return NULL;
116 }
117
118 filename_start = library_path + length;
119 // Append '\' + name + ".dll" + NUL
120 length += 1 + (UINT)strlen(name) + 4 + 1;
121 if (length >= (UINT)sizeof(library_path)) {
122 usbi_err(ctx, "program assertion failed - library path buffer overflow");
123 return NULL;
124 }
125
126 sprintf(filename_start, "\\%s.dll", name);
127 return LoadLibraryA(library_path);
128 }
129
130 /* Hash table functions - modified From glibc 2.3.2:
131 [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
132 [Knuth] The Art of Computer Programming, part 3 (6.4) */
133
134 #define HTAB_SIZE 1021UL // *MUST* be a prime number!!
135
136 typedef struct htab_entry {
137 unsigned long used;
138 char *str;
139 } htab_entry;
140
141 static htab_entry *htab_table;
142 static usbi_mutex_t htab_mutex;
143 static unsigned long htab_filled;
144
145 /* Before using the hash table we must allocate memory for it.
146 We allocate one element more as the found prime number says.
147 This is done for more effective indexing as explained in the
148 comment for the hash function. */
149 static bool htab_create(struct libusb_context *ctx)
150 {
151 if (htab_table != NULL) {
152 usbi_err(ctx, "program assertion failed - hash table already allocated");
153 return true;
154 }
155
156 // Create a mutex
157 usbi_mutex_init(&htab_mutex);
158
159 usbi_dbg(ctx, "using %lu entries hash table", HTAB_SIZE);
160 htab_filled = 0;
161
162 // allocate memory and zero out.
163 htab_table = calloc(HTAB_SIZE + 1, sizeof(htab_entry));
164 if (htab_table == NULL) {
165 usbi_err(ctx, "could not allocate space for hash table");
166 return false;
167 }
168
169 return true;
170 }
171
172 /* After using the hash table it has to be destroyed. */
173 static void htab_destroy(void)
174 {
175 unsigned long i;
176
177 if (htab_table == NULL)
178 return;
179
180 for (i = 0; i < HTAB_SIZE; i++)
181 free(htab_table[i].str);
182
183 safe_free(htab_table);
184
185 usbi_mutex_destroy(&htab_mutex);
186 }
187
188 /* This is the search function. It uses double hashing with open addressing.
189 We use a trick to speed up the lookup. The table is created with one
190 more element available. This enables us to use the index zero special.
191 This index will never be used because we store the first hash index in
192 the field used where zero means not used. Every other value means used.
193 The used field can be used as a first fast comparison for equality of
194 the stored and the parameter value. This helps to prevent unnecessary
195 expensive calls of strcmp. */
196 unsigned long htab_hash(const char *str)
197 {
198 unsigned long hval, hval2;
199 unsigned long idx;
200 unsigned long r = 5381UL;
201 int c;
202 const char *sz = str;
203
204 if (str == NULL)
205 return 0;
206
207 // Compute main hash value (algorithm suggested by Nokia)
208 while ((c = *sz++) != 0)
209 r = ((r << 5) + r) + c;
210 if (r == 0)
211 ++r;
212
213 // compute table hash: simply take the modulus
214 hval = r % HTAB_SIZE;
215 if (hval == 0)
216 ++hval;
217
218 // Try the first index
219 idx = hval;
220
221 // Mutually exclusive access (R/W lock would be better)
222 usbi_mutex_lock(&htab_mutex);
223
224 if (htab_table[idx].used) {
225 if ((htab_table[idx].used == hval) && (strcmp(str, htab_table[idx].str) == 0))
226 goto out_unlock; // existing hash
227
228 usbi_dbg(NULL, "hash collision ('%s' vs '%s')", str, htab_table[idx].str);
229
230 // Second hash function, as suggested in [Knuth]
231 hval2 = 1UL + hval % (HTAB_SIZE - 2);
232
233 do {
234 // Because size is prime this guarantees to step through all available indexes
235 if (idx <= hval2)
236 idx = HTAB_SIZE + idx - hval2;
237 else
238 idx -= hval2;
239
240 // If we visited all entries leave the loop unsuccessfully
241 if (idx == hval)
242 break;
243
244 // If entry is found use it.
245 if ((htab_table[idx].used == hval) && (strcmp(str, htab_table[idx].str) == 0))
246 goto out_unlock;
247 } while (htab_table[idx].used);
248 }
249
250 // Not found => New entry
251
252 // If the table is full return an error
253 if (htab_filled >= HTAB_SIZE) {
254 usbi_err(NULL, "hash table is full (%lu entries)", HTAB_SIZE);
255 idx = 0UL;
256 goto out_unlock;
257 }
258
259 htab_table[idx].str = _strdup(str);
260 if (htab_table[idx].str == NULL) {
261 usbi_err(NULL, "could not duplicate string for hash table");
262 idx = 0UL;
263 goto out_unlock;
264 }
265
266 htab_table[idx].used = hval;
267 ++htab_filled;
268
269 out_unlock:
270 usbi_mutex_unlock(&htab_mutex);
271
272 return idx;
273 }
274
275 enum libusb_transfer_status usbd_status_to_libusb_transfer_status(USBD_STATUS status)
276 {
277 if (USBD_SUCCESS(status))
278 return LIBUSB_TRANSFER_COMPLETED;
279
280 switch (status) {
281 case USBD_STATUS_TIMEOUT:
282 return LIBUSB_TRANSFER_TIMED_OUT;
283 case USBD_STATUS_CANCELED:
284 return LIBUSB_TRANSFER_CANCELLED;
285 case USBD_STATUS_ENDPOINT_HALTED:
286 case USBD_STATUS_STALL_PID:
287 return LIBUSB_TRANSFER_STALL;
288 case USBD_STATUS_DEVICE_GONE:
289 return LIBUSB_TRANSFER_NO_DEVICE;
290 default:
291 usbi_dbg(NULL, "USBD_STATUS 0x%08lx translated to LIBUSB_TRANSFER_ERROR", ULONG_CAST(status));
292 return LIBUSB_TRANSFER_ERROR;
293 }
294 }
295
296 /*
297 * Make a transfer complete synchronously
298 */
299 void windows_force_sync_completion(struct usbi_transfer *itransfer, ULONG size)
300 {
301 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
302 struct windows_context_priv *priv = usbi_get_context_priv(TRANSFER_CTX(transfer));
303 struct windows_transfer_priv *transfer_priv = usbi_get_transfer_priv(itransfer);
304 OVERLAPPED *overlapped = &transfer_priv->overlapped;
305
306 usbi_dbg(TRANSFER_CTX(transfer), "transfer %p, length %lu", transfer, ULONG_CAST(size));
307
308 overlapped->Internal = (ULONG_PTR)STATUS_SUCCESS;
309 overlapped->InternalHigh = (ULONG_PTR)size;
310
311 if (!PostQueuedCompletionStatus(priv->completion_port, (DWORD)size, (ULONG_PTR)transfer->dev_handle, overlapped))
312 usbi_err(TRANSFER_CTX(transfer), "failed to post I/O completion: %s", windows_error_str(0));
313 }
314
315 /* Windows version detection */
316 static BOOL is_x64(void)
317 {
318 BOOL ret = FALSE;
319
320 // Detect if we're running a 32 or 64 bit system
321 if (sizeof(uintptr_t) < 8) {
322 IsWow64Process(GetCurrentProcess(), &ret);
323 } else {
324 ret = TRUE;
325 }
326
327 return ret;
328 }
329
330 static enum windows_version get_windows_version(void)
331 {
332 enum windows_version winver;
333 OSVERSIONINFOEXA vi, vi2;
334 unsigned major, minor, version;
335 ULONGLONG major_equal, minor_equal;
336 const char *w, *arch;
337 bool ws;
338
339 #ifndef ENABLE_LOGGING
340 UNUSED(w); UNUSED(arch);
341 #endif
342 memset(&vi, 0, sizeof(vi));
343 vi.dwOSVersionInfoSize = sizeof(vi);
344 if (!GetVersionExA((OSVERSIONINFOA *)&vi)) {
345 memset(&vi, 0, sizeof(vi));
346 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
347 if (!GetVersionExA((OSVERSIONINFOA *)&vi))
348 return WINDOWS_UNDEFINED;
349 }
350
351 if (vi.dwPlatformId != VER_PLATFORM_WIN32_NT)
352 return WINDOWS_UNDEFINED;
353
354 if ((vi.dwMajorVersion > 6) || ((vi.dwMajorVersion == 6) && (vi.dwMinorVersion >= 2))) {
355 // Starting with Windows 8.1 Preview, GetVersionEx() does no longer report the actual OS version
356 // See: http://msdn.microsoft.com/en-us/library/windows/desktop/dn302074.aspx
357 // And starting with Windows 10 Preview 2, Windows enforces the use of the application/supportedOS
358 // manifest in order for VerSetConditionMask() to report the ACTUAL OS major and minor...
359
360 major_equal = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL);
361 for (major = vi.dwMajorVersion; major <= 9; major++) {
362 memset(&vi2, 0, sizeof(vi2));
363 vi2.dwOSVersionInfoSize = sizeof(vi2);
364 vi2.dwMajorVersion = major;
365 if (!VerifyVersionInfoA(&vi2, VER_MAJORVERSION, major_equal))
366 continue;
367
368 if (vi.dwMajorVersion < major) {
369 vi.dwMajorVersion = major;
370 vi.dwMinorVersion = 0;
371 }
372
373 minor_equal = VerSetConditionMask(0, VER_MINORVERSION, VER_EQUAL);
374 for (minor = vi.dwMinorVersion; minor <= 9; minor++) {
375 memset(&vi2, 0, sizeof(vi2));
376 vi2.dwOSVersionInfoSize = sizeof(vi2);
377 vi2.dwMinorVersion = minor;
378 if (!VerifyVersionInfoA(&vi2, VER_MINORVERSION, minor_equal))
379 continue;
380
381 vi.dwMinorVersion = minor;
382 break;
383 }
384
385 break;
386 }
387 }
388
389 if ((vi.dwMajorVersion > 0xf) || (vi.dwMinorVersion > 0xf))
390 return WINDOWS_UNDEFINED;
391
392 ws = (vi.wProductType <= VER_NT_WORKSTATION);
393 version = vi.dwMajorVersion << 4 | vi.dwMinorVersion;
394
395 switch (version) {
396 case 0x50: winver = WINDOWS_2000; w = "2000"; break;
397 case 0x51: winver = WINDOWS_XP; w = "XP"; break;
398 case 0x52: winver = WINDOWS_2003; w = "2003"; break;
399 case 0x60: winver = WINDOWS_VISTA; w = (ws ? "Vista" : "2008"); break;
400 case 0x61: winver = WINDOWS_7; w = (ws ? "7" : "2008_R2"); break;
401 case 0x62: winver = WINDOWS_8; w = (ws ? "8" : "2012"); break;
402 case 0x63: winver = WINDOWS_8_1; w = (ws ? "8.1" : "2012_R2"); break;
403 case 0x64: // Early Windows 10 Insider Previews and Windows Server 2017 Technical Preview 1 used version 6.4
404 case 0xA0: winver = WINDOWS_10; w = (ws ? "10" : "2016");
405 if (vi.dwBuildNumber < 20000)
406 break;
407 // fallthrough
408 case 0xB0: winver = WINDOWS_11; w = (ws ? "11" : "2022"); break;
409 default:
410 if (version < 0x50)
411 return WINDOWS_UNDEFINED;
412 winver = WINDOWS_12_OR_LATER;
413 w = "12 or later";
414 }
415
416 // We cannot tell if we are on 8, 10, or 11 without "app manifest"
417 if (version == 0x62 && vi.dwBuildNumber == 9200)
418 w = "8 (or later)";
419
420 arch = is_x64() ? "64-bit" : "32-bit";
421
422 if (vi.wServicePackMinor)
423 usbi_dbg(NULL, "Windows %s SP%u.%u %s", w, vi.wServicePackMajor, vi.wServicePackMinor, arch);
424 else if (vi.wServicePackMajor)
425 usbi_dbg(NULL, "Windows %s SP%u %s", w, vi.wServicePackMajor, arch);
426 else
427 usbi_dbg(NULL, "Windows %s %s", w, arch);
428
429 return winver;
430 }
431
432 static unsigned __stdcall windows_iocp_thread(void *arg)
433 {
434 struct libusb_context *ctx = arg;
435 struct windows_context_priv *priv = usbi_get_context_priv(ctx);
436 HANDLE iocp = priv->completion_port;
437 DWORD num_bytes;
438 ULONG_PTR completion_key;
439 OVERLAPPED *overlapped;
440 struct libusb_device_handle *dev_handle;
441 struct libusb_device_handle *opened_device_handle;
442 struct windows_device_handle_priv *handle_priv;
443 struct windows_transfer_priv *transfer_priv;
444 struct usbi_transfer *itransfer;
445 bool found;
446
447 usbi_dbg(ctx, "I/O completion thread started");
448
449 while (true) {
450 overlapped = NULL;
451 if (!GetQueuedCompletionStatus(iocp, &num_bytes, &completion_key, &overlapped, INFINITE) && (overlapped == NULL)) {
452 usbi_err(ctx, "GetQueuedCompletionStatus failed: %s", windows_error_str(0));
453 break;
454 }
455
456 if (overlapped == NULL) {
457 // Signal to quit
458 if (completion_key != (ULONG_PTR)ctx)
459 usbi_err(ctx, "program assertion failed - overlapped is NULL");
460 break;
461 }
462
463 // Find the transfer associated with the OVERLAPPED that just completed.
464 // If we cannot find a match, the I/O operation originated from outside of libusb
465 // (e.g. within libusbK) and we need to ignore it.
466 dev_handle = (struct libusb_device_handle *)completion_key;
467
468 found = false;
469 transfer_priv = NULL;
470
471 // Issue 912: lock opened device handles in context to search the current device handle
472 // to avoid accessing unallocated memory after device has been closed
473 usbi_mutex_lock(&ctx->open_devs_lock);
474 for_each_open_device(ctx, opened_device_handle) {
475 if (dev_handle == opened_device_handle) {
476 handle_priv = usbi_get_device_handle_priv(dev_handle);
477
478 usbi_mutex_lock(&dev_handle->lock);
479 list_for_each_entry(transfer_priv, &handle_priv->active_transfers, list, struct windows_transfer_priv) {
480 if (overlapped == &transfer_priv->overlapped) {
481 // This OVERLAPPED belongs to us, remove the transfer from the device handle's list
482 list_del(&transfer_priv->list);
483 found = true;
484 break;
485 }
486 }
487 usbi_mutex_unlock(&dev_handle->lock);
488 }
489 }
490 usbi_mutex_unlock(&ctx->open_devs_lock);
491
492 if (!found) {
493 usbi_dbg(ctx, "ignoring overlapped %p for handle %p",
494 overlapped, dev_handle);
495 continue;
496 }
497
498 itransfer = TRANSFER_PRIV_TO_USBI_TRANSFER(transfer_priv);
499 #ifdef ENABLE_LOGGING
500 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
501 usbi_dbg(ctx, "transfer %p completed, length %lu",
502 transfer, ULONG_CAST(num_bytes));
503 #endif
504 usbi_signal_transfer_completion(itransfer);
505 }
506
507 usbi_dbg(ctx, "I/O completion thread exiting");
508
509 return 0;
510 }
511
512 static int windows_init(struct libusb_context *ctx)
513 {
514 struct windows_context_priv *priv = usbi_get_context_priv(ctx);
515 bool winusb_backend_init = false;
516 int r;
517
518 // NB: concurrent usage supposes that init calls are equally balanced with
519 // exit calls. If init is called more than exit, we will not exit properly
520 if (++init_count == 1) { // First init?
521 windows_version = get_windows_version();
522 if (windows_version == WINDOWS_UNDEFINED) {
523 usbi_err(ctx, "failed to detect Windows version");
524 r = LIBUSB_ERROR_NOT_SUPPORTED;
525 goto init_exit;
526 } else if (windows_version < WINDOWS_VISTA) {
527 usbi_err(ctx, "Windows version is too old");
528 r = LIBUSB_ERROR_NOT_SUPPORTED;
529 goto init_exit;
530 }
531
532 if (!htab_create(ctx)) {
533 r = LIBUSB_ERROR_NO_MEM;
534 goto init_exit;
535 }
536
537 r = winusb_backend.init(ctx);
538 if (r != LIBUSB_SUCCESS)
539 goto init_exit;
540 winusb_backend_init = true;
541
542 r = usbdk_backend.init(ctx);
543 if (r == LIBUSB_SUCCESS) {
544 usbi_dbg(ctx, "UsbDk backend is available");
545 usbdk_available = true;
546 } else {
547 usbi_info(ctx, "UsbDk backend is not available");
548 // Do not report this as an error
549 }
550 }
551
552 // By default, new contexts will use the WinUSB backend
553 priv->backend = &winusb_backend;
554
555 r = LIBUSB_ERROR_NO_MEM;
556
557 // Use an I/O completion port to manage all transfers for this context
558 priv->completion_port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
559 if (priv->completion_port == NULL) {
560 usbi_err(ctx, "failed to create I/O completion port: %s", windows_error_str(0));
561 goto init_exit;
562 }
563
564 // And a dedicated thread to wait for I/O completions
565 priv->completion_port_thread = (HANDLE)_beginthreadex(NULL, 0, windows_iocp_thread, ctx, 0, NULL);
566 if (priv->completion_port_thread == NULL) {
567 usbi_err(ctx, "failed to create I/O completion port thread");
568 CloseHandle(priv->completion_port);
569 goto init_exit;
570 }
571
572 r = LIBUSB_SUCCESS;
573
574 #if defined(LIBUSB_WINDOWS_HOTPLUG)
575 if (init_count == 1) {
576 r = windows_start_event_monitor(); // Start-up hotplug event handler
577 if (r != LIBUSB_SUCCESS) {
578 usbi_err(ctx, "error starting hotplug event monitor");
579 goto init_exit;
580 }
581 }
582
583 windows_initial_scan_devices(ctx);
584 #endif
585
586 init_exit: // Holds semaphore here
587 if ((init_count == 1) && (r != LIBUSB_SUCCESS)) { // First init failed?
588 if (usbdk_available) {
589 usbdk_backend.exit(ctx);
590 usbdk_available = false;
591 }
592 if (winusb_backend_init)
593 winusb_backend.exit(ctx);
594 htab_destroy();
595 --init_count;
596 }
597
598 return r;
599 }
600
601 static void windows_exit(struct libusb_context *ctx)
602 {
603 struct windows_context_priv *priv = usbi_get_context_priv(ctx);
604
605 // A NULL completion status will indicate to the thread that it is time to exit
606 if (!PostQueuedCompletionStatus(priv->completion_port, 0, (ULONG_PTR)ctx, NULL))
607 usbi_err(ctx, "failed to post I/O completion: %s", windows_error_str(0));
608
609 if (WaitForSingleObject(priv->completion_port_thread, INFINITE) == WAIT_FAILED)
610 usbi_err(ctx, "failed to wait for I/O completion port thread: %s", windows_error_str(0));
611
612 CloseHandle(priv->completion_port_thread);
613 CloseHandle(priv->completion_port);
614
615 // Only works if exits and inits are balanced exactly
616 if (--init_count == 0) { // Last exit
617 #if defined(LIBUSB_WINDOWS_HOTPLUG)
618 windows_stop_event_monitor();
619 #endif
620 if (usbdk_available) {
621 usbdk_backend.exit(ctx);
622 usbdk_available = false;
623 }
624 winusb_backend.exit(ctx);
625 htab_destroy();
626 }
627 }
628
629 static int windows_set_option(struct libusb_context *ctx, enum libusb_option option, va_list ap)
630 {
631 struct windows_context_priv *priv = usbi_get_context_priv(ctx);
632
633 UNUSED(ap);
634
635 if (option == LIBUSB_OPTION_USE_USBDK) {
636 if (!usbdk_available) {
637 usbi_err(ctx, "UsbDk backend not available");
638 return LIBUSB_ERROR_NOT_FOUND;
639 }
640 usbi_dbg(ctx, "switching context %p to use UsbDk backend", ctx);
641 priv->backend = &usbdk_backend;
642 return LIBUSB_SUCCESS;
643 }
644
645 return LIBUSB_ERROR_NOT_SUPPORTED;
646 }
647
648 #if !defined(LIBUSB_WINDOWS_HOTPLUG)
649 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **discdevs)
650 {
651 struct windows_context_priv *priv = usbi_get_context_priv(ctx);
652 return priv->backend->get_device_list(ctx, discdevs);
653 }
654 #endif
655
656 static int windows_get_device_string(libusb_device *dev,
657 enum libusb_device_string_type string_type, char *data, int length)
658 {
659 struct windows_context_priv* priv = usbi_get_context_priv(DEVICE_CTX(dev));
660 if (NULL != priv->backend->get_device_string) {
661 return priv->backend->get_device_string(dev, string_type, data, length);
662 }
663 return LIBUSB_ERROR_NOT_SUPPORTED;
664 }
665
666 static int windows_open(struct libusb_device_handle *dev_handle)
667 {
668 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
669 struct windows_device_handle_priv *handle_priv = usbi_get_device_handle_priv(dev_handle);
670
671 list_init(&handle_priv->active_transfers);
672 return priv->backend->open(dev_handle);
673 }
674
675 static void windows_close(struct libusb_device_handle *dev_handle)
676 {
677 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
678 priv->backend->close(dev_handle);
679 }
680
681 static int windows_get_active_config_descriptor(struct libusb_device *dev,
682 void *buffer, size_t len)
683 {
684 struct windows_context_priv *priv = usbi_get_context_priv(DEVICE_CTX(dev));
685 return priv->backend->get_active_config_descriptor(dev, buffer, len);
686 }
687
688 static int windows_get_config_descriptor(struct libusb_device *dev,
689 uint8_t config_index, void *buffer, size_t len)
690 {
691 struct windows_context_priv *priv = usbi_get_context_priv(DEVICE_CTX(dev));
692 return priv->backend->get_config_descriptor(dev, config_index, buffer, len);
693 }
694
695 static int windows_get_config_descriptor_by_value(struct libusb_device *dev,
696 uint8_t bConfigurationValue, void **buffer)
697 {
698 struct windows_context_priv *priv = usbi_get_context_priv(DEVICE_CTX(dev));
699 return priv->backend->get_config_descriptor_by_value(dev, bConfigurationValue, buffer);
700 }
701
702 static int windows_get_configuration(struct libusb_device_handle *dev_handle, uint8_t *config)
703 {
704 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
705 return priv->backend->get_configuration(dev_handle, config);
706 }
707
708 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
709 {
710 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
711 if (config == -1)
712 config = 0;
713 return priv->backend->set_configuration(dev_handle, (uint8_t)config);
714 }
715
716 static int windows_claim_interface(struct libusb_device_handle *dev_handle, uint8_t interface_number)
717 {
718 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
719 return priv->backend->claim_interface(dev_handle, interface_number);
720 }
721
722 static int windows_release_interface(struct libusb_device_handle *dev_handle, uint8_t interface_number)
723 {
724 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
725 return priv->backend->release_interface(dev_handle, interface_number);
726 }
727
728 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle,
729 uint8_t interface_number, uint8_t altsetting)
730 {
731 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
732 return priv->backend->set_interface_altsetting(dev_handle, interface_number, altsetting);
733 }
734
735 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
736 {
737 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
738 return priv->backend->clear_halt(dev_handle, endpoint);
739 }
740
741 static int windows_reset_device(struct libusb_device_handle *dev_handle)
742 {
743 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
744 return priv->backend->reset_device(dev_handle);
745 }
746
747 static void windows_destroy_device(struct libusb_device *dev)
748 {
749 struct windows_context_priv *priv = usbi_get_context_priv(DEVICE_CTX(dev));
750 priv->backend->destroy_device(dev);
751 }
752
753 static int windows_endpoint_supports_raw_io(libusb_device_handle* dev_handle,
754 uint8_t endpoint)
755 {
756 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
757 if (priv->backend->endpoint_supports_raw_io)
758 return priv->backend->endpoint_supports_raw_io(dev_handle, endpoint);
759 return LIBUSB_ERROR_NOT_SUPPORTED;
760 }
761
762 static int windows_endpoint_set_raw_io(libusb_device_handle* dev_handle,
763 uint8_t endpoint, int enable)
764 {
765 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
766
767 if (priv->backend->endpoint_supports_raw_io == NULL
768 || priv->backend->endpoint_supports_raw_io(dev_handle, endpoint) != 1
769 || priv->backend->endpoint_set_raw_io == NULL)
770 return LIBUSB_ERROR_NOT_SUPPORTED;
771
772 return priv->backend->endpoint_set_raw_io(dev_handle, endpoint, enable);
773 }
774
775 static int windows_get_max_raw_io_transfer_size(struct libusb_device_handle *dev_handle,
776 uint8_t endpoint)
777 {
778 struct windows_context_priv *priv = usbi_get_context_priv(HANDLE_CTX(dev_handle));
779 if (priv->backend->get_max_raw_io_transfer_size)
780 return priv->backend->get_max_raw_io_transfer_size(dev_handle, endpoint);
781 return LIBUSB_ERROR_NOT_SUPPORTED;
782 }
783
784 static int windows_submit_transfer(struct usbi_transfer *itransfer)
785 {
786 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
787 struct libusb_device_handle *dev_handle = transfer->dev_handle;
788 struct libusb_context *ctx = HANDLE_CTX(dev_handle);
789 struct windows_context_priv *priv = usbi_get_context_priv(ctx);
790 struct windows_device_handle_priv *handle_priv = usbi_get_device_handle_priv(dev_handle);
791 struct windows_transfer_priv *transfer_priv = usbi_get_transfer_priv(itransfer);
792 int r;
793
794 switch (transfer->type) {
795 case LIBUSB_TRANSFER_TYPE_CONTROL:
796 case LIBUSB_TRANSFER_TYPE_BULK:
797 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
798 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
799 break;
800 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
801 usbi_warn(ctx, "bulk stream transfers are not yet supported on this platform");
802 return LIBUSB_ERROR_NOT_SUPPORTED;
803 default:
804 usbi_err(ctx, "unknown endpoint type %d", transfer->type);
805 return LIBUSB_ERROR_INVALID_PARAM;
806 }
807
808 if (transfer_priv->handle != NULL) {
809 usbi_err(ctx, "program assertion failed - transfer HANDLE is not NULL");
810 transfer_priv->handle = NULL;
811 }
812
813 // Add transfer to the device handle's list
814 usbi_mutex_lock(&dev_handle->lock);
815 list_add_tail(&transfer_priv->list, &handle_priv->active_transfers);
816 usbi_mutex_unlock(&dev_handle->lock);
817
818 r = priv->backend->submit_transfer(itransfer);
819 if (r != LIBUSB_SUCCESS) {
820 // Remove the unsuccessful transfer from the device handle's list
821 usbi_mutex_lock(&dev_handle->lock);
822 list_del(&transfer_priv->list);
823 usbi_mutex_unlock(&dev_handle->lock);
824
825 // Always call the backend's clear_transfer_priv() function on failure
826 priv->backend->clear_transfer_priv(itransfer);
827 transfer_priv->handle = NULL;
828 return r;
829 }
830
831 // The backend should set the HANDLE used for each submitted transfer
832 // by calling set_transfer_priv_handle()
833 if (transfer_priv->handle == NULL)
834 usbi_err(ctx, "program assertion failed - transfer HANDLE is NULL after transfer was submitted");
835
836 return r;
837 }
838
839 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
840 {
841 struct windows_context_priv *priv = usbi_get_context_priv(ITRANSFER_CTX(itransfer));
842 struct windows_transfer_priv *transfer_priv = usbi_get_transfer_priv(itransfer);
843
844 // Try CancelIoEx() on the transfer
845 // If that fails, fall back to the backend's cancel_transfer()
846 // function if it is available
847 if (CancelIoEx(transfer_priv->handle, &transfer_priv->overlapped))
848 return LIBUSB_SUCCESS;
849 else if (GetLastError() == ERROR_NOT_FOUND)
850 return LIBUSB_ERROR_NOT_FOUND;
851
852 if (priv->backend->cancel_transfer)
853 return priv->backend->cancel_transfer(itransfer);
854
855 usbi_warn(ITRANSFER_CTX(itransfer), "cancellation not supported for this transfer's driver");
856 return LIBUSB_ERROR_NOT_SUPPORTED;
857 }
858
859 static int windows_handle_transfer_completion(struct usbi_transfer *itransfer)
860 {
861 struct libusb_context *ctx = ITRANSFER_CTX(itransfer);
862 struct windows_context_priv *priv = usbi_get_context_priv(ctx);
863 const struct windows_backend *backend = priv->backend;
864 struct windows_transfer_priv *transfer_priv = usbi_get_transfer_priv(itransfer);
865 enum libusb_transfer_status status, istatus;
866 DWORD result, bytes_transferred;
867 HANDLE transfer_handle;
868
869 /*
870 * The submit path runs with itransfer->lock held. Grab the handle under
871 * the same lock so we do not race with submission/completion bookkeeping.
872 */
873 usbi_mutex_lock(&itransfer->lock);
874 transfer_handle = transfer_priv->handle;
875 usbi_mutex_unlock(&itransfer->lock);
876
877 if (GetOverlappedResult(transfer_handle, &transfer_priv->overlapped, &bytes_transferred, FALSE))
878 result = NO_ERROR;
879 else
880 result = GetLastError();
881
882 #ifdef ENABLE_LOGGING
883 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
884 usbi_dbg(ctx, "handling transfer %p completion with errcode %lu, length %lu",
885 transfer, ULONG_CAST(result), ULONG_CAST(bytes_transferred));
886 #endif
887
888 switch (result) {
889 case NO_ERROR:
890 status = backend->copy_transfer_data(itransfer, bytes_transferred);
891 break;
892 case ERROR_GEN_FAILURE:
893 usbi_dbg(ctx, "detected endpoint stall");
894 status = LIBUSB_TRANSFER_STALL;
895 break;
896 case ERROR_SEM_TIMEOUT:
897 usbi_dbg(ctx, "detected semaphore timeout");
898 status = LIBUSB_TRANSFER_TIMED_OUT;
899 break;
900 case ERROR_OPERATION_ABORTED:
901 istatus = backend->copy_transfer_data(itransfer, bytes_transferred);
902 if (istatus != LIBUSB_TRANSFER_COMPLETED)
903 usbi_dbg(ctx, "failed to copy partial data in aborted operation: %d", (int)istatus);
904
905 usbi_dbg(ctx, "detected operation aborted");
906 status = LIBUSB_TRANSFER_CANCELLED;
907 break;
908 case ERROR_FILE_NOT_FOUND:
909 case ERROR_DEVICE_NOT_CONNECTED:
910 case ERROR_NO_SUCH_DEVICE:
911 usbi_dbg(ctx, "detected device removed");
912 status = LIBUSB_TRANSFER_NO_DEVICE;
913 break;
914 default:
915 usbi_err(ctx, "detected I/O error %lu: %s",
916 ULONG_CAST(result), windows_error_str(result));
917 status = LIBUSB_TRANSFER_ERROR;
918 break;
919 }
920
921 usbi_mutex_lock(&itransfer->lock);
922 transfer_priv->handle = NULL;
923 usbi_mutex_unlock(&itransfer->lock);
924
925 // Backend-specific cleanup
926 backend->clear_transfer_priv(itransfer);
927
928 if (status == LIBUSB_TRANSFER_CANCELLED)
929 return usbi_handle_transfer_cancellation(itransfer);
930 else
931 return usbi_handle_transfer_completion(itransfer, status);
932 }
933
934 #ifndef HAVE_CLOCK_GETTIME
935 void usbi_get_monotonic_time(struct timespec *tp)
936 {
937 static LONG hires_counter_init;
938 static uint64_t hires_ticks_to_ps;
939 static uint64_t hires_frequency;
940 LARGE_INTEGER hires_counter;
941
942 if (InterlockedExchange(&hires_counter_init, 1L) == 0L) {
943 LARGE_INTEGER li_frequency;
944
945 // Microsoft says that the QueryPerformanceFrequency() and
946 // QueryPerformanceCounter() functions always succeed on XP and later
947 QueryPerformanceFrequency(&li_frequency);
948
949 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
950 // to picoseconds to compute the tv_nsecs part
951 hires_frequency = li_frequency.QuadPart;
952 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
953 }
954
955 QueryPerformanceCounter(&hires_counter);
956 tp->tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
957 tp->tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency) * hires_ticks_to_ps) / UINT64_C(1000));
958 }
959 #endif
960
961 // NB: MSVC6 does not support named initializers.
962 const struct usbi_os_backend usbi_backend = {
963 "Windows",
964 USBI_CAP_HAS_HID_ACCESS,
965 windows_init,
966 windows_exit,
967 windows_set_option,
968 #if defined(LIBUSB_WINDOWS_HOTPLUG)
969 NULL, /* get_device_list */
970 #else
971 windows_get_device_list,
972 #endif
973 windows_get_device_string,
974 NULL, /* hotplug_poll */
975 NULL, /* wrap_sys_device */
976 windows_open,
977 windows_close,
978 windows_get_active_config_descriptor,
979 windows_get_config_descriptor,
980 windows_get_config_descriptor_by_value,
981 windows_get_configuration,
982 windows_set_configuration,
983 windows_claim_interface,
984 windows_release_interface,
985 windows_set_interface_altsetting,
986 windows_clear_halt,
987 windows_reset_device,
988 NULL, /* alloc_streams */
989 NULL, /* free_streams */
990 NULL, /* dev_mem_alloc */
991 NULL, /* dev_mem_free */
992 NULL, /* kernel_driver_active */
993 NULL, /* detach_kernel_driver */
994 NULL, /* attach_kernel_driver */
995 windows_endpoint_supports_raw_io,
996 windows_endpoint_set_raw_io,
997 windows_get_max_raw_io_transfer_size,
998 windows_destroy_device,
999 windows_submit_transfer,
1000 windows_cancel_transfer,
1001 NULL, /* clear_transfer_priv */
1002 NULL, /* handle_events */
1003 windows_handle_transfer_completion,
1004 sizeof(struct windows_context_priv),
1005 sizeof(union windows_device_priv),
1006 sizeof(struct windows_device_handle_priv),
1007 sizeof(struct windows_transfer_priv),
1008 };