windows_common.c 29 KB

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