thegecko / webusb

Node.js implementation of the WebUSB Specification
https://thegecko.github.io/webusb/
MIT License
183 stars 27 forks source link

requestDevice not 'thread-safe' #40

Open dsanders11 opened 5 years ago

dsanders11 commented 5 years ago

Putting 'thread-safe' in quotes because really I'm referring to async code, but the idea is the same. Two different parts of code simultaneously accessing requestDevice will lead to a crash:

    at Device.require.usb.Device.close (node_modules/usb/usb.js:48:7)
    at node_modules/webusb/lib/adapter.js:411:28
    at Device.<anonymous> (node_modules/usb/usb.js:160:4)
    at Transfer.<anonymous> (node_modules/usb/usb.js:131:15)

As the error message suggests, I believe this is because while one request is ongoing the other code closes the device, leading to the crash.

I believe the offending code is in getCapabilities in adapter.ts. Off the top of my head, a possible solution may be to add a closeDevice method to dovetail with openDevice, and use reference counting to only close the device when it's safe to do so.