Merge tag 'v0.2.0'
[rtmpclient.git] / app / src / main / jni / libusb / libusb / core.c
1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2 /*
3  * add some functions for no-rooted Android
4  * add optimaization when compiling with gcc
5  * Copyright © 2014-2017 saki <t_saki@serenegiant.com>
6  *
7  * Core functions for libusb
8  * Copyright © 2012-2013 Nathan Hjelm <hjelmn@cs.unm.edu>
9  * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
10  * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25  */
26
27 #define LOCAL_DEBUG 0
28
29 #define LOG_TAG "libusb/core"
30 #if 1   // デバッグ情報を出さない時1
31         #ifndef LOG_NDEBUG
32                 #define LOG_NDEBUG              // LOGV/LOGD/MARKを出力しない時
33                 #endif
34         #undef USE_LOGALL                       // 指定したLOGxだけを出力
35 #else
36         #define USE_LOGALL
37         #undef LOG_NDEBUG
38         #undef NDEBUG
39         #define GET_RAW_DESCRIPTOR
40 #endif
41
42 #include "config.h"
43 #include <assert.h>             // XXX add assert for debugging
44
45 #include <errno.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #ifdef HAVE_SYS_TYPES_H
51 #include <sys/types.h>
52 #endif
53 #ifdef HAVE_SYS_TIME_H
54 #include <sys/time.h>
55 #endif
56 #ifdef HAVE_SYSLOG_H
57 #include <syslog.h>
58 #endif
59
60 #ifdef __ANDROID__
61 #include <android/log.h>
62 #endif
63
64 #include "libusbi.h"
65 #include "hotplug.h"
66
67 #if defined(OS_ANDROID) // XXX for non rooted android device
68 const struct usbi_os_backend * const usbi_backend = &android_usbfs_backend;
69 #elif defined(OS_LINUX)
70 const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
71 #elif defined(OS_DARWIN)
72 const struct usbi_os_backend * const usbi_backend = &darwin_backend;
73 #elif defined(OS_OPENBSD)
74 const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
75 #elif defined(OS_NETBSD)
76 const struct usbi_os_backend * const usbi_backend = &netbsd_backend;
77 #elif defined(OS_WINDOWS)
78 const struct usbi_os_backend * const usbi_backend = &windows_backend;
79 #elif defined(OS_WINCE)
80 const struct usbi_os_backend * const usbi_backend = &wince_backend;
81 #else
82 #error "Unsupported OS"
83 #endif
84
85 struct libusb_context *usbi_default_context = NULL;
86 static const struct libusb_version libusb_version_internal =
87         { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
88           LIBUSB_RC, "http://libusb.info" };
89 static int default_context_refcnt = 0;
90 static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
91 static struct timeval timestamp_origin = { 0, 0 };
92
93 usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
94 struct list_head active_contexts_list;
95
96 #ifdef __ANDROID__
97 int android_generate_device(struct libusb_context *ctx, struct libusb_device **dev,
98         int vid, int pid, const char *serial, int fd, int busnum, int devaddr);
99 #endif
100
101 /**
102  * \mainpage libusb-1.0 API Reference
103  *
104  * \section intro Introduction
105  *
106  * libusb is an open source library that allows you to communicate with USB
107  * devices from userspace. For more info, see the
108  * <a href="http://libusb.info">libusb homepage</a>.
109  *
110  * This documentation is aimed at application developers wishing to
111  * communicate with USB peripherals from their own software. After reviewing
112  * this documentation, feedback and questions can be sent to the
113  * <a href="http://mailing-list.libusb.info">libusb-devel mailing list</a>.
114  *
115  * This documentation assumes knowledge of how to operate USB devices from
116  * a software standpoint (descriptors, configurations, interfaces, endpoints,
117  * control/bulk/interrupt/isochronous transfers, etc). Full information
118  * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
119  * Specification</a> which is available for free download. You can probably
120  * find less verbose introductions by searching the web.
121  *
122  * \section features Library features
123  *
124  * - All transfer types supported (control/bulk/interrupt/isochronous)
125  * - 2 transfer interfaces:
126  *    -# Synchronous (simple)
127  *    -# Asynchronous (more complicated, but more powerful)
128  * - Thread safe (although the asynchronous interface means that you
129  *   usually won't need to thread)
130  * - Lightweight with lean API
131  * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
132  * - Hotplug support (on some platforms). See \ref hotplug.
133  *
134  * \section gettingstarted Getting Started
135  *
136  * To begin reading the API documentation, start with the Modules page which
137  * links to the different categories of libusb's functionality.
138  *
139  * One decision you will have to make is whether to use the synchronous
140  * or the asynchronous data transfer interface. The \ref io documentation
141  * provides some insight into this topic.
142  *
143  * Some example programs can be found in the libusb source distribution under
144  * the "examples" subdirectory. The libusb homepage includes a list of
145  * real-life project examples which use libusb.
146  *
147  * \section errorhandling Error handling
148  *
149  * libusb functions typically return 0 on success or a negative error code
150  * on failure. These negative error codes relate to LIBUSB_ERROR constants
151  * which are listed on the \ref misc "miscellaneous" documentation page.
152  *
153  * \section msglog Debug message logging
154  *
155  * libusb uses stderr for all logging. By default, logging is set to NONE,
156  * which means that no output will be produced. However, unless the library
157  * has been compiled with logging disabled, then any application calls to
158  * libusb_set_debug(), or the setting of the environmental variable
159  * LIBUSB_DEBUG outside of the application, can result in logging being
160  * produced. Your application should therefore not close stderr, but instead
161  * direct it to the null device if its output is undesireable.
162  *
163  * The libusb_set_debug() function can be used to enable logging of certain
164  * messages. Under standard configuration, libusb doesn't really log much
165  * so you are advised to use this function to enable all error/warning/
166  * informational messages. It will help debug problems with your software.
167  *
168  * The logged messages are unstructured. There is no one-to-one correspondence
169  * between messages being logged and success or failure return codes from
170  * libusb functions. There is no format to the messages, so you should not
171  * try to capture or parse them. They are not and will not be localized.
172  * These messages are not intended to being passed to your application user;
173  * instead, you should interpret the error codes returned from libusb functions
174  * and provide appropriate notification to the user. The messages are simply
175  * there to aid you as a programmer, and if you're confused because you're
176  * getting a strange error code from a libusb function, enabling message
177  * logging may give you a suitable explanation.
178  *
179  * The LIBUSB_DEBUG environment variable can be used to enable message logging
180  * at run-time. This environment variable should be set to a log level number,
181  * which is interpreted the same as the libusb_set_debug() parameter. When this
182  * environment variable is set, the message logging verbosity level is fixed
183  * and libusb_set_debug() effectively does nothing.
184  *
185  * libusb can be compiled without any logging functions, useful for embedded
186  * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
187  * variable have no effects.
188  *
189  * libusb can also be compiled with verbose debugging messages always. When
190  * the library is compiled in this way, all messages of all verbosities are
191  * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
192  * have no effects.
193  *
194  * \section remarks Other remarks
195  *
196  * libusb does have imperfections. The \ref caveats "caveats" page attempts
197  * to document these.
198  */
199
200 /**
201  * \page caveats Caveats
202  *
203  * \section devresets Device resets
204  *
205  * The libusb_reset_device() function allows you to reset a device. If your
206  * program has to call such a function, it should obviously be aware that
207  * the reset will cause device state to change (e.g. register values may be
208  * reset).
209  *
210  * The problem is that any other program could reset the device your program
211  * is working with, at any time. libusb does not offer a mechanism to inform
212  * you when this has happened, so if someone else resets your device it will
213  * not be clear to your own program why the device state has changed.
214  *
215  * Ultimately, this is a limitation of writing drivers in userspace.
216  * Separation from the USB stack in the underlying kernel makes it difficult
217  * for the operating system to deliver such notifications to your program.
218  * The Linux kernel USB stack allows such reset notifications to be delivered
219  * to in-kernel USB drivers, but it is not clear how such notifications could
220  * be delivered to second-class drivers that live in userspace.
221  *
222  * \section blockonly Blocking-only functionality
223  *
224  * The functionality listed below is only available through synchronous,
225  * blocking functions. There are no asynchronous/non-blocking alternatives,
226  * and no clear ways of implementing these.
227  *
228  * - Configuration activation (libusb_set_configuration())
229  * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
230  * - Releasing of interfaces (libusb_release_interface())
231  * - Clearing of halt/stall condition (libusb_clear_halt())
232  * - Device resets (libusb_reset_device())
233  *
234  * \section configsel Configuration selection and handling
235  *
236  * When libusb presents a device handle to an application, there is a chance
237  * that the corresponding device may be in unconfigured state. For devices
238  * with multiple configurations, there is also a chance that the configuration
239  * currently selected is not the one that the application wants to use.
240  *
241  * The obvious solution is to add a call to libusb_set_configuration() early
242  * on during your device initialization routines, but there are caveats to
243  * be aware of:
244  * -# If the device is already in the desired configuration, calling
245  *    libusb_set_configuration() using the same configuration value will cause
246  *    a lightweight device reset. This may not be desirable behaviour.
247  * -# libusb will be unable to change configuration if the device is in
248  *    another configuration and other programs or drivers have claimed
249  *    interfaces under that configuration.
250  * -# In the case where the desired configuration is already active, libusb
251  *    may not even be able to perform a lightweight device reset. For example,
252  *    take my USB keyboard with fingerprint reader: I'm interested in driving
253  *    the fingerprint reader interface through libusb, but the kernel's
254  *    USB-HID driver will almost always have claimed the keyboard interface.
255  *    Because the kernel has claimed an interface, it is not even possible to
256  *    perform the lightweight device reset, so libusb_set_configuration() will
257  *    fail. (Luckily the device in question only has a single configuration.)
258  *
259  * One solution to some of the above problems is to consider the currently
260  * active configuration. If the configuration we want is already active, then
261  * we don't have to select any configuration:
262  \code
263  cfg = libusb_get_configuration(dev);
264  if (cfg != desired)
265  libusb_set_configuration(dev, desired);
266  \endcode
267  *
268  * This is probably suitable for most scenarios, but is inherently racy:
269  * another application or driver may change the selected configuration
270  * <em>after</em> the libusb_get_configuration() call.
271  *
272  * Even in cases where libusb_set_configuration() succeeds, consider that other
273  * applications or drivers may change configuration after your application
274  * calls libusb_set_configuration().
275  *
276  * One possible way to lock your device into a specific configuration is as
277  * follows:
278  * -# Set the desired configuration (or use the logic above to realise that
279  *    it is already in the desired configuration)
280  * -# Claim the interface that you wish to use
281  * -# Check that the currently active configuration is the one that you want
282  *    to use.
283  *
284  * The above method works because once an interface is claimed, no application
285  * or driver is able to select another configuration.
286  *
287  * \section earlycomp Early transfer completion
288  *
289  * NOTE: This section is currently Linux-centric. I am not sure if any of these
290  * considerations apply to Darwin or other platforms.
291  *
292  * When a transfer completes early (i.e. when less data is received/sent in
293  * any one packet than the transfer buffer allows for) then libusb is designed
294  * to terminate the transfer immediately, not transferring or receiving any
295  * more data unless other transfers have been queued by the user.
296  *
297  * On legacy platforms, libusb is unable to do this in all situations. After
298  * the incomplete packet occurs, "surplus" data may be transferred. For recent
299  * versions of libusb, this information is kept (the data length of the
300  * transfer is updated) and, for device-to-host transfers, any surplus data was
301  * added to the buffer. Still, this is not a nice solution because it loses the
302  * information about the end of the short packet, and the user probably wanted
303  * that surplus data to arrive in the next logical transfer.
304  *
305  *
306  * \section zlp Zero length packets
307  *
308  * - libusb is able to send a packet of zero length to an endpoint simply by
309  * submitting a transfer of zero length.
310  * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
311  * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
312  */
313
314 /**
315  * \page contexts Contexts
316  *
317  * It is possible that libusb may be used simultaneously from two independent
318  * libraries linked into the same executable. For example, if your application
319  * has a plugin-like system which allows the user to dynamically load a range
320  * of modules into your program, it is feasible that two independently
321  * developed modules may both use libusb.
322  *
323  * libusb is written to allow for these multiple user scenarios. The two
324  * "instances" of libusb will not interfere: libusb_set_debug() calls
325  * from one user will not affect the same settings for other users, other
326  * users can continue using libusb after one of them calls libusb_exit(), etc.
327  *
328  * This is made possible through libusb's <em>context</em> concept. When you
329  * call libusb_init(), you are (optionally) given a context. You can then pass
330  * this context pointer back into future libusb functions.
331  *
332  * In order to keep things simple for more simplistic applications, it is
333  * legal to pass NULL to all functions requiring a context pointer (as long as
334  * you're sure no other code will attempt to use libusb from the same process).
335  * When you pass NULL, the default context will be used. The default context
336  * is created the first time a process calls libusb_init() when no other
337  * context is alive. Contexts are destroyed during libusb_exit().
338  *
339  * The default context is reference-counted and can be shared. That means that
340  * if libusb_init(NULL) is called twice within the same process, the two
341  * users end up sharing the same context. The deinitialization and freeing of
342  * the default context will only happen when the last user calls libusb_exit().
343  * In other words, the default context is created and initialized when its
344  * reference count goes from 0 to 1, and is deinitialized and destroyed when
345  * its reference count goes from 1 to 0.
346  *
347  * You may be wondering why only a subset of libusb functions require a
348  * context pointer in their function definition. Internally, libusb stores
349  * context pointers in other objects (e.g. libusb_device instances) and hence
350  * can infer the context from those objects.
351  */
352
353 /**
354  * @defgroup lib Library initialization/deinitialization
355  * This page details how to initialize and deinitialize libusb. Initialization
356  * must be performed before using any libusb functionality, and similarly you
357  * must not call any libusb functions after deinitialization.
358  */
359
360 /**
361  * @defgroup dev Device handling and enumeration
362  * The functionality documented below is designed to help with the following
363  * operations:
364  * - Enumerating the USB devices currently attached to the system
365  * - Choosing a device to operate from your software
366  * - Opening and closing the chosen device
367  *
368  * \section nutshell In a nutshell...
369  *
370  * The description below really makes things sound more complicated than they
371  * actually are. The following sequence of function calls will be suitable
372  * for almost all scenarios and does not require you to have such a deep
373  * understanding of the resource management issues:
374  * \code
375  // discover devices
376  libusb_device **list;
377  libusb_device *found = NULL;
378  ssize_t cnt = libusb_get_device_list(NULL, &list);
379  ssize_t i = 0;
380  int err = 0;
381  if (cnt < 0)
382  error();
383
384  for (i = 0; i < cnt; i++) {
385  libusb_device *device = list[i];
386  if (is_interesting(device)) {
387  found = device;
388  break;
389  }
390  }
391
392  if (found) {
393  libusb_device_handle *handle;
394
395  err = libusb_open(found, &handle);
396  if (err)
397  error();
398  // etc
399  }
400
401  libusb_free_device_list(list, 1);
402  \endcode
403  *
404  * The two important points:
405  * - You asked libusb_free_device_list() to unreference the devices (2nd
406  *   parameter)
407  * - You opened the device before freeing the list and unreferencing the
408  *   devices
409  *
410  * If you ended up with a handle, you can now proceed to perform I/O on the
411  * device.
412  *
413  * \section devshandles Devices and device handles
414  * libusb has a concept of a USB device, represented by the
415  * \ref libusb_device opaque type. A device represents a USB device that
416  * is currently or was previously connected to the system. Using a reference
417  * to a device, you can determine certain information about the device (e.g.
418  * you can read the descriptor data).
419  *
420  * The libusb_get_device_list() function can be used to obtain a list of
421  * devices currently connected to the system. This is known as device
422  * discovery.
423  *
424  * Just because you have a reference to a device does not mean it is
425  * necessarily usable. The device may have been unplugged, you may not have
426  * permission to operate such device, or another program or driver may be
427  * using the device.
428  *
429  * When you've found a device that you'd like to operate, you must ask
430  * libusb to open the device using the libusb_open() function. Assuming
431  * success, libusb then returns you a <em>device handle</em>
432  * (a \ref libusb_device_handle pointer). All "real" I/O operations then
433  * operate on the handle rather than the original device pointer.
434  *
435  * \section devref Device discovery and reference counting
436  *
437  * Device discovery (i.e. calling libusb_get_device_list()) returns a
438  * freshly-allocated list of devices. The list itself must be freed when
439  * you are done with it. libusb also needs to know when it is OK to free
440  * the contents of the list - the devices themselves.
441  *
442  * To handle these issues, libusb provides you with two separate items:
443  * - A function to free the list itself
444  * - A reference counting system for the devices inside
445  *
446  * New devices presented by the libusb_get_device_list() function all have a
447  * reference count of 1. You can increase and decrease reference count using
448  * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
449  * its reference count reaches 0.
450  *
451  * With the above information in mind, the process of opening a device can
452  * be viewed as follows:
453  * -# Discover devices using libusb_get_device_list().
454  * -# Choose the device that you want to operate, and call libusb_open().
455  * -# Unref all devices in the discovered device list.
456  * -# Free the discovered device list.
457  *
458  * The order is important - you must not unreference the device before
459  * attempting to open it, because unreferencing it may destroy the device.
460  *
461  * For convenience, the libusb_free_device_list() function includes a
462  * parameter to optionally unreference all the devices in the list before
463  * freeing the list itself. This combines steps 3 and 4 above.
464  *
465  * As an implementation detail, libusb_open() actually adds a reference to
466  * the device in question. This is because the device remains available
467  * through the handle via libusb_get_device(). The reference is deleted during
468  * libusb_close().
469  */
470
471 /** @defgroup misc Miscellaneous */
472
473 /* we traverse usbfs without knowing how many devices we are going to find.
474  * so we create this discovered_devs model which is similar to a linked-list
475  * which grows when required. it can be freed once discovery has completed,
476  * eliminating the need for a list node in the libusb_device structure
477  * itself. */
478 #define DISCOVERED_DEVICES_SIZE_STEP 8
479
480 static struct discovered_devs *discovered_devs_alloc(void) {
481
482         struct discovered_devs *ret =
483                 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
484
485         if (ret) {
486                 ret->len = 0;
487                 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
488         }
489         return ret;
490 }
491
492 /* append a device to the discovered devices collection. may realloc itself,
493  * returning new discdevs. returns NULL on realloc failure. */
494 struct discovered_devs *discovered_devs_append(
495         struct discovered_devs *discdevs, struct libusb_device *dev) {
496         
497         size_t len = discdevs->len;
498         size_t capacity;
499
500         /* if there is space, just append the device */
501         if (LIKELY(len < discdevs->capacity)) {
502                 discdevs->devices[len] = libusb_ref_device(dev);
503                 discdevs->len++;
504                 return discdevs;
505         }
506
507         /* exceeded capacity, need to grow */
508         usbi_dbg("need to increase capacity");
509         capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
510         discdevs = usbi_reallocf(discdevs,
511                         sizeof(*discdevs) + (sizeof(void *) * capacity));
512         if (LIKELY(discdevs)) {
513                 discdevs->capacity = capacity;
514                 discdevs->devices[len] = libusb_ref_device(dev);
515                 discdevs->len++;
516         }
517
518         return discdevs;
519 }
520
521 static void discovered_devs_free(struct discovered_devs *discdevs) {
522
523         size_t i;
524
525         for (i = 0; i < discdevs->len; i++)
526                 libusb_unref_device(discdevs->devices[i]);
527
528         free(discdevs);
529 }
530
531 /* Allocate a new device with a specific session ID. The returned device has
532  * a reference count of 1. */
533 struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
534         unsigned long session_id) {
535         
536         size_t priv_size = usbi_backend->device_priv_size;
537         struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
538         int r;
539
540         if (UNLIKELY(!dev))
541                 return NULL ;
542
543         r = usbi_mutex_init(&dev->lock, NULL);
544         if (UNLIKELY(r)) {
545                 free(dev);
546                 return NULL;
547         }
548
549         dev->ctx = ctx;
550         dev->refcnt = 1;
551         dev->session_data = session_id;
552         dev->speed = LIBUSB_SPEED_UNKNOWN;
553
554         if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
555                 usbi_connect_device(dev);
556         }
557
558         return dev;
559 }
560
561 void usbi_connect_device(struct libusb_device *dev) {
562
563         libusb_hotplug_message message;
564         ssize_t ret;
565
566         memset(&message, 0, sizeof(message));
567         message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED;
568         message.device = dev;
569         dev->attached = 1;
570
571         usbi_mutex_lock(&dev->ctx->usb_devs_lock);
572         {
573                 list_add(&dev->list, &dev->ctx->usb_devs);
574         }
575         usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
576
577         /* Signal that an event has occurred for this device if we support hotplug AND
578          * the hotplug pipe is ready. This prevents an event from getting raised during
579          * initial enumeration. */
580         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)
581                         && dev->ctx->hotplug_pipe[1] > 0) {
582                 ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
583                 if (UNLIKELY(sizeof(message) != ret)) {
584                         usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
585                 }
586         }
587 }
588
589 void usbi_disconnect_device(struct libusb_device *dev) {
590
591         libusb_hotplug_message message;
592         struct libusb_context *ctx = dev->ctx;
593         ssize_t ret;
594
595         memset(&message, 0, sizeof(message));
596         message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT;
597         message.device = dev;
598         usbi_mutex_lock(&dev->lock);
599         {
600                 dev->attached = 0;
601         }
602         usbi_mutex_unlock(&dev->lock);
603
604         usbi_mutex_lock(&ctx->usb_devs_lock);
605         {
606                 list_del(&dev->list);
607         }
608         usbi_mutex_unlock(&ctx->usb_devs_lock);
609
610         /* Signal that an event has occurred for this device if we support hotplug AND
611          * the hotplug pipe is ready. This prevents an event from getting raised during
612          * initial enumeration. libusb_handle_events will take care of dereferencing the
613          * device. */
614         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)
615                         && dev->ctx->hotplug_pipe[1] > 0) {
616                 ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
617                 if (UNLIKELY(sizeof(message) != ret)) {
618                         usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
619                 }
620         }
621 }
622
623 /* Perform some final sanity checks on a newly discovered device. If this
624  * function fails (negative return code), the device should not be added
625  * to the discovered device list. */
626 int usbi_sanitize_device(struct libusb_device *dev) {
627
628         int r;
629         uint8_t num_configurations;
630
631         r = usbi_device_cache_descriptor(dev);
632         if (UNLIKELY(r < 0))
633                 return r;
634
635         num_configurations = dev->device_descriptor.bNumConfigurations;
636         if UNLIKELY(num_configurations > USB_MAXCONFIG) {
637                 usbi_err(DEVICE_CTX(dev), "too many configurations");
638                 return LIBUSB_ERROR_IO;
639         } else if (0 == num_configurations)
640                 usbi_dbg("zero configurations, maybe an unauthorized device");
641
642         dev->num_configurations = num_configurations;
643         return LIBUSB_SUCCESS;
644 }
645
646 /* Examine libusb's internal list of known devices, looking for one with
647  * a specific session ID. Returns the matching device if it was found, and
648  * NULL otherwise. */
649 struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
650                 unsigned long session_id) {
651                 
652         struct libusb_device *dev;
653         struct libusb_device *ret = NULL;
654
655         usbi_mutex_lock(&ctx->usb_devs_lock);
656         {
657                 list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
658                         if (dev->session_data == session_id) {
659                                 ret = libusb_ref_device(dev);
660                                 break;
661                         }
662         }
663         usbi_mutex_unlock(&ctx->usb_devs_lock);
664
665         return ret;
666 }
667
668 /** @ingroup dev
669  * Returns a list of USB devices currently attached to the system. This is
670  * your entry point into finding a USB device to operate.
671  *
672  * You are expected to unreference all the devices when you are done with
673  * them, and then free the list with libusb_free_device_list(). Note that
674  * libusb_free_device_list() can unref all the devices for you. Be careful
675  * not to unreference a device you are about to open until after you have
676  * opened it.
677  *
678  * This return value of this function indicates the number of devices in
679  * the resultant list. The list is actually one element larger, as it is
680  * NULL-terminated.
681  *
682  * \param ctx the context to operate on, or NULL for the default context
683  * \param list output location for a list of devices. Must be later freed with
684  * libusb_free_device_list().
685  * \returns the number of devices in the outputted list, or any
686  * \ref libusb_error according to errors encountered by the backend.
687  */
688 ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
689                 libusb_device ***list) {
690
691         ENTER();
692
693         struct discovered_devs *discdevs = discovered_devs_alloc();
694         struct libusb_device **ret;
695         int r = 0;
696         ssize_t i, len;
697         USBI_GET_CONTEXT(ctx);
698         usbi_dbg("");
699
700         if (UNLIKELY(!discdevs))
701                 return LIBUSB_ERROR_NO_MEM;
702
703         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
704                 LOGD("backend provides hotplug support");
705                 struct libusb_device *dev;
706
707                 if (usbi_backend->hotplug_poll)
708                         usbi_backend->hotplug_poll();
709
710                 usbi_mutex_lock(&ctx->usb_devs_lock);
711                 {
712                         list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
713                         {
714                                 discdevs = discovered_devs_append(discdevs, dev);
715
716                                 if (UNLIKELY(!discdevs)) {
717                                         r = LIBUSB_ERROR_NO_MEM;
718                                         break;
719                                 }
720                         }
721                 }
722                 usbi_mutex_unlock(&ctx->usb_devs_lock);
723         } else {
724                 LOGD("backend does not provide hotplug support");
725                 r = usbi_backend->get_device_list(ctx, &discdevs);
726         }
727
728         if (UNLIKELY(r < 0)) {
729                 len = r;
730                 goto out;
731         }
732
733         /* convert discovered_devs into a list */
734         len = discdevs->len;
735         ret = calloc(len + 1, sizeof(struct libusb_device *));
736         if (UNLIKELY(!ret)) {
737                 LOGE("LIBUSB_ERROR_NO_MEM");
738                 len = LIBUSB_ERROR_NO_MEM;
739                 goto out;
740         }
741
742         ret[len] = NULL;
743         for (i = 0; i < len; i++) {
744                 struct libusb_device *dev = discdevs->devices[i];
745                 ret[i] = libusb_ref_device(dev);
746         }
747         *list = ret;
748
749 out:
750         discovered_devs_free(discdevs);
751         RETURN(len, int);
752 }
753
754 /**
755  * search device with specific vender ID and product ID
756  * TODO it is better to check serial number for multiple device connection with same vender ID and product ID
757  * @return null if not found
758  * @param vid: vender ID, 0 means don't care
759  * @param pid: product ID, 0 means don't care
760  * @param sn: serial number(currently not use)
761  * @param fd: file descripter that need to access device on no-rooted Android
762  * @return null if not found
763  */
764 libusb_device *libusb_find_device(libusb_context *ctx, const int vid,
765                 const int pid, const char* sn, int fd) {
766
767         ENTER();
768
769         libusb_device **devs;
770         // get list of devices
771         int cnt = libusb_get_device_list(ctx, &devs);
772         if (UNLIKELY(cnt < 0)) {
773                 LOGI("failed to get device list");
774                 usbi_dbg("failed to get device list");
775                 return NULL ;
776         }
777
778         int r, i;
779         libusb_device *device = NULL;
780         struct libusb_device_descriptor desc;
781         LOGI("try to find specific device:cnt=%d", cnt);
782         for (i = 0; i < cnt; i++) {
783                 r = libusb_get_device_descriptor(devs[i], &desc);
784                 if (UNLIKELY(r < 0)) {
785                         LOGI("failed to get device descriptor");
786                         usbi_dbg("failed to get device descriptor");
787                         continue;
788                 }
789                 if ((!vid || (desc.idVendor == vid))
790                                 && (!pid || (desc.idProduct == pid))) {
791                         LOGI("found");
792                         device = devs[i];
793                         libusb_ref_device(device);
794                         break;
795                 }
796         }
797
798         libusb_free_device_list(devs, 1);
799         RET(device);
800 }
801
802 /** \ingroup dev
803  * Frees a list of devices previously discovered using
804  * libusb_get_device_list(). If the unref_devices parameter is set, the
805  * reference count of each device in the list is decremented by 1.
806  * \param list the list to free
807  * \param unref_devices whether to unref the devices in the list
808  */
809 void API_EXPORTED libusb_free_device_list(libusb_device **list,
810                 int unref_devices) {
811                 
812         if (UNLIKELY(!list))
813                 return;
814
815         if (unref_devices) {
816                 int i = 0;
817                 struct libusb_device *dev;
818
819                 while ((dev = list[i++]) != NULL)
820                         libusb_unref_device(dev);
821         }
822         free(list);
823 }
824
825 /** \ingroup dev
826  * Get the number of the bus that a device is connected to.
827  * \param dev a device
828  * \returns the bus number
829  */
830 uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev) {
831
832         return dev->bus_number;
833 }
834
835 /** \ingroup dev
836  * Get the number of the port that a device is connected to.
837  * Unless the OS does something funky, or you are hot-plugging USB extension cards,
838  * the port number returned by this call is usually guaranteed to be uniquely tied
839  * to a physical port, meaning that different devices plugged on the same physical
840  * port should return the same port number.
841  *
842  * But outside of this, there is no guarantee that the port number returned by this
843  * call will remain the same, or even match the order in which ports have been
844  * numbered by the HUB/HCD manufacturer.
845  *
846  * \param dev a device
847  * \returns the port number (0 if not available)
848  */
849 uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev) {
850
851         return dev->port_number;
852 }
853
854 /** \ingroup dev
855  * Get the list of all port numbers from root for the specified device
856  *
857  * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102
858  * \param dev a device
859  * \param port_numbers the array that should contain the port numbers
860  * \param port_numbers_len the maximum length of the array. As per the USB 3.0
861  * specs, the current maximum limit for the depth is 7.
862  * \returns the number of elements filled
863  * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
864  */
865 int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
866                 uint8_t* port_numbers, int port_numbers_len) {
867
868         int i = port_numbers_len;
869         struct libusb_context *ctx = DEVICE_CTX(dev);
870
871         if UNLIKELY(port_numbers_len <= 0)
872                 return LIBUSB_ERROR_INVALID_PARAM;
873
874         // HCDs can be listed as devices with port #0
875         while ((dev) && (dev->port_number != 0)) {
876                 if (--i < 0) {
877                         usbi_warn(ctx, "port numbers array is too small");
878                         return LIBUSB_ERROR_OVERFLOW;
879                 }
880                 port_numbers[i] = dev->port_number;
881                 dev = dev->parent_dev;
882         }
883         if (i < port_numbers_len)
884                 memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
885         return port_numbers_len - i;
886 }
887
888 /** \ingroup dev
889  * Deprecated please use libusb_get_port_numbers instead.
890  */
891 int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
892                 uint8_t* port_numbers, uint8_t port_numbers_len) {
893                 
894         UNUSED(ctx);
895
896         return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
897 }
898
899 /** \ingroup dev
900  * Get the the parent from the specified device.
901  * \param dev a device
902  * \returns the device parent or NULL if not available
903  * You should issue a \ref libusb_get_device_list() before calling this
904  * function and make sure that you only access the parent before issuing
905  * \ref libusb_free_device_list(). The reason is that libusb currently does
906  * not maintain a permanent list of device instances, and therefore can
907  * only guarantee that parents are fully instantiated within a 
908  * libusb_get_device_list() - libusb_free_device_list() block.
909  */
910 DEFAULT_VISIBILITY
911 libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev) {
912
913         return dev->parent_dev;
914 }
915
916 /** \ingroup dev
917  * Get the address of the device on the bus it is connected to.
918  * \param dev a device
919  * \returns the device address
920  */
921 uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev) {
922
923         return dev->device_address;
924 }
925
926 /** \ingroup dev
927  * Get the negotiated connection speed for a device.
928  * \param dev a device
929  * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
930  * the OS doesn't know or doesn't support returning the negotiated speed.
931  */
932 int API_EXPORTED libusb_get_device_speed(libusb_device *dev) {
933
934         return dev->speed;
935 }
936
937 static const struct libusb_endpoint_descriptor *find_endpoint(
938         struct libusb_config_descriptor *config, unsigned char endpoint) {
939         
940         int iface_idx;
941         for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
942                 const struct libusb_interface *iface = &config->interface[iface_idx];
943                 int altsetting_idx;
944
945                 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
946                                 altsetting_idx++) {
947                         const struct libusb_interface_descriptor *altsetting
948                                 = &iface->altsetting[altsetting_idx];
949                         int ep_idx;
950
951                         for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
952                                 const struct libusb_endpoint_descriptor *ep =
953                                                 &altsetting->endpoint[ep_idx];
954                                 if (ep->bEndpointAddress == endpoint)
955                                         return ep;
956                         }
957                 }
958         }
959         return NULL;
960 }
961
962 /** \ingroup dev
963  * Convenience function to retrieve the wMaxPacketSize value for a particular
964  * endpoint in the active device configuration.
965  *
966  * This function was originally intended to be of assistance when setting up
967  * isochronous transfers, but a design mistake resulted in this function
968  * instead. It simply returns the wMaxPacketSize value without considering
969  * its contents. If you're dealing with isochronous transfers, you probably
970  * want libusb_get_max_iso_packet_size() instead.
971  *
972  * \param dev a device
973  * \param endpoint address of the endpoint in question
974  * \returns the wMaxPacketSize value
975  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
976  * \returns LIBUSB_ERROR_OTHER on other failure
977  */
978 int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
979                 unsigned char endpoint) {
980
981         struct libusb_config_descriptor *config;
982         const struct libusb_endpoint_descriptor *ep;
983         int r;
984
985         r = libusb_get_active_config_descriptor(dev, &config);
986         if (UNLIKELY(r < 0)) {
987                 usbi_err(DEVICE_CTX(dev),
988                                 "could not retrieve active config descriptor");
989                 return LIBUSB_ERROR_OTHER;
990         }
991
992         ep = find_endpoint(config, endpoint);
993         if (UNLIKELY(!ep)) {
994                 r = LIBUSB_ERROR_NOT_FOUND;
995                 goto out;
996         }
997
998         r = ep->wMaxPacketSize;
999
1000 out:
1001         libusb_free_config_descriptor(config);
1002         return r;
1003 }
1004
1005 /** \ingroup dev
1006  * Calculate the maximum packet size which a specific endpoint is capable is
1007  * sending or receiving in the duration of 1 microframe
1008  *
1009  * Only the active configuration is examined. The calculation is based on the
1010  * wMaxPacketSize field in the endpoint descriptor as described in section
1011  * 9.6.6 in the USB 2.0 specifications.
1012  *
1013  * If acting on an isochronous or interrupt endpoint, this function will
1014  * multiply the value found in bits 0:10 by the number of transactions per
1015  * microframe (determined by bits 11:12). Otherwise, this function just
1016  * returns the numeric value found in bits 0:10.
1017  *
1018  * This function is useful for setting up isochronous transfers, for example
1019  * you might pass the return value from this function to
1020  * libusb_set_iso_packet_lengths() in order to set the length field of every
1021  * isochronous packet in a transfer.
1022  *
1023  * Since v1.0.3.
1024  *
1025  * \param dev a device
1026  * \param endpoint address of the endpoint in question
1027  * \returns the maximum packet size which can be sent/received on this endpoint
1028  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1029  * \returns LIBUSB_ERROR_OTHER on other failure
1030  */
1031 int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
1032                 unsigned char endpoint) {
1033
1034         struct libusb_config_descriptor *config;
1035         const struct libusb_endpoint_descriptor *ep;
1036         enum libusb_transfer_type ep_type;
1037         uint16_t val;
1038         int r;
1039
1040         r = libusb_get_active_config_descriptor(dev, &config);
1041         if (UNLIKELY(r < 0)) {
1042                 usbi_err(DEVICE_CTX(dev),
1043                                 "could not retrieve active config descriptor");
1044                 return LIBUSB_ERROR_OTHER;
1045         }
1046
1047         ep = find_endpoint(config, endpoint);
1048         if (UNLIKELY(!ep)) {
1049                 r = LIBUSB_ERROR_NOT_FOUND;
1050                 goto out;
1051         }
1052
1053         val = ep->wMaxPacketSize;
1054         ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
1055
1056         r = val & 0x07ff;
1057         if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
1058                         || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
1059                 r *= (1 + ((val >> 11) & 3));
1060
1061 out:
1062         libusb_free_config_descriptor(config);
1063         return r;
1064 }
1065
1066 /** \ingroup dev
1067  * Increment the reference count of a device.
1068  * \param dev the device to reference
1069  * \returns the same device
1070  */
1071 DEFAULT_VISIBILITY
1072 libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev) {
1073
1074         int refcnt;
1075         usbi_mutex_lock(&dev->lock);
1076         {
1077                 refcnt = ++dev->refcnt;
1078         }
1079         usbi_mutex_unlock(&dev->lock);
1080 //      LOGI("refcnt=%d", refcnt);
1081         return dev;
1082 }
1083
1084 /** \ingroup dev
1085  * Decrement the reference count of a device. If the decrement operation
1086  * causes the reference count to reach zero, the device shall be destroyed.
1087  * \param dev the device to unreference
1088  */
1089 void API_EXPORTED libusb_unref_device(libusb_device *dev) {
1090
1091         int refcnt;
1092
1093         if (UNLIKELY(!dev))
1094                 return;
1095
1096         usbi_mutex_lock(&dev->lock);
1097         {
1098                 refcnt = --dev->refcnt;
1099         }
1100         usbi_mutex_unlock(&dev->lock);
1101 //      LOGI("refcnt=%d", dev->refcnt);
1102
1103         if (refcnt == 0) {
1104                 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
1105
1106                 libusb_unref_device(dev->parent_dev);
1107
1108                 if (usbi_backend->destroy_device)
1109                         usbi_backend->destroy_device(dev);
1110
1111                 if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
1112                         /* backend does not support hotplug */
1113                         usbi_disconnect_device(dev);
1114                 }
1115
1116                 usbi_mutex_destroy(&dev->lock);
1117                 free(dev);
1118         }
1119 }
1120
1121 /*
1122  * Interrupt the iteration of the event handling thread, so that it picks
1123  * up the new fd.
1124  */
1125 void usbi_fd_notification(struct libusb_context *ctx) {
1126
1127         unsigned char dummy = 1;
1128         ssize_t r;
1129
1130         if (UNLIKELY(ctx == NULL))
1131                 return;
1132
1133         /* record that we are messing with poll fds */
1134         usbi_mutex_lock(&ctx->pollfd_modify_lock);
1135         {
1136                 ctx->pollfd_modify++;
1137         }
1138         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1139
1140         /* write some data on control pipe to interrupt event handlers */
1141         r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1142         if (UNLIKELY(r <= 0)) {
1143                 usbi_warn(ctx, "internal signalling write failed");
1144                 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1145                 {
1146                         ctx->pollfd_modify--;
1147                 }
1148                 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1149                 return;
1150         }
1151
1152         /* take event handling lock */
1153         libusb_lock_events(ctx);
1154         {
1155                 /* read the dummy data */
1156                 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
1157                 if (UNLIKELY(r <= 0))
1158                         usbi_warn(ctx, "internal signalling read failed");
1159
1160                 /* we're done with modifying poll fds */
1161                 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1162                 {
1163                         ctx->pollfd_modify--;
1164                 }
1165                 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1166         }
1167         /* Release event handling lock and wake up event waiters */
1168         libusb_unlock_events(ctx);
1169 }
1170
1171 /** \ingroup dev
1172  * Open a device and obtain a device handle. A handle allows you to perform
1173  * I/O on the device in question.
1174  *
1175  * Internally, this function adds a reference to the device and makes it
1176  * available to you through libusb_get_device(). This reference is removed
1177  * during libusb_close().
1178  *
1179  * This is a non-blocking function; no requests are sent over the bus.
1180  *
1181  * \param dev the device to open
1182  * \param handle output location for the returned device handle pointer. Only
1183  * populated when the return code is 0.
1184  * \returns 0 on success
1185  * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
1186  * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
1187  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1188  * \returns another LIBUSB_ERROR code on other failure
1189  */
1190 int API_EXPORTED libusb_open(libusb_device *dev, libusb_device_handle **handle) {
1191
1192         struct libusb_context *ctx = DEVICE_CTX(dev);
1193         struct libusb_device_handle *_handle;
1194         size_t priv_size = usbi_backend->device_handle_priv_size;
1195         int r;
1196         usbi_dbg("open (bus/addr)=(%d.%d)", dev->bus_number, dev->device_address);
1197
1198         if (UNLIKELY(!dev->attached)) {
1199                 return LIBUSB_ERROR_NO_DEVICE;
1200         }
1201
1202         _handle = malloc(sizeof(*_handle) + priv_size);
1203         if (UNLIKELY(!_handle))
1204                 return LIBUSB_ERROR_NO_MEM;
1205
1206         r = usbi_mutex_init(&_handle->lock, NULL);
1207         if (UNLIKELY(r)) {
1208                 free(_handle);
1209                 return LIBUSB_ERROR_OTHER;
1210         }
1211
1212         _handle->dev = libusb_ref_device(dev);
1213         _handle->auto_detach_kernel_driver = 0;
1214         _handle->claimed_interfaces = 0;
1215         memset(&_handle->os_priv, 0, priv_size);
1216
1217         r = usbi_backend->open(_handle);
1218         if (UNLIKELY(r < 0)) {
1219                 usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
1220                 libusb_unref_device(dev);
1221                 usbi_mutex_destroy(&_handle->lock);
1222                 free(_handle);
1223                 return r;
1224         }
1225
1226         usbi_mutex_lock(&ctx->open_devs_lock);
1227         {
1228                 list_add(&_handle->list, &ctx->open_devs);
1229         }
1230         usbi_mutex_unlock(&ctx->open_devs_lock);
1231         *handle = _handle;
1232
1233         /* At this point, we want to interrupt any existing event handlers so
1234          * that they realise the addition of the new device's poll fd. One
1235          * example when this is desirable is if the user is running a separate
1236          * dedicated libusb events handling thread, which is running with a long
1237          * or infinite timeout. We want to interrupt that iteration of the loop,
1238          * so that it picks up the new fd, and then continues. */
1239         usbi_fd_notification(ctx);
1240
1241         return LIBUSB_SUCCESS;
1242 }
1243
1244 int API_EXPORTED libusb_set_device_fd(libusb_device *dev, int fd) {
1245
1246         return usbi_backend->set_device_fd(dev, fd);
1247 }
1248
1249 libusb_device * LIBUSB_CALL libusb_get_device_with_fd(libusb_context *ctx,
1250         int vid, int pid, const char *serial, int fd, int busnum, int devaddr) {
1251
1252         ENTER();
1253
1254         struct libusb_device *device = NULL;
1255         // android_generate_device内でusbi_alloc_deviceが呼ばれた時に参照カウンタは1
1256         int ret = android_generate_device(ctx, &device, vid, pid, serial, fd, busnum, devaddr);
1257         if (ret) {
1258                 LOGD("android_generate_device failed:err=%d", ret);
1259                 device = NULL;
1260         }
1261
1262         RET(device);
1263 }
1264
1265 /** \ingroup dev
1266  * Convenience function for finding a device with a particular
1267  * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
1268  * for those scenarios where you are using libusb to knock up a quick test
1269  * application - it allows you to avoid calling libusb_get_device_list() and
1270  * worrying about traversing/freeing the list.
1271  *
1272  * This function has limitations and is hence not intended for use in real
1273  * applications: if multiple devices have the same IDs it will only
1274  * give you the first one, etc.
1275  *
1276  * \param ctx the context to operate on, or NULL for the default context
1277  * \param vendor_id the idVendor value to search for
1278  * \param product_id the idProduct value to search for
1279  * \returns a handle for the first found device, or NULL on error or if the
1280  * device could not be found. */
1281 DEFAULT_VISIBILITY
1282 libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
1283                 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id) {
1284
1285         struct libusb_device **devs;
1286         struct libusb_device *found = NULL;
1287         struct libusb_device *dev;
1288         struct libusb_device_handle *handle = NULL;
1289         size_t i = 0;
1290         int r;
1291
1292         if (libusb_get_device_list(ctx, &devs) < 0)
1293                 return NULL;
1294
1295         while ((dev = devs[i++]) != NULL) {
1296                 struct libusb_device_descriptor desc;
1297                 r = libusb_get_device_descriptor(dev, &desc);
1298                 if (UNLIKELY(r < 0))
1299                         goto out;
1300                 if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
1301                         found = dev;
1302                         break;
1303                 }
1304         }
1305
1306         if (found) {
1307                 r = libusb_open(found, &handle);
1308                 if (UNLIKELY(r < 0))
1309                         handle = NULL;
1310         }
1311
1312 out:
1313         libusb_free_device_list(devs, 1);
1314         return handle;
1315 }
1316
1317 static void do_close(struct libusb_context *ctx,
1318         struct libusb_device_handle *dev_handle) {
1319
1320         struct usbi_transfer *itransfer;
1321         struct usbi_transfer *tmp;
1322
1323         libusb_lock_events(ctx);
1324         {
1325                 /* remove any transfers in flight that are for this device */
1326                 usbi_mutex_lock(&ctx->flying_transfers_lock);
1327                 {
1328                         /* safe iteration because transfers may be being deleted */
1329                         list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer)
1330                         {
1331                                 struct libusb_transfer *transfer =
1332                                         USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1333
1334                                 if (transfer->dev_handle != dev_handle)
1335                                         continue;
1336
1337                                 if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
1338                                         usbi_err(ctx,
1339                                                 "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
1340
1341                                         if (itransfer->flags & USBI_TRANSFER_CANCELLING)
1342                                                 usbi_warn(ctx,
1343                                                         "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
1344                                         else
1345                                                 usbi_err(ctx,
1346                                                         "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
1347                                 }
1348
1349                                 /* remove from the list of in-flight transfers and make sure
1350                                  * we don't accidentally use the device handle in the future
1351                                  * (or that such accesses will be easily caught and identified as a crash)
1352                                  */
1353                                 usbi_mutex_lock(&itransfer->lock);
1354                                 {
1355                                         list_del(&itransfer->list);
1356                                         transfer->dev_handle = NULL;
1357                                 }
1358                                 usbi_mutex_unlock(&itransfer->lock);
1359
1360                                 /* it is up to the user to free up the actual transfer struct.  this is
1361                                  * just making sure that we don't attempt to process the transfer after
1362                                  * the device handle is invalid
1363                                  */
1364                                 usbi_dbg(
1365                                                 "Removed transfer %p from the in-flight list because device handle %p closed",
1366                                                 transfer, dev_handle);
1367                         }
1368                 }
1369                 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1370         }
1371         libusb_unlock_events(ctx);
1372
1373         usbi_mutex_lock(&ctx->open_devs_lock);
1374         {
1375                 list_del(&dev_handle->list);
1376         }
1377         usbi_mutex_unlock(&ctx->open_devs_lock);
1378
1379         usbi_backend->close(dev_handle);
1380         libusb_unref_device(dev_handle->dev);
1381         usbi_mutex_destroy(&dev_handle->lock);
1382         free(dev_handle);
1383 }
1384
1385 /** \ingroup dev
1386  * Close a device handle. Should be called on all open handles before your
1387  * application exits.
1388  *
1389  * Internally, this function destroys the reference that was added by
1390  * libusb_open() on the given device.
1391  *
1392  * This is a non-blocking function; no requests are sent over the bus.
1393  *
1394  * \param dev_handle the handle to close
1395  */
1396 void API_EXPORTED libusb_close(libusb_device_handle *dev_handle) {
1397
1398         struct libusb_context *ctx;
1399         unsigned char dummy = 1;
1400         ssize_t r;
1401
1402         if (UNLIKELY(!dev_handle))
1403                 return;
1404         usbi_dbg("");
1405
1406         ctx = HANDLE_CTX(dev_handle);
1407
1408         /* Similarly to libusb_open(), we want to interrupt all event handlers
1409          * at this point. More importantly, we want to perform the actual close of
1410          * the device while holding the event handling lock (preventing any other
1411          * thread from doing event handling) because we will be removing a file
1412          * descriptor from the polling loop. */
1413
1414         /* record that we are messing with poll fds */
1415         usbi_mutex_lock(&ctx->pollfd_modify_lock);
1416         {
1417                 ctx->pollfd_modify++;
1418         }
1419         usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1420
1421         /* write some data on control pipe to interrupt event handlers */
1422         r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
1423         if (UNLIKELY(r <= 0)) {
1424                 usbi_warn(ctx, "internal signalling write failed, closing anyway");
1425                 do_close(ctx, dev_handle);
1426                 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1427                 {
1428                         ctx->pollfd_modify--;
1429                 }
1430                 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1431                 return;
1432         }
1433
1434         /* take event handling lock */
1435         libusb_lock_events(ctx);        // XXX crash
1436         {
1437                 /* read the dummy data */
1438                 r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));        // XXX crash
1439                 if (UNLIKELY(r <= 0)) {
1440                         usbi_warn(ctx, "internal signalling read failed, closing anyway");
1441                 }
1442
1443                 /* Close the device */
1444                 do_close(ctx, dev_handle);      // XXX this function internally call libusb_lock_events/libusb_unlock_events
1445                                                                         // while libusb_lock_events is already called and will hang-up on some OS?
1446
1447                 /* we're done with modifying poll fds */
1448                 usbi_mutex_lock(&ctx->pollfd_modify_lock);
1449                 {
1450                         ctx->pollfd_modify--;
1451                 }
1452                 usbi_mutex_unlock(&ctx->pollfd_modify_lock);
1453         }
1454         /* Release event handling lock and wake up event waiters */
1455         libusb_unlock_events(ctx);
1456 }
1457
1458 /** \ingroup dev
1459  * Get the underlying device for a handle. This function does not modify
1460  * the reference count of the returned device, so do not feel compelled to
1461  * unreference it when you are done.
1462  * \param dev_handle a device handle
1463  * \returns the underlying device
1464  */
1465 DEFAULT_VISIBILITY
1466 libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle) {
1467
1468         return dev_handle->dev;
1469 }
1470
1471 /** \ingroup dev
1472  * Determine the bConfigurationValue of the currently active configuration.
1473  *
1474  * You could formulate your own control request to obtain this information,
1475  * but this function has the advantage that it may be able to retrieve the
1476  * information from operating system caches (no I/O involved).
1477  *
1478  * If the OS does not cache this information, then this function will block
1479  * while a control transfer is submitted to retrieve the information.
1480  *
1481  * This function will return a value of 0 in the <tt>config</tt> output
1482  * parameter if the device is in unconfigured state.
1483  *
1484  * \param dev a device handle
1485  * \param config output location for the bConfigurationValue of the active
1486  * configuration (only valid for return code 0)
1487  * \returns 0 on success
1488  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1489  * \returns another LIBUSB_ERROR code on other failure
1490  */
1491 int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
1492                 int *config) {
1493         int r = LIBUSB_ERROR_NOT_SUPPORTED;
1494
1495         usbi_dbg("");
1496         if (usbi_backend->get_configuration)
1497                 r = usbi_backend->get_configuration(dev, config);
1498
1499         if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
1500                 uint8_t tmp = 0;
1501                 usbi_dbg("falling back to control message");
1502                 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1503                                 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
1504                 if (r == 0) {
1505                         usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
1506                         r = LIBUSB_ERROR_IO;
1507                 } else if (r == 1) {
1508                         r = 0;
1509                         *config = tmp;
1510                 } else {
1511                         usbi_dbg("control failed, error %d", r);
1512                 }
1513         }
1514
1515         if (r == 0)
1516                 usbi_dbg("active config %d", *config);
1517
1518         return r;
1519 }
1520
1521 /** \ingroup dev
1522  * Set the active configuration for a device.
1523  *
1524  * The operating system may or may not have already set an active
1525  * configuration on the device. It is up to your application to ensure the
1526  * correct configuration is selected before you attempt to claim interfaces
1527  * and perform other operations.
1528  *
1529  * If you call this function on a device already configured with the selected
1530  * configuration, then this function will act as a lightweight device reset:
1531  * it will issue a SET_CONFIGURATION request using the current configuration,
1532  * causing most USB-related device state to be reset (altsetting reset to zero,
1533  * endpoint halts cleared, toggles reset).
1534  *
1535  * You cannot change/reset configuration if your application has claimed
1536  * interfaces. It is advised to set the desired configuration before claiming
1537  * interfaces.
1538  *
1539  * Alternatively you can call libusb_release_interface() first. Note if you
1540  * do things this way you must ensure that auto_detach_kernel_driver for
1541  * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
1542  * release the interface(s).
1543  *
1544  * You cannot change/reset configuration if other applications or drivers have
1545  * claimed interfaces.
1546  *
1547  * A configuration value of -1 will put the device in unconfigured state.
1548  * The USB specifications state that a configuration value of 0 does this,
1549  * however buggy devices exist which actually have a configuration 0.
1550  *
1551  * You should always use this function rather than formulating your own
1552  * SET_CONFIGURATION control request. This is because the underlying operating
1553  * system needs to know when such changes happen.
1554  *
1555  * This is a blocking function.
1556  *
1557  * \param dev a device handle
1558  * \param configuration the bConfigurationValue of the configuration you
1559  * wish to activate, or -1 if you wish to put the device in unconfigured state
1560  * \returns 0 on success
1561  * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
1562  * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
1563  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1564  * \returns another LIBUSB_ERROR code on other failure
1565  * \see libusb_set_auto_detach_kernel_driver()
1566  */
1567 int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
1568                 int configuration) {
1569
1570         usbi_dbg("configuration %d", configuration);
1571         return usbi_backend->set_configuration(dev, configuration);
1572 }
1573
1574 /** \ingroup dev
1575  * Claim an interface on a given device handle. You must claim the interface
1576  * you wish to use before you can perform I/O on any of its endpoints.
1577  *
1578  * It is legal to attempt to claim an already-claimed interface, in which
1579  * case libusb just returns 0 without doing anything.
1580  *
1581  * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
1582  * will be detached if necessary, on failure the detach error is returned.
1583  *
1584  * Claiming of interfaces is a purely logical operation; it does not cause
1585  * any requests to be sent over the bus. Interface claiming is used to
1586  * instruct the underlying operating system that your application wishes
1587  * to take ownership of the interface.
1588  *
1589  * This is a non-blocking function.
1590  *
1591  * \param dev a device handle
1592  * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
1593  * wish to claim
1594  * \returns 0 on success
1595  * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
1596  * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
1597  * interface
1598  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1599  * \returns a LIBUSB_ERROR code on other failure
1600  * \see libusb_set_auto_detach_kernel_driver()
1601  */
1602 int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
1603                 int interface_number) {
1604
1605         ENTER();
1606
1607         int r = LIBUSB_SUCCESS;
1608
1609         usbi_dbg("interface %d", interface_number);
1610         LOGD("interface %d", interface_number);
1611
1612         if (interface_number >= USB_MAXINTERFACES) {
1613                 RETURN(LIBUSB_ERROR_INVALID_PARAM, int);
1614         }
1615
1616         if (UNLIKELY(!dev->dev->attached)) {
1617                 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1618         }
1619
1620         usbi_mutex_lock(&dev->lock);
1621         if (!(dev->claimed_interfaces & (1 << interface_number))) {
1622                 r = usbi_backend->claim_interface(dev, interface_number);
1623                 if (r == LIBUSB_ERROR_BUSY) {
1624                         // EBUSYが返ってきた時はたぶんカーネルドライバーがアタッチされているから
1625                         // デタッチ要求してから再度claimしてみる
1626                         LOGV("request detach kernel driver and retry claim interface");
1627                         r = usbi_backend->release_interface(dev, interface_number);
1628                         libusb_detach_kernel_driver(dev, interface_number);
1629                         if (!r) {
1630                                 r = usbi_backend->claim_interface(dev, interface_number);
1631                         }
1632                 }
1633                 if (!r) {
1634                         dev->claimed_interfaces |= 1 << interface_number;
1635                 }
1636         } else {
1637                 LOGV("already claimed");
1638         }
1639         usbi_mutex_unlock(&dev->lock);
1640
1641         RETURN(r, int);
1642 }
1643
1644 /** \ingroup dev
1645  * Release an interface previously claimed with libusb_claim_interface(). You
1646  * should release all claimed interfaces before closing a device handle.
1647  *
1648  * This is a blocking function. A SET_INTERFACE control request will be sent
1649  * to the device, resetting interface state to the first alternate setting.
1650  *
1651  * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
1652  * driver will be re-attached after releasing the interface.
1653  *
1654  * \param dev a device handle
1655  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1656  * previously-claimed interface
1657  * \returns 0 on success
1658  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
1659  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1660  * \returns another LIBUSB_ERROR code on other failure
1661  * \see libusb_set_auto_detach_kernel_driver()
1662  */
1663 int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
1664                 int interface_number) {
1665
1666         ENTER();
1667
1668         int r;
1669
1670         LOGD("interface %d", interface_number);
1671         usbi_dbg("interface %d", interface_number);
1672         if (UNLIKELY(interface_number >= USB_MAXINTERFACES))
1673                 RETURN(LIBUSB_ERROR_INVALID_PARAM, int);
1674
1675         usbi_mutex_lock(&dev->lock);
1676         {
1677                 if (dev->claimed_interfaces & (1 << interface_number)) {
1678                         r = usbi_backend->release_interface(dev, interface_number);
1679                         if (!r) {
1680                                 LOGV("released");
1681                                 dev->claimed_interfaces &= ~(1 << interface_number);
1682                         }
1683                 } else {
1684                         // already released
1685                         r = LIBUSB_ERROR_NOT_FOUND;
1686                 }
1687         }
1688         usbi_mutex_unlock(&dev->lock);
1689
1690         RETURN(r, int);
1691 }
1692
1693 /** \ingroup dev
1694  * Activate an alternate setting for an interface. The interface must have
1695  * been previously claimed with libusb_claim_interface().
1696  *
1697  * You should always use this function rather than formulating your own
1698  * SET_INTERFACE control request. This is because the underlying operating
1699  * system needs to know when such changes happen.
1700  *
1701  * This is a blocking function.
1702  *
1703  * \param dev a device handle
1704  * \param interface_number the <tt>bInterfaceNumber</tt> of the
1705  * previously-claimed interface
1706  * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
1707  * setting to activate
1708  * \returns 0 on success
1709  * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
1710  * requested alternate setting does not exist
1711  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1712  * \returns another LIBUSB_ERROR code on other failure
1713  */
1714 int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
1715                 int interface_number, int alternate_setting) {
1716
1717         usbi_dbg("interface %d altsetting %d", interface_number, alternate_setting);
1718         if (interface_number >= USB_MAXINTERFACES)
1719                 return LIBUSB_ERROR_INVALID_PARAM;
1720
1721         usbi_mutex_lock(&dev->lock);
1722         {
1723                 if (UNLIKELY(!dev->dev->attached)) {
1724                         usbi_mutex_unlock(&dev->lock);
1725                         return LIBUSB_ERROR_NO_DEVICE;
1726                 }
1727
1728                 if (UNLIKELY(!(dev->claimed_interfaces & (1 << interface_number)))) {
1729                         usbi_mutex_unlock(&dev->lock);
1730                         return LIBUSB_ERROR_NOT_FOUND;
1731                 }
1732         }
1733         usbi_mutex_unlock(&dev->lock);
1734
1735         return usbi_backend->set_interface_altsetting(dev, interface_number,
1736                         alternate_setting);
1737 }
1738
1739 /** \ingroup dev
1740  * Clear the halt/stall condition for an endpoint. Endpoints with halt status
1741  * are unable to receive or transmit data until the halt condition is stalled.
1742  *
1743  * You should cancel all pending transfers before attempting to clear the halt
1744  * condition.
1745  *
1746  * This is a blocking function.
1747  *
1748  * \param dev a device handle
1749  * \param endpoint the endpoint to clear halt status
1750  * \returns 0 on success
1751  * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
1752  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1753  * \returns another LIBUSB_ERROR code on other failure
1754  */
1755 int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
1756                 unsigned char endpoint) {
1757
1758         usbi_dbg("endpoint %x", endpoint);
1759         if (UNLIKELY(!dev->dev->attached))
1760                 return LIBUSB_ERROR_NO_DEVICE;
1761
1762         return usbi_backend->clear_halt(dev, endpoint);
1763 }
1764
1765 /** \ingroup dev
1766  * Perform a USB port reset to reinitialize a device. The system will attempt
1767  * to restore the previous configuration and alternate settings after the
1768  * reset has completed.
1769  *
1770  * If the reset fails, the descriptors change, or the previous state cannot be
1771  * restored, the device will appear to be disconnected and reconnected. This
1772  * means that the device handle is no longer valid (you should close it) and
1773  * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
1774  * when this is the case.
1775  *
1776  * This is a blocking function which usually incurs a noticeable delay.
1777  *
1778  * \param dev a handle of the device to reset
1779  * \returns 0 on success
1780  * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
1781  * device has been disconnected
1782  * \returns another LIBUSB_ERROR code on other failure
1783  */
1784 int API_EXPORTED libusb_reset_device(libusb_device_handle *dev) {
1785
1786         usbi_dbg("");
1787         if (UNLIKELY(!dev->dev->attached))
1788                 return LIBUSB_ERROR_NO_DEVICE;
1789
1790         return usbi_backend->reset_device(dev);
1791 }
1792
1793 /** \ingroup asyncio
1794  * Allocate up to num_streams usb bulk streams on the specified endpoints. This
1795  * function takes an array of endpoints rather then a single endpoint because
1796  * some protocols require that endpoints are setup with similar stream ids.
1797  * All endpoints passed in must belong to the same interface.
1798  *
1799  * Note this function may return less streams then requested. Also note that the
1800  * same number of streams are allocated for each endpoint in the endpoint array.
1801  *
1802  * Stream id 0 is reserved, and should not be used to communicate with devices.
1803  * If libusb_alloc_streams() returns with a value of N, you may use stream ids
1804  * 1 to N.
1805  *
1806  * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1807  *
1808  * \param dev a device handle
1809  * \param num_streams number of streams to try to allocate
1810  * \param endpoints array of endpoints to allocate streams on
1811  * \param num_endpoints length of the endpoints array
1812  * \returns number of streams allocated, or a LIBUSB_ERROR code on failure
1813  */
1814 int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev,
1815         uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1816 {
1817         usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints);
1818
1819         if UNLIKELY(!dev->dev->attached)
1820                 return LIBUSB_ERROR_NO_DEVICE;
1821
1822         if LIKELY(usbi_backend->alloc_streams)
1823                 return usbi_backend->alloc_streams(dev, num_streams, endpoints,
1824                                                    num_endpoints);
1825         else
1826                 return LIBUSB_ERROR_NOT_SUPPORTED;
1827 }
1828
1829 /** \ingroup asyncio
1830  * Free usb bulk streams allocated with libusb_alloc_streams().
1831  *
1832  * Note streams are automatically free-ed when releasing an interface.
1833  *
1834  * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103
1835  *
1836  * \param dev a device handle
1837  * \param endpoints array of endpoints to free streams on
1838  * \param num_endpoints length of the endpoints array
1839  * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure
1840  */
1841 int API_EXPORTED libusb_free_streams(libusb_device_handle *dev,
1842         unsigned char *endpoints, int num_endpoints)
1843 {
1844         ENTER();
1845
1846         LOGD("eps %d", num_endpoints);
1847         usbi_dbg("eps %d", num_endpoints);
1848
1849         if UNLIKELY(!dev->dev->attached) {
1850                 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1851         }
1852
1853         if LIKELY(usbi_backend->free_streams) {
1854                 RETURN(usbi_backend->free_streams(dev, endpoints, num_endpoints), int);
1855         } else {
1856                 RETURN(LIBUSB_ERROR_NOT_SUPPORTED, int);
1857         }
1858 }
1859
1860 /** \ingroup dev
1861  * Determine if a kernel driver is active on an interface. If a kernel driver
1862  * is active, you cannot claim the interface, and libusb will be unable to
1863  * perform I/O.
1864  *
1865  * This functionality is not available on Windows.
1866  *
1867  * \param dev a device handle
1868  * \param interface_number the interface to check
1869  * \returns 0 if no kernel driver is active
1870  * \returns 1 if a kernel driver is active
1871  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1872  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1873  * is not available
1874  * \returns another LIBUSB_ERROR code on other failure
1875  * \see libusb_detach_kernel_driver()
1876  */
1877 int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
1878                 int interface_number) {
1879
1880         ENTER();
1881
1882         LOGD("interface %d", interface_number);
1883         usbi_dbg("interface %d", interface_number);
1884
1885         if (UNLIKELY(!dev->dev->attached)) {
1886                 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1887         }
1888
1889         if LIKELY(usbi_backend->kernel_driver_active) {
1890                 RETURN(usbi_backend->kernel_driver_active(dev, interface_number), int);
1891         } else {
1892                 RETURN(LIBUSB_ERROR_NOT_SUPPORTED, int);
1893         }
1894 }
1895
1896 /** \ingroup dev
1897  * Detach a kernel driver from an interface. If successful, you will then be
1898  * able to claim the interface and perform I/O.
1899  *
1900  * This functionality is not available on Darwin or Windows.
1901  *
1902  * Note that libusb itself also talks to the device through a special kernel
1903  * driver, if this driver is already attached to the device, this call will
1904  * not detach it and return LIBUSB_ERROR_NOT_FOUND.
1905  *
1906  * \param dev a device handle
1907  * \param interface_number the interface to detach the driver from
1908  * \returns 0 on success
1909  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1910  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1911  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1912  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1913  * is not available
1914  * \returns another LIBUSB_ERROR code on other failure
1915  * \see libusb_kernel_driver_active()
1916  */
1917 int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
1918                 int interface_number) {
1919
1920         usbi_dbg("interface %d", interface_number);
1921
1922         if (UNLIKELY(!dev->dev->attached))
1923                 return LIBUSB_ERROR_NO_DEVICE;
1924
1925         if (LIKELY(usbi_backend->detach_kernel_driver))
1926                 return usbi_backend->detach_kernel_driver(dev, interface_number);
1927         else
1928                 return LIBUSB_ERROR_NOT_SUPPORTED;
1929 }
1930
1931 /** \ingroup dev
1932  * Re-attach an interface's kernel driver, which was previously detached
1933  * using libusb_detach_kernel_driver(). This call is only effective on
1934  * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
1935  *
1936  * This functionality is not available on Darwin or Windows.
1937  *
1938  * \param dev a device handle
1939  * \param interface_number the interface to attach the driver from
1940  * \returns 0 on success
1941  * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
1942  * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
1943  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
1944  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1945  * is not available
1946  * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
1947  * interface is claimed by a program or driver
1948  * \returns another LIBUSB_ERROR code on other failure
1949  * \see libusb_kernel_driver_active()
1950  */
1951 int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
1952                 int interface_number) {
1953
1954         ENTER();
1955
1956         LOGD("interface %d", interface_number);
1957         usbi_dbg("interface %d", interface_number);
1958
1959         if (UNLIKELY(!dev->dev->attached)) {
1960                 RETURN(LIBUSB_ERROR_NO_DEVICE, int);
1961         }
1962
1963         if (LIKELY(usbi_backend->attach_kernel_driver)) {
1964                 RETURN(usbi_backend->attach_kernel_driver(dev, interface_number), int);
1965         } else {
1966                 RETURN(LIBUSB_ERROR_NOT_SUPPORTED, int);
1967         }
1968 }
1969
1970 /** \ingroup dev
1971  * Enable/disable libusb's automatic kernel driver detachment. When this is
1972  * enabled libusb will automatically detach the kernel driver on an interface
1973  * when claiming the interface, and attach it when releasing the interface.
1974  *
1975  * Automatic kernel driver detachment is disabled on newly opened device
1976  * handles by default.
1977  *
1978  * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
1979  * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will
1980  * continue as if this function was never called.
1981  *
1982  * \param dev a device handle
1983  * \param enable whether to enable or disable auto kernel driver detachment
1984  *
1985  * \returns LIBUSB_SUCCESS on success
1986  * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
1987  * is not available
1988  * \see libusb_claim_interface()
1989  * \see libusb_release_interface()
1990  * \see libusb_set_configuration()
1991  */
1992 int API_EXPORTED libusb_set_auto_detach_kernel_driver(libusb_device_handle *dev,
1993                 int enable) {
1994
1995         ENTER();
1996
1997         LOGD("enable=%d", enable);
1998         if (!(usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER)) {
1999                 LOGD("does not support detach kernel driver");
2000                 RETURN(LIBUSB_ERROR_NOT_SUPPORTED, int);
2001         }
2002
2003         dev->auto_detach_kernel_driver = enable;
2004         RETURN(LIBUSB_SUCCESS, int);
2005 }
2006
2007 /** \ingroup lib
2008  * Set log message verbosity.
2009  *
2010  * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
2011  * printed. If you choose to increase the message verbosity level, ensure
2012  * that your application does not close the stdout/stderr file descriptors.
2013  *
2014  * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusb is conservative
2015  * with its message logging and most of the time, will only log messages that
2016  * explain error conditions and other oddities. This will help you debug
2017  * your software.
2018  *
2019  * If the LIBUSB_DEBUG environment variable was set when libusb was
2020  * initialized, this function does nothing: the message verbosity is fixed
2021  * to the value in the environment variable.
2022  *
2023  * If libusb was compiled without any message logging, this function does
2024  * nothing: you'll never get any messages.
2025  *
2026  * If libusb was compiled with verbose debug message logging, this function
2027  * does nothing: you'll always get messages from all levels.
2028  *
2029  * \param ctx the context to operate on, or NULL for the default context
2030  * \param level debug level to set
2031  */
2032 void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level) {
2033
2034         USBI_GET_CONTEXT(ctx);
2035         if (!ctx->debug_fixed)
2036                 ctx->debug = level;
2037 }
2038
2039 int API_EXPORTED libusb_init2(libusb_context **context, const char *usbfs) {
2040         ENTER();
2041         struct libusb_device *dev, *next;
2042         char *dbg = getenv("LIBUSB_DEBUG");
2043         struct libusb_context *ctx;
2044         static int first_init = 1;
2045         int r = 0;
2046
2047         usbi_mutex_static_lock(&default_context_lock);
2048         {
2049                 if (!timestamp_origin.tv_sec) {
2050                         usbi_gettimeofday(&timestamp_origin, NULL);
2051                 }
2052
2053                 if (!context && usbi_default_context) {
2054                         usbi_dbg("reusing default context");
2055                         LOGI("reusing default context");
2056                         default_context_refcnt++;
2057                         usbi_mutex_static_unlock(&default_context_lock);
2058                         return LIBUSB_SUCCESS;
2059                 }
2060
2061                 ctx = calloc(1, sizeof(*ctx));
2062                 if (UNLIKELY(!ctx)) {
2063                         r = LIBUSB_ERROR_NO_MEM;
2064                         goto err_unlock;
2065                 }
2066
2067 #ifdef ENABLE_DEBUG_LOGGING
2068                 ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
2069 #endif
2070
2071                 if (UNLIKELY(dbg)) {
2072                         ctx->debug = atoi(dbg);
2073                         if (ctx->debug)
2074                                 ctx->debug_fixed = 1;
2075                 }
2076
2077                 /* default context should be initialized before calling usbi_dbg */
2078                 if (!usbi_default_context) {
2079                         usbi_default_context = ctx;
2080                         default_context_refcnt++;
2081                         usbi_dbg("created default context");
2082                 }
2083
2084                 LOGI("libusb v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
2085                         libusb_version_internal.micro, libusb_version_internal.nano);
2086
2087                 usbi_dbg("libusb v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
2088                         libusb_version_internal.micro, libusb_version_internal.nano);
2089
2090                 usbi_mutex_init(&ctx->usb_devs_lock, NULL);
2091                 usbi_mutex_init(&ctx->open_devs_lock, NULL);
2092                 usbi_mutex_init(&ctx->hotplug_cbs_lock, NULL);
2093                 list_init(&ctx->usb_devs);
2094                 list_init(&ctx->open_devs);
2095                 list_init(&ctx->hotplug_cbs);
2096
2097                 usbi_mutex_static_lock(&active_contexts_lock);
2098                 {
2099                         if (first_init) {
2100                                 first_init = 0;
2101                                 list_init(&active_contexts_list);
2102                         }
2103                         list_add(&ctx->list, &active_contexts_list);
2104                 }
2105                 usbi_mutex_static_unlock(&active_contexts_lock);
2106
2107                 if (LIKELY(usbfs && strlen(usbfs) > 0)) {
2108                         LOGD("call usbi_backend->init2");
2109                         if (usbi_backend->init2) {
2110                                 r = usbi_backend->init2(ctx, usbfs);
2111                                 if (UNLIKELY(r)) {
2112                                         LOGE("failed to call usbi_backend->init2, err=%d", r);
2113                                         goto err_free_ctx;
2114                                 }
2115                         } else {
2116                                 LOGE("has no usbi_backend->init2");
2117                                 goto err_free_ctx;
2118                         }
2119                 } else {
2120                         LOGD("call usbi_backend->init");
2121                         if (usbi_backend->init) {
2122                                 r = usbi_backend->init(ctx);
2123                                 if (UNLIKELY(r))
2124                                         goto err_free_ctx;
2125                         } else
2126                                 goto err_free_ctx;
2127                 }
2128
2129                 r = usbi_io_init(ctx);
2130                 if (UNLIKELY(r < 0))
2131                         goto err_backend_exit;
2132         }
2133         usbi_mutex_static_unlock(&default_context_lock);
2134
2135         if (context)
2136                 *context = ctx;
2137
2138         RETURN(LIBUSB_SUCCESS, int);
2139
2140 err_backend_exit:
2141         LOGI("err_backend_exit");
2142         if (usbi_backend->exit)
2143                 usbi_backend->exit();
2144 err_free_ctx:
2145         LOGI("err_free_ctx");
2146         if (ctx == usbi_default_context)
2147                 usbi_default_context = NULL;
2148
2149         usbi_mutex_static_lock(&active_contexts_lock);
2150         {
2151                 list_del(&ctx->list);
2152         }
2153         usbi_mutex_static_unlock(&active_contexts_lock);
2154
2155         usbi_mutex_lock(&ctx->usb_devs_lock);
2156         {
2157                 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device)
2158                 {
2159                         list_del(&dev->list);
2160                         libusb_unref_device(dev);
2161                 }
2162         }
2163         usbi_mutex_unlock(&ctx->usb_devs_lock);
2164
2165         usbi_mutex_destroy(&ctx->open_devs_lock);
2166         usbi_mutex_destroy(&ctx->usb_devs_lock);
2167         usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2168
2169         free(ctx);
2170 err_unlock:
2171         LOGI("err_unlock");
2172         usbi_mutex_static_unlock(&default_context_lock);
2173         RETURN(r, int);
2174 }
2175
2176 /** \ingroup lib
2177  * Initialize libusb. This function must be called before calling any other
2178  * libusb function.
2179  *
2180  * If you do not provide an output location for a context pointer, a default
2181  * context will be created. If there was already a default context, it will
2182  * be reused (and nothing will be initialized/reinitialized).
2183  *
2184  * \param context Optional output location for context pointer.
2185  * Only valid on return code 0.
2186  * \returns 0 on success, or a LIBUSB_ERROR code on failure
2187  * \see contexts
2188  */
2189 int API_EXPORTED libusb_init(libusb_context **context) {
2190
2191         return libusb_init2(context, NULL);
2192 #if 0
2193         struct libusb_device *dev, *next;
2194         char *dbg = getenv("LIBUSB_DEBUG");
2195         struct libusb_context *ctx;
2196         static int first_init = 1;
2197         int r = 0;
2198
2199         usbi_mutex_static_lock(&default_context_lock);
2200         {
2201                 if (!timestamp_origin.tv_sec) {
2202                         usbi_gettimeofday(&timestamp_origin, NULL);
2203                 }
2204
2205                 if (!context && usbi_default_context) {
2206                         usbi_dbg("reusing default context");
2207                         default_context_refcnt++;
2208                         usbi_mutex_static_unlock(&default_context_lock);
2209                         return LIBUSB_SUCCESS;
2210                 }
2211
2212                 ctx = calloc(1, sizeof(*ctx));
2213                 if (UNLIKELY(!ctx)) {
2214                         r = LIBUSB_ERROR_NO_MEM;
2215                         goto err_unlock;
2216                 }
2217
2218 #ifdef ENABLE_DEBUG_LOGGING
2219                 ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
2220 #endif
2221
2222                 if (UNLIKELY(dbg)) {
2223                         ctx->debug = atoi(dbg);
2224                         if (ctx->debug)
2225                                 ctx->debug_fixed = 1;
2226                 }
2227
2228                 /* default context should be initialized before calling usbi_dbg */
2229                 if (!usbi_default_context) {
2230                         usbi_default_context = ctx;
2231                         default_context_refcnt++;
2232                         usbi_dbg("created default context");
2233                 }
2234
2235                 usbi_dbg("libusb v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
2236                         libusb_version_internal.micro, libusb_version_internal.nano);
2237
2238                 usbi_mutex_init(&ctx->usb_devs_lock, NULL);
2239                 usbi_mutex_init(&ctx->open_devs_lock, NULL);
2240                 usbi_mutex_init(&ctx->hotplug_cbs_lock, NULL);
2241                 list_init(&ctx->usb_devs);
2242                 list_init(&ctx->open_devs);
2243                 list_init(&ctx->hotplug_cbs);
2244
2245                 usbi_mutex_static_lock(&active_contexts_lock);
2246                 {
2247                         if (first_init) {
2248                                 first_init = 0;
2249                                 list_init(&active_contexts_list);
2250                         }
2251                         list_add(&ctx->list, &active_contexts_list);
2252                 }
2253                 usbi_mutex_static_unlock(&active_contexts_lock);
2254
2255                 if (usbi_backend->init) {
2256                         r = usbi_backend->init(ctx);
2257                         if (UNLIKELY(r))
2258                                 goto err_free_ctx;
2259                 }
2260
2261                 r = usbi_io_init(ctx);
2262                 if (UNLIKELY(r < 0))
2263                         goto err_backend_exit;
2264         }
2265         usbi_mutex_static_unlock(&default_context_lock);
2266
2267         if (context)
2268                 *context = ctx;
2269
2270         return LIBUSB_SUCCESS;
2271
2272 err_backend_exit:
2273         if (usbi_backend->exit)
2274                 usbi_backend->exit();
2275 err_free_ctx:
2276         if (ctx == usbi_default_context)
2277                 usbi_default_context = NULL;
2278
2279         usbi_mutex_static_lock(&active_contexts_lock);
2280         {
2281                 list_del(&ctx->list);
2282         }
2283         usbi_mutex_static_unlock(&active_contexts_lock);
2284
2285         usbi_mutex_lock(&ctx->usb_devs_lock);
2286         {
2287                 list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device)
2288                 {
2289                         list_del(&dev->list);
2290                         libusb_unref_device(dev);
2291                 }
2292         }
2293         usbi_mutex_unlock(&ctx->usb_devs_lock);
2294
2295         usbi_mutex_destroy(&ctx->open_devs_lock);
2296         usbi_mutex_destroy(&ctx->usb_devs_lock);
2297         usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2298
2299         free(ctx);
2300 err_unlock:
2301         usbi_mutex_static_unlock(&default_context_lock);
2302         return r;
2303 #endif
2304 }
2305
2306 /** \ingroup lib
2307  * Deinitialize libusb. Should be called after closing all open devices and
2308  * before your application terminates.
2309  * \param ctx the context to deinitialize, or NULL for the default context
2310  */
2311 void API_EXPORTED libusb_exit(struct libusb_context *ctx) {
2312
2313         struct libusb_device *dev, *next;
2314         struct timeval tv = { 0, 0 };
2315
2316         usbi_dbg("");
2317         USBI_GET_CONTEXT(ctx);
2318
2319         /* if working with default context, only actually do the deinitialization
2320          * if we're the last user */
2321         usbi_mutex_static_lock(&default_context_lock);
2322         if (ctx == usbi_default_context) {
2323                 if (--default_context_refcnt > 0) {
2324                         usbi_dbg("not destroying default context");
2325                         usbi_mutex_static_unlock(&default_context_lock);
2326                         return;
2327                 }
2328                 usbi_dbg("destroying default context");
2329                 usbi_default_context = NULL;
2330         }
2331         usbi_mutex_static_unlock(&default_context_lock);
2332
2333         usbi_mutex_static_lock(&active_contexts_lock);
2334         {
2335                 list_del(&ctx->list);
2336         }
2337         usbi_mutex_static_unlock(&active_contexts_lock);
2338
2339         if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
2340                 usbi_hotplug_deregister_all(ctx);
2341
2342                 /*
2343                  * Ensure any pending unplug events are read from the hotplug
2344                  * pipe. The usb_device-s hold in the events are no longer part
2345                  * of usb_devs, but the events still hold a reference!
2346                  *
2347                  * Note we don't do this if the application has left devices
2348                  * open (which implies a buggy app) to avoid packet completion
2349                  * handlers running when the app does not expect them to run.
2350                  */
2351                 if (list_empty(&ctx->open_devs))
2352                         libusb_handle_events_timeout(ctx, &tv);
2353
2354                 usbi_mutex_lock(&ctx->usb_devs_lock);
2355                 {
2356                         list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device)
2357                         {
2358                                 list_del(&dev->list);
2359                                 libusb_unref_device(dev);
2360                         }
2361                 }
2362                 usbi_mutex_unlock(&ctx->usb_devs_lock);
2363         }
2364
2365         /* a few sanity checks. don't bother with locking because unless
2366          * there is an application bug, nobody will be accessing these. */
2367         if (!list_empty(&ctx->usb_devs))
2368                 usbi_warn(ctx, "some libusb_devices were leaked");
2369         if (!list_empty(&ctx->open_devs))
2370                 usbi_warn(ctx, "application left some devices open");
2371
2372         usbi_io_exit(ctx);
2373         if (usbi_backend->exit)
2374                 usbi_backend->exit();
2375
2376         usbi_mutex_destroy(&ctx->open_devs_lock);
2377         usbi_mutex_destroy(&ctx->usb_devs_lock);
2378         usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
2379         free(ctx);
2380 }
2381
2382 /** \ingroup misc
2383  * Check at runtime if the loaded library has a given capability.
2384  * This call should be performed after \ref libusb_init(), to ensure the
2385  * backend has updated its capability set.
2386  *
2387  * \param capability the \ref libusb_capability to check for
2388  * \returns nonzero if the running library has the capability, 0 otherwise
2389  */
2390 int API_EXPORTED libusb_has_capability(uint32_t capability) {
2391
2392         switch (capability) {
2393         case LIBUSB_CAP_HAS_CAPABILITY:
2394                 return 1;
2395         case LIBUSB_CAP_HAS_HOTPLUG:
2396                 return !(usbi_backend->get_device_list);
2397         case LIBUSB_CAP_HAS_HID_ACCESS:
2398                 return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS);
2399         case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
2400                 return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
2401         }
2402         return LIBUSB_SUCCESS;
2403 }
2404
2405 /* this is defined in libusbi.h if needed */
2406 #ifdef LIBUSB_GETTIMEOFDAY_WIN32
2407 /*
2408  * gettimeofday
2409  * Implementation according to:
2410  * The Open Group Base Specifications Issue 6
2411  * IEEE Std 1003.1, 2004 Edition
2412  */
2413
2414 /*
2415  *  THIS SOFTWARE IS NOT COPYRIGHTED
2416  *
2417  *  This source code is offered for use in the public domain. You may
2418  *  use, modify or distribute it freely.
2419  *
2420  *  This code is distributed in the hope that it will be useful but
2421  *  WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
2422  *  DISCLAIMED. This includes but is not limited to warranties of
2423  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
2424  *
2425  *  Contributed by:
2426  *  Danny Smith <dannysmith@users.sourceforge.net>
2427  */
2428
2429 /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
2430 #define _W32_FT_OFFSET (116444736000000000)
2431
2432 int usbi_gettimeofday(struct timeval *tp, void *tzp)
2433 {
2434         union {
2435                 unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
2436                 FILETIME ft;
2437         } _now;
2438         UNUSED(tzp);
2439
2440         if(tp) {
2441 #if defined(OS_WINCE)
2442                 SYSTEMTIME st;
2443                 GetSystemTime(&st);
2444                 SystemTimeToFileTime(&st, &_now.ft);
2445 #else
2446                 GetSystemTimeAsFileTime (&_now.ft);
2447 #endif
2448                 tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
2449                 tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
2450         }
2451         /* Always return 0 as per Open Group Base Specifications Issue 6.
2452          Do not set errno on error.  */
2453         return LIBUSB_SUCCESS;
2454 }
2455 #endif
2456
2457 static void usbi_log_str(struct libusb_context *ctx,
2458         enum libusb_log_level level, const char * str) {
2459
2460 #if defined(USE_SYSTEM_LOGGING_FACILITY)
2461 #if defined(OS_WINDOWS) || defined(OS_WINCE)
2462         /* Windows CE only supports the Unicode version of OutputDebugString. */
2463         WCHAR wbuf[USBI_MAX_LOG_LEN];
2464         MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
2465         OutputDebugStringW(wbuf);
2466 #elif defined(__ANDROID__)
2467         int priority = ANDROID_LOG_UNKNOWN;
2468         switch (level) {
2469         case LIBUSB_LOG_LEVEL_NONE: break;      // XXX add to avoid warning when compiling with clang
2470         case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
2471         case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
2472         case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
2473         case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
2474         }
2475         __android_log_write(priority, "libusb", str);
2476 #elif defined(HAVE_SYSLOG_FUNC)
2477         int syslog_level = LOG_INFO;
2478         switch (level) {
2479         case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
2480         case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
2481         case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
2482         case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
2483         }
2484         syslog(syslog_level, "%s", str);
2485 #else /* All of gcc, Clang, XCode seem to use #warning */
2486 #warning System logging is not supported on this platform. Logging to stderr will be used instead.
2487         fputs(str, stderr);
2488 #endif
2489 #else
2490         fputs(str, stderr);
2491 #endif /* USE_SYSTEM_LOGGING_FACILITY */
2492         UNUSED(ctx);
2493         UNUSED(level);
2494 }
2495
2496 void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
2497         const char *function, const char *format, va_list args) {
2498
2499 #ifndef __ANDROID__
2500         const char *prefix = "";
2501 #endif
2502         char buf[USBI_MAX_LOG_LEN];
2503         struct timeval now;
2504         int global_debug, header_len, text_len;
2505         static int has_debug_header_been_displayed = 0;
2506
2507 #ifdef ENABLE_DEBUG_LOGGING
2508         global_debug = 1;
2509         UNUSED(ctx);
2510 #else
2511         int ctx_level = 0;
2512
2513         USBI_GET_CONTEXT(ctx);
2514         if (ctx) {
2515                 ctx_level = ctx->debug;
2516         } else {
2517                 char *dbg = getenv("LIBUSB_DEBUG");
2518                 if (dbg)
2519                         ctx_level = atoi(dbg);
2520         }
2521 #ifdef __ANDROID__
2522         global_debug = 0;
2523 #else
2524         global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG);
2525 #endif
2526         if (!ctx_level)
2527                 return;
2528         if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING)
2529                 return;
2530         if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO)
2531                 return;
2532         if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG)
2533                 return;
2534 #endif
2535
2536         usbi_gettimeofday(&now, NULL);
2537         if ((global_debug) && (!has_debug_header_been_displayed)) {
2538                 has_debug_header_been_displayed = 1;
2539                 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>\n");
2540                 usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------\n");
2541         }
2542         if (now.tv_usec < timestamp_origin.tv_usec) {
2543                 now.tv_sec--;
2544                 now.tv_usec += 1000000;
2545         }
2546         now.tv_sec -= timestamp_origin.tv_sec;
2547         now.tv_usec -= timestamp_origin.tv_usec;
2548 #ifndef __ANDROID__
2549         switch (level) {
2550         case LIBUSB_LOG_LEVEL_INFO:
2551                 prefix = "info";
2552                 break;
2553         case LIBUSB_LOG_LEVEL_WARNING:
2554                 prefix = "warning";
2555                 break;
2556         case LIBUSB_LOG_LEVEL_ERROR:
2557                 prefix = "error";
2558                 break;
2559         case LIBUSB_LOG_LEVEL_DEBUG:
2560                 prefix = "debug";
2561                 break;
2562         case LIBUSB_LOG_LEVEL_NONE:
2563                 return;
2564         default:
2565                 prefix = "unknown";
2566                 break;
2567         }
2568 #endif
2569 #ifdef __ANDROID__
2570         header_len = snprintf(buf, sizeof(buf), "[%s] ", function);
2571 #else
2572         if (global_debug) {
2573                 header_len = snprintf(buf, sizeof(buf),
2574                         "[%2d.%06d] [%08x] libusb: %s [%s] ", (int) now.tv_sec,
2575                         (int) now.tv_usec, usbi_get_tid(), prefix, function);
2576         } else {
2577                 header_len = snprintf(buf, sizeof(buf),
2578                         "libusb:%s [%s] ", prefix, function);
2579         }
2580 #endif
2581
2582         if (header_len < 0 || header_len >= sizeof(buf)) {
2583                 /* Somehow snprintf failed to write to the buffer,
2584                  * remove the header so something useful is output. */
2585                 header_len = 0;
2586         }
2587         /* Make sure buffer is NUL terminated */
2588         buf[header_len] = '\0';
2589         text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len, format, args);
2590         if (text_len < 0 || text_len + header_len >= sizeof(buf)) {
2591                 /* Truncated log output. On some platforms a -1 return value means
2592                  * that the output was truncated. */
2593                 text_len = sizeof(buf) - header_len;
2594         }
2595         if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
2596                 /* Need to truncate the text slightly to fit on the terminator. */
2597                 text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
2598         }
2599         strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
2600
2601         usbi_log_str(ctx, level, buf);
2602 }
2603
2604 void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
2605         const char *function, const char *format, ...) {
2606
2607         va_list args;
2608
2609         va_start(args, format);
2610         usbi_log_v(ctx, level, function, format, args);
2611         va_end(args);
2612 }
2613
2614 /** \ingroup misc
2615  * Returns a constant NULL-terminated string with the ASCII name of a libusb
2616  * error or transfer status code. The caller must not free() the returned
2617  * string.
2618  *
2619  * \param error_code The \ref libusb_error or libusb_transfer_status code to
2620  * return the name of.
2621  * \returns The error name, or the string **UNKNOWN** if the value of
2622  * error_code is not a known error / status code.
2623  */
2624 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code) {
2625
2626         switch (error_code) {
2627         case LIBUSB_ERROR_IO:
2628                 return "LIBUSB_ERROR_IO";
2629         case LIBUSB_ERROR_INVALID_PARAM:
2630                 return "LIBUSB_ERROR_INVALID_PARAM";
2631         case LIBUSB_ERROR_ACCESS:
2632                 return "LIBUSB_ERROR_ACCESS";
2633         case LIBUSB_ERROR_NO_DEVICE:
2634                 return "LIBUSB_ERROR_NO_DEVICE";
2635         case LIBUSB_ERROR_NOT_FOUND:
2636                 return "LIBUSB_ERROR_NOT_FOUND";
2637         case LIBUSB_ERROR_BUSY:
2638                 return "LIBUSB_ERROR_BUSY";
2639         case LIBUSB_ERROR_TIMEOUT:
2640                 return "LIBUSB_ERROR_TIMEOUT";
2641         case LIBUSB_ERROR_OVERFLOW:
2642                 return "LIBUSB_ERROR_OVERFLOW";
2643         case LIBUSB_ERROR_PIPE:
2644                 return "LIBUSB_ERROR_PIPE";
2645         case LIBUSB_ERROR_INTERRUPTED:
2646                 return "LIBUSB_ERROR_INTERRUPTED";
2647         case LIBUSB_ERROR_NO_MEM:
2648                 return "LIBUSB_ERROR_NO_MEM";
2649         case LIBUSB_ERROR_NOT_SUPPORTED:
2650                 return "LIBUSB_ERROR_NOT_SUPPORTED";
2651         case LIBUSB_ERROR_OTHER:
2652                 return "LIBUSB_ERROR_OTHER";
2653
2654         case LIBUSB_TRANSFER_ERROR:
2655                 return "LIBUSB_TRANSFER_ERROR";
2656         case LIBUSB_TRANSFER_TIMED_OUT:
2657                 return "LIBUSB_TRANSFER_TIMED_OUT";
2658         case LIBUSB_TRANSFER_CANCELLED:
2659                 return "LIBUSB_TRANSFER_CANCELLED";
2660         case LIBUSB_TRANSFER_STALL:
2661                 return "LIBUSB_TRANSFER_STALL";
2662         case LIBUSB_TRANSFER_NO_DEVICE:
2663                 return "LIBUSB_TRANSFER_NO_DEVICE";
2664         case LIBUSB_TRANSFER_OVERFLOW:
2665                 return "LIBUSB_TRANSFER_OVERFLOW";
2666
2667         case 0:
2668                 return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
2669         default:
2670                 return "**UNKNOWN**";
2671         }
2672 }
2673
2674 /** \ingroup misc
2675  * Returns a pointer to const struct libusb_version with the version
2676  * (major, minor, micro, nano and rc) of the running library.
2677  */
2678 DEFAULT_VISIBILITY
2679 const struct libusb_version * LIBUSB_CALL libusb_get_version(void) {
2680
2681         return &libusb_version_internal;
2682 }