core.c 94 KB

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