| 1 |
/* |
| 2 |
* Copyright © 2021 Google LLC |
| 3 |
* Copyright © 2023 Ingvar Stepanyan <[email protected]> |
| 4 |
* |
| 5 |
* This library is free software; you can redistribute it and/or |
| 6 |
* modify it under the terms of the GNU Lesser General Public |
| 7 |
* License as published by the Free Software Foundation; either |
| 8 |
* version 2.1 of the License, or (at your option) any later version. |
| 9 |
* |
| 10 |
* This library is distributed in the hope that it will be useful, |
| 11 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 |
* Lesser General Public License for more details. |
| 14 |
* |
| 15 |
* You should have received a copy of the GNU Lesser General Public |
| 16 |
* License along with this library; if not, write to the Free Software |
| 17 |
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
| 18 |
* |
| 19 |
* Authors: |
| 20 |
* Ingvar Stepanyan <[email protected]> |
| 21 |
*/ |
| 22 |
|
| 23 |
#include <emscripten/version.h> |
| 24 |
|
| 25 |
static_assert((__EMSCRIPTEN_major__ * 100 * 100 + __EMSCRIPTEN_minor__ * 100 + |
| 26 |
__EMSCRIPTEN_tiny__) >= 30148, |
| 27 |
"Emscripten 3.1.48 or newer is required."); |
| 28 |
|
| 29 |
#include <assert.h> |
| 30 |
#include <emscripten.h> |
| 31 |
#include <emscripten/val.h> |
| 32 |
|
| 33 |
#include <type_traits> |
| 34 |
#include <utility> |
| 35 |
|
| 36 |
#include "libusbi.h" |
| 37 |
|
| 38 |
using namespace emscripten; |
| 39 |
|
| 40 |
#ifdef _REENTRANT |
| 41 |
#include <emscripten/proxying.h> |
| 42 |
#include <emscripten/threading.h> |
| 43 |
#include <pthread.h> |
| 44 |
|
| 45 |
static ProxyingQueue queue; |
| 46 |
#endif |
| 47 |
|
| 48 |
#pragma clang diagnostic push |
| 49 |
#pragma clang diagnostic ignored "-Wmissing-prototypes" |
| 50 |
#pragma clang diagnostic ignored "-Wunused-parameter" |
| 51 |
#pragma clang diagnostic ignored "-Wshadow" |
| 52 |
|
| 53 |
namespace { |
| 54 |
|
| 55 |
// clang-format off |
| 56 |
EM_JS(EM_VAL, usbi_em_promise_catch, (EM_VAL handle), { |
| 57 |
let promise = Emval.toValue(handle); |
| 58 |
promise = promise.then( |
| 59 |
value => ({error : 0, value}), |
| 60 |
error => { |
| 61 |
console.error(error); |
| 62 |
let errorCode = -99; // LIBUSB_ERROR_OTHER |
| 63 |
if (error instanceof DOMException) { |
| 64 |
const ERROR_CODES = { |
| 65 |
// LIBUSB_ERROR_IO |
| 66 |
NetworkError : -1, |
| 67 |
// LIBUSB_ERROR_INVALID_PARAM |
| 68 |
DataError : -2, |
| 69 |
TypeMismatchError : -2, |
| 70 |
IndexSizeError : -2, |
| 71 |
// LIBUSB_ERROR_ACCESS |
| 72 |
SecurityError : -3, |
| 73 |
// LIBUSB_ERROR_NOT_FOUND |
| 74 |
NotFoundError : -5, |
| 75 |
// LIBUSB_ERROR_BUSY |
| 76 |
InvalidStateError : -6, |
| 77 |
// LIBUSB_ERROR_TIMEOUT |
| 78 |
TimeoutError : -7, |
| 79 |
// LIBUSB_ERROR_INTERRUPTED |
| 80 |
AbortError : -10, |
| 81 |
// LIBUSB_ERROR_NOT_SUPPORTED |
| 82 |
NotSupportedError : -12, |
| 83 |
}; |
| 84 |
errorCode = ERROR_CODES[error.name] ?? errorCode; |
| 85 |
} else if (error instanceof RangeError || error instanceof TypeError) { |
| 86 |
errorCode = -2; // LIBUSB_ERROR_INVALID_PARAM |
| 87 |
} |
| 88 |
return {error: errorCode, value: undefined}; |
| 89 |
} |
| 90 |
); |
| 91 |
return Emval.toHandle(promise); |
| 92 |
}); |
| 93 |
|
| 94 |
EM_JS(void, usbi_em_copy_from_dataview, (void* dst, EM_VAL src), { |
| 95 |
src = Emval.toValue(src); |
| 96 |
src = new Uint8Array(src.buffer, src.byteOffset, src.byteLength); |
| 97 |
HEAPU8.set(src, dst); |
| 98 |
}); |
| 99 |
|
| 100 |
// Our implementation proxies operations from multiple threads to the same |
| 101 |
// underlying USBDevice on the main thread. This can lead to issues when |
| 102 |
// multiple threads try to open/close the same device at the same time. |
| 103 |
// |
| 104 |
// First, since open/close operations are asynchronous in WebUSB, we can end up |
| 105 |
// with multiple open/close operations in flight at the same time, which can |
| 106 |
// lead to unpredictable outcome (e.g. device got closed but opening succeeded |
| 107 |
// right before that). |
| 108 |
// |
| 109 |
// Second, since multiple threads are allowed to have their own handles to the |
| 110 |
// same device, we need to keep track of number of open handles and close the |
| 111 |
// device only when the last handle is closed. |
| 112 |
// |
| 113 |
// We fix both of these issues by using a shared promise chain that executes |
| 114 |
// open and close operations sequentially and keeps track of the reference count |
| 115 |
// in each promise's result. This way, we can ensure that only one open/close |
| 116 |
// operation is in flight at any given time. Note that we don't need to worry |
| 117 |
// about all other operations because they're preconditioned on the device being |
| 118 |
// open and having at least 1 reference anyway. |
| 119 |
EM_JS(EM_VAL, usbi_em_device_safe_open_close, (EM_VAL device, bool open), { |
| 120 |
device = Emval.toValue(device); |
| 121 |
const symbol = Symbol.for('libusb.open_close_chain'); |
| 122 |
let promiseChain = device[symbol] ?? Promise.resolve(0); |
| 123 |
device[symbol] = promiseChain = promiseChain.then(async refCount => { |
| 124 |
if (open) { |
| 125 |
if (!refCount++) { |
| 126 |
await device.open(); |
| 127 |
} |
| 128 |
} else { |
| 129 |
if (!--refCount) { |
| 130 |
await device.close(); |
| 131 |
} |
| 132 |
} |
| 133 |
return refCount; |
| 134 |
}); |
| 135 |
return Emval.toHandle(promiseChain); |
| 136 |
}); |
| 137 |
// clang-format on |
| 138 |
|
| 139 |
libusb_transfer_status getTransferStatus(const val& transfer_result) { |
| 140 |
auto status = transfer_result["status"].as<std::string>(); |
| 141 |
if (status == "ok") { |
| 142 |
return LIBUSB_TRANSFER_COMPLETED; |
| 143 |
} else if (status == "stall") { |
| 144 |
return LIBUSB_TRANSFER_STALL; |
| 145 |
} else if (status == "babble") { |
| 146 |
return LIBUSB_TRANSFER_OVERFLOW; |
| 147 |
} else { |
| 148 |
return LIBUSB_TRANSFER_ERROR; |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
// Note: this assumes that `dst` is valid for at least `src.byteLength` bytes. |
| 153 |
// This is true for all results returned from WebUSB as we pass max length to |
| 154 |
// the transfer APIs. |
| 155 |
void copyFromDataView(void* dst, const val& src) { |
| 156 |
usbi_em_copy_from_dataview(dst, src.as_handle()); |
| 157 |
} |
| 158 |
|
| 159 |
auto getUnsharedMemoryView(void* src, size_t len) { |
| 160 |
auto view = typed_memory_view(len, (uint8_t*)src); |
| 161 |
#ifdef _REENTRANT |
| 162 |
// Unfortunately, TypedArrays backed by SharedArrayBuffers are not accepted |
| 163 |
// by most Web APIs, trading off guaranteed thread-safety for performance |
| 164 |
// loss. The usual workaround is to copy them into a new TypedArray, which |
| 165 |
// is what we do here via the `.slice()` method. |
| 166 |
return val(view).call<val>("slice"); |
| 167 |
#else |
| 168 |
// Non-threaded builds can avoid the copy penalty. |
| 169 |
return view; |
| 170 |
#endif |
| 171 |
} |
| 172 |
|
| 173 |
// A helper that proxies a function call to the main thread if not already |
| 174 |
// there. This is a wrapper around Emscripten's raw proxying API with couple of |
| 175 |
// high-level improvements, namely support for destroying lambda on the target |
| 176 |
// thread as well as custom return types. |
| 177 |
template <typename Func> |
| 178 |
auto runOnMain(Func&& func) { |
| 179 |
#ifdef _REENTRANT |
| 180 |
if (!emscripten_is_main_runtime_thread()) { |
| 181 |
if constexpr (std::is_same_v<std::invoke_result_t<Func>, void>) { |
| 182 |
bool proxied = |
| 183 |
queue.proxySync(emscripten_main_runtime_thread_id(), [&func] { |
| 184 |
// Capture func by reference and move into a local variable |
| 185 |
// to render the captured func inert on the first (and only) |
| 186 |
// call. This way it can be safely destructed on the main |
| 187 |
// thread instead of the current one when this call |
| 188 |
// finishes. TODO: remove this when |
| 189 |
// https://github.com/emscripten-core/emscripten/issues/20610 |
| 190 |
// is fixed. |
| 191 |
auto func_ = std::move(func); |
| 192 |
func_(); |
| 193 |
}); |
| 194 |
assert(proxied); |
| 195 |
return; |
| 196 |
} else { |
| 197 |
// A storage for the result of the function call. |
| 198 |
// TODO: remove when |
| 199 |
// https://github.com/emscripten-core/emscripten/issues/20611 is |
| 200 |
// implemented. |
| 201 |
std::optional<std::invoke_result_t<Func>> result; |
| 202 |
runOnMain( |
| 203 |
[&result, func = std::move(func)] { result.emplace(func()); }); |
| 204 |
return std::move(result.value()); |
| 205 |
} |
| 206 |
} |
| 207 |
#endif |
| 208 |
return func(); |
| 209 |
} |
| 210 |
|
| 211 |
// C++ struct representation for `{value, error}` object used by `CaughtPromise` |
| 212 |
// below. |
| 213 |
struct PromiseResult { |
| 214 |
int error; |
| 215 |
val value; |
| 216 |
|
| 217 |
PromiseResult() = delete; |
| 218 |
PromiseResult(PromiseResult&&) = default; |
| 219 |
|
| 220 |
PromiseResult(val&& result) |
| 221 |
: error(result["error"].as<int>()), value(result["value"]) {} |
| 222 |
|
| 223 |
~PromiseResult() { |
| 224 |
// make sure value is freed on the thread it exists on |
| 225 |
runOnMain([value = std::move(value)] {}); |
| 226 |
} |
| 227 |
}; |
| 228 |
|
| 229 |
struct CaughtPromise : val { |
| 230 |
CaughtPromise(val&& promise) |
| 231 |
: val(wrapPromiseWithCatch(std::move(promise))) {} |
| 232 |
|
| 233 |
using AwaitResult = PromiseResult; |
| 234 |
|
| 235 |
private: |
| 236 |
|
| 237 |
// Wrap promise with conversion from some value T to `{value: T, error: |
| 238 |
// number}`. |
| 239 |
static val wrapPromiseWithCatch(val&& promise) { |
| 240 |
auto handle = promise.as_handle(); |
| 241 |
handle = usbi_em_promise_catch(handle); |
| 242 |
return val::take_ownership(handle); |
| 243 |
} |
| 244 |
}; |
| 245 |
|
| 246 |
#define co_await_try(promise) \ |
| 247 |
({ \ |
| 248 |
PromiseResult result = co_await CaughtPromise(promise); \ |
| 249 |
if (result.error) { \ |
| 250 |
co_return result.error; \ |
| 251 |
} \ |
| 252 |
std::move(result.value); \ |
| 253 |
}) |
| 254 |
|
| 255 |
// A helper that runs an asynchronous callback when the promise is resolved. |
| 256 |
template <typename Promise, typename OnResult> |
| 257 |
val promiseThen(Promise&& promise, OnResult&& onResult) { |
| 258 |
// Save captures from the callback while we can, or they'll be destructed. |
| 259 |
// https://devblogs.microsoft.com/oldnewthing/20211103-00/?p=105870 |
| 260 |
auto onResult_ = std::move(onResult); |
| 261 |
onResult_(co_await promise); |
| 262 |
co_return val::undefined(); |
| 263 |
} |
| 264 |
|
| 265 |
// A helper that runs an asynchronous function on the main thread and blocks the |
| 266 |
// current thread until the promise is resolved (via Asyncify "blocking" if |
| 267 |
// already on the main thread or regular blocking otherwise). |
| 268 |
template <typename Func> |
| 269 |
static std::invoke_result_t<Func>::AwaitResult awaitOnMain(Func&& func) { |
| 270 |
#ifdef _REENTRANT |
| 271 |
if (!emscripten_is_main_runtime_thread()) { |
| 272 |
// If we're on a different thread, we can't use main thread's Asyncify |
| 273 |
// as multiple threads might be fighting for its state; instead, use |
| 274 |
// proxying to synchronously block the current thread until the promise |
| 275 |
// is complete. |
| 276 |
std::optional<typename std::invoke_result_t<Func>::AwaitResult> result; |
| 277 |
queue.proxySyncWithCtx( |
| 278 |
emscripten_main_runtime_thread_id(), |
| 279 |
[&result, &func](ProxyingQueue::ProxyingCtx ctx) { |
| 280 |
// Same as `func` in `runOnMain`, move to destruct on the first |
| 281 |
// call. |
| 282 |
auto func_ = std::move(func); |
| 283 |
promiseThen( |
| 284 |
func_(), |
| 285 |
[&result, ctx = std::move(ctx)](auto&& result_) mutable { |
| 286 |
result.emplace(std::move(result_)); |
| 287 |
ctx.finish(); |
| 288 |
}); |
| 289 |
}); |
| 290 |
return std::move(result.value()); |
| 291 |
} |
| 292 |
#endif |
| 293 |
// If we're already on the main thread, use Asyncify to block until the |
| 294 |
// promise is resolved. |
| 295 |
return func().await(); |
| 296 |
} |
| 297 |
|
| 298 |
// A helper that makes a control transfer given a setup pointer (assumed to be |
| 299 |
// followed by data payload for out-transfers). |
| 300 |
val makeControlTransferPromise(const val& dev, libusb_control_setup* setup) { |
| 301 |
auto params = val::object(); |
| 302 |
|
| 303 |
const char* request_type = "unknown"; |
| 304 |
// See LIBUSB_REQ_TYPE in windows_winusb.h (or docs for `bmRequestType`). |
| 305 |
switch (setup->bmRequestType & (0x03 << 5)) { |
| 306 |
case LIBUSB_REQUEST_TYPE_STANDARD: |
| 307 |
request_type = "standard"; |
| 308 |
break; |
| 309 |
case LIBUSB_REQUEST_TYPE_CLASS: |
| 310 |
request_type = "class"; |
| 311 |
break; |
| 312 |
case LIBUSB_REQUEST_TYPE_VENDOR: |
| 313 |
request_type = "vendor"; |
| 314 |
break; |
| 315 |
} |
| 316 |
params.set("requestType", request_type); |
| 317 |
|
| 318 |
const char* recipient = "other"; |
| 319 |
switch (setup->bmRequestType & 0x0f) { |
| 320 |
case LIBUSB_RECIPIENT_DEVICE: |
| 321 |
recipient = "device"; |
| 322 |
break; |
| 323 |
case LIBUSB_RECIPIENT_INTERFACE: |
| 324 |
recipient = "interface"; |
| 325 |
break; |
| 326 |
case LIBUSB_RECIPIENT_ENDPOINT: |
| 327 |
recipient = "endpoint"; |
| 328 |
break; |
| 329 |
} |
| 330 |
params.set("recipient", recipient); |
| 331 |
|
| 332 |
params.set("request", setup->bRequest); |
| 333 |
params.set("value", setup->wValue); |
| 334 |
params.set("index", setup->wIndex); |
| 335 |
|
| 336 |
if (setup->bmRequestType & LIBUSB_ENDPOINT_IN) { |
| 337 |
return dev.call<val>("controlTransferIn", params, setup->wLength); |
| 338 |
} else { |
| 339 |
return dev.call<val>("controlTransferOut", params, |
| 340 |
getUnsharedMemoryView(setup + 1, setup->wLength)); |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
// Smart pointer for managing pointers to places allocated by libusb inside its |
| 345 |
// backend structures. |
| 346 |
template <typename T> |
| 347 |
struct ValPtr { |
| 348 |
template <typename... Args> |
| 349 |
void emplace(Args&&... args) { |
| 350 |
new (ptr) T(std::forward<Args>(args)...); |
| 351 |
} |
| 352 |
|
| 353 |
const T& operator*() const { return *ptr; } |
| 354 |
T& operator*() { return *ptr; } |
| 355 |
|
| 356 |
const T* operator->() const { return ptr; } |
| 357 |
T* operator->() { return ptr; } |
| 358 |
|
| 359 |
void free() { ptr->~T(); } |
| 360 |
|
| 361 |
T take() { |
| 362 |
auto value = std::move(*ptr); |
| 363 |
free(); |
| 364 |
return value; |
| 365 |
} |
| 366 |
|
| 367 |
protected: |
| 368 |
|
| 369 |
ValPtr(void* ptr) : ptr(static_cast<T*>(ptr)) {} |
| 370 |
|
| 371 |
private: |
| 372 |
|
| 373 |
// Note: this is not a heap-allocated pointer, but a pointer to a part |
| 374 |
// of the backend structure allocated by libusb itself. |
| 375 |
T* ptr; |
| 376 |
}; |
| 377 |
|
| 378 |
struct CachedDevice; |
| 379 |
|
| 380 |
struct WebUsbDevicePtr : ValPtr<CachedDevice> { |
| 381 |
public: |
| 382 |
|
| 383 |
WebUsbDevicePtr(libusb_device* dev) : ValPtr(usbi_get_device_priv(dev)) {} |
| 384 |
WebUsbDevicePtr(libusb_device_handle* handle) |
| 385 |
: WebUsbDevicePtr(handle->dev) {} |
| 386 |
}; |
| 387 |
|
| 388 |
struct WebUsbTransferPtr : ValPtr<PromiseResult> { |
| 389 |
public: |
| 390 |
|
| 391 |
WebUsbTransferPtr(usbi_transfer* itransfer) |
| 392 |
: ValPtr(usbi_get_transfer_priv(itransfer)) {} |
| 393 |
}; |
| 394 |
|
| 395 |
enum class OpenClose : bool { |
| 396 |
Open = true, |
| 397 |
Close = false, |
| 398 |
}; |
| 399 |
|
| 400 |
struct CachedDevice { |
| 401 |
CachedDevice() = delete; |
| 402 |
CachedDevice(CachedDevice&&) = delete; |
| 403 |
|
| 404 |
// Fill in the device descriptor and configurations by reading them from the |
| 405 |
// WebUSB device. |
| 406 |
static val initFromDevice(val&& web_usb_dev, libusb_device* libusb_dev) { |
| 407 |
auto cachedDevicePtr = WebUsbDevicePtr(libusb_dev); |
| 408 |
cachedDevicePtr.emplace(std::move(web_usb_dev)); |
| 409 |
bool must_close = false; |
| 410 |
val result = co_await cachedDevicePtr->initFromDeviceWithoutClosing( |
| 411 |
libusb_dev, must_close); |
| 412 |
if (must_close) { |
| 413 |
co_await_try(cachedDevicePtr->safeOpenCloseAssumingMainThread( |
| 414 |
OpenClose::Close)); |
| 415 |
} |
| 416 |
co_return std::move(result); |
| 417 |
} |
| 418 |
|
| 419 |
const val& getDeviceAssumingMainThread() const { return device; } |
| 420 |
|
| 421 |
uint8_t getActiveConfigValue() const { |
| 422 |
return runOnMain([&] { |
| 423 |
auto web_usb_config = device["configuration"]; |
| 424 |
return web_usb_config.isNull() |
| 425 |
? 0 |
| 426 |
: web_usb_config["configurationValue"].as<uint8_t>(); |
| 427 |
}); |
| 428 |
} |
| 429 |
|
| 430 |
usbi_configuration_descriptor* getConfigDescriptor(uint8_t config_id) { |
| 431 |
return config_id < configurations.size() |
| 432 |
? configurations[config_id].get() |
| 433 |
: nullptr; |
| 434 |
} |
| 435 |
|
| 436 |
usbi_configuration_descriptor* findConfigDescriptorByValue( |
| 437 |
uint8_t config_id) const { |
| 438 |
for (auto& config : configurations) { |
| 439 |
if (config->bConfigurationValue == config_id) { |
| 440 |
return config.get(); |
| 441 |
} |
| 442 |
} |
| 443 |
return nullptr; |
| 444 |
} |
| 445 |
|
| 446 |
int copyConfigDescriptor(const usbi_configuration_descriptor* config, |
| 447 |
void* buf, |
| 448 |
size_t buf_len) { |
| 449 |
auto len = std::min(buf_len, (size_t)config->wTotalLength); |
| 450 |
memcpy(buf, config, len); |
| 451 |
return len; |
| 452 |
} |
| 453 |
|
| 454 |
template <typename... Args> |
| 455 |
int awaitOnMain(const char* methodName, Args&&... args) const { |
| 456 |
return ::awaitOnMain([&] { |
| 457 |
return CaughtPromise(device.call<val>( |
| 458 |
methodName, std::forward<Args>(args)...)); |
| 459 |
}) |
| 460 |
.error; |
| 461 |
} |
| 462 |
|
| 463 |
~CachedDevice() { |
| 464 |
runOnMain([device = std::move(device)] {}); |
| 465 |
} |
| 466 |
|
| 467 |
CaughtPromise safeOpenCloseAssumingMainThread(OpenClose open) { |
| 468 |
return val::take_ownership(usbi_em_device_safe_open_close( |
| 469 |
device.as_handle(), static_cast<bool>(open))); |
| 470 |
} |
| 471 |
|
| 472 |
int safeOpenCloseOnMain(OpenClose open) { |
| 473 |
return ::awaitOnMain([this, open] { |
| 474 |
return safeOpenCloseAssumingMainThread(open); |
| 475 |
}) |
| 476 |
.error; |
| 477 |
} |
| 478 |
|
| 479 |
private: |
| 480 |
|
| 481 |
val device; |
| 482 |
std::vector<std::unique_ptr<usbi_configuration_descriptor>> configurations; |
| 483 |
|
| 484 |
CaughtPromise requestDescriptor(libusb_descriptor_type desc_type, |
| 485 |
uint8_t desc_index, |
| 486 |
uint16_t max_length) const { |
| 487 |
libusb_control_setup setup = { |
| 488 |
.bmRequestType = LIBUSB_ENDPOINT_IN, |
| 489 |
.bRequest = LIBUSB_REQUEST_GET_DESCRIPTOR, |
| 490 |
.wValue = (uint16_t)((desc_type << 8) | desc_index), |
| 491 |
.wIndex = 0, |
| 492 |
.wLength = max_length, |
| 493 |
}; |
| 494 |
return makeControlTransferPromise(device, &setup); |
| 495 |
} |
| 496 |
|
| 497 |
// Implementation of the `CachedDevice::initFromDevice` above. This is a |
| 498 |
// separate function just because we need to close the device on exit if |
| 499 |
// we opened it successfully, and we can't use an async operation (`close`) |
| 500 |
// in RAII destructor. |
| 501 |
val initFromDeviceWithoutClosing(libusb_device* dev, bool& must_close) { |
| 502 |
co_await_try(safeOpenCloseAssumingMainThread(OpenClose::Open)); |
| 503 |
|
| 504 |
// Can't use RAII to close on exit as co_await is not permitted in |
| 505 |
// destructors (yet: |
| 506 |
// https://github.com/cplusplus/papers/issues/445), so use a good |
| 507 |
// old boolean + a wrapper instead. |
| 508 |
must_close = true; |
| 509 |
|
| 510 |
{ |
| 511 |
auto result = co_await_try( |
| 512 |
requestDescriptor(LIBUSB_DT_DEVICE, 0, LIBUSB_DT_DEVICE_SIZE)); |
| 513 |
if (auto error = getTransferStatus(result)) { |
| 514 |
co_return error; |
| 515 |
} |
| 516 |
copyFromDataView(&dev->device_descriptor, result["data"]); |
| 517 |
} |
| 518 |
|
| 519 |
// Infer the device speed (which is not yet provided by WebUSB) from |
| 520 |
// the descriptor. |
| 521 |
if (dev->device_descriptor.bMaxPacketSize0 == |
| 522 |
/* actually means 2^9, only valid for superspeeds */ 9) { |
| 523 |
dev->speed = dev->device_descriptor.bcdUSB >= 0x0310 |
| 524 |
? LIBUSB_SPEED_SUPER_PLUS |
| 525 |
: LIBUSB_SPEED_SUPER; |
| 526 |
} else if (dev->device_descriptor.bcdUSB >= 0x0200) { |
| 527 |
dev->speed = LIBUSB_SPEED_HIGH; |
| 528 |
} else if (dev->device_descriptor.bMaxPacketSize0 > 8) { |
| 529 |
dev->speed = LIBUSB_SPEED_FULL; |
| 530 |
} else { |
| 531 |
dev->speed = LIBUSB_SPEED_LOW; |
| 532 |
} |
| 533 |
|
| 534 |
if (auto error = usbi_sanitize_device(dev)) { |
| 535 |
co_return error; |
| 536 |
} |
| 537 |
|
| 538 |
auto configurations_len = dev->device_descriptor.bNumConfigurations; |
| 539 |
configurations.reserve(configurations_len); |
| 540 |
for (uint8_t j = 0; j < configurations_len; j++) { |
| 541 |
// Read descriptor header first to discover target length. |
| 542 |
auto config_header_result = co_await_try( |
| 543 |
requestDescriptor(LIBUSB_DT_CONFIG, j, LIBUSB_DT_CONFIG_SIZE)); |
| 544 |
if (auto error = getTransferStatus(config_header_result)) { |
| 545 |
co_return error; |
| 546 |
} |
| 547 |
union usbi_config_desc_buf config_header = {}; |
| 548 |
copyFromDataView(config_header.buf, config_header_result["data"]); |
| 549 |
if (config_header.desc.bDescriptorType != LIBUSB_DT_CONFIG || |
| 550 |
config_header.desc.bLength < LIBUSB_DT_CONFIG_SIZE) { |
| 551 |
co_return LIBUSB_ERROR_IO; |
| 552 |
} |
| 553 |
|
| 554 |
auto config_total_length = |
| 555 |
libusb_le16_to_cpu(config_header.desc.wTotalLength); |
| 556 |
if (config_total_length < LIBUSB_DT_CONFIG_SIZE) { |
| 557 |
co_return LIBUSB_ERROR_IO; |
| 558 |
} |
| 559 |
|
| 560 |
auto config_result = co_await_try( |
| 561 |
requestDescriptor(LIBUSB_DT_CONFIG, j, config_total_length)); |
| 562 |
if (auto error = getTransferStatus(config_result)) { |
| 563 |
co_return error; |
| 564 |
} |
| 565 |
|
| 566 |
auto configVal = config_result["data"]; |
| 567 |
if (configVal["byteLength"].as<size_t>() < config_total_length) { |
| 568 |
co_return LIBUSB_ERROR_IO; |
| 569 |
} |
| 570 |
|
| 571 |
auto configLen = configVal["byteLength"].as<size_t>(); |
| 572 |
auto& config = configurations.emplace_back( |
| 573 |
(usbi_configuration_descriptor*)::operator new(configLen)); |
| 574 |
copyFromDataView(config.get(), configVal); |
| 575 |
} |
| 576 |
|
| 577 |
co_return (int) LIBUSB_SUCCESS; |
| 578 |
} |
| 579 |
|
| 580 |
CachedDevice(val device) : device(std::move(device)) {} |
| 581 |
|
| 582 |
friend struct ValPtr<CachedDevice>; |
| 583 |
}; |
| 584 |
|
| 585 |
unsigned long getDeviceSessionId(val& web_usb_device) { |
| 586 |
thread_local const val SessionIdSymbol = |
| 587 |
val::global("Symbol")(val("libusb.session_id")); |
| 588 |
|
| 589 |
val session_id_val = web_usb_device[SessionIdSymbol]; |
| 590 |
if (!session_id_val.isUndefined()) { |
| 591 |
return session_id_val.as<unsigned long>(); |
| 592 |
} |
| 593 |
|
| 594 |
// If the device doesn't have a session ID, it means we haven't seen |
| 595 |
// it before. Generate a new session ID for it. We can associate an |
| 596 |
// incrementing ID with the `USBDevice` object itself. It's |
| 597 |
// guaranteed to be alive and, thus, stable as long as the device is |
| 598 |
// connected, even between different libusb invocations. See |
| 599 |
// https://github.com/WICG/webusb/issues/241. |
| 600 |
|
| 601 |
static unsigned long next_session_id = 0; |
| 602 |
|
| 603 |
web_usb_device.set(SessionIdSymbol, next_session_id); |
| 604 |
return next_session_id++; |
| 605 |
} |
| 606 |
|
| 607 |
val getDeviceList(libusb_context* ctx, discovered_devs** devs) { |
| 608 |
// Check if browser supports USB |
| 609 |
val navigator_usb = val::global("navigator")["usb"]; |
| 610 |
if (navigator_usb == val::undefined()) { |
| 611 |
co_return (int) LIBUSB_ERROR_NOT_SUPPORTED; |
| 612 |
} |
| 613 |
// C++ equivalent of `await navigator.usb.getDevices()`. Note: at this point |
| 614 |
// we must already have some devices exposed - caller must have called |
| 615 |
// `await navigator.usb.requestDevice(...)` in response to user interaction |
| 616 |
// before going to LibUSB. Otherwise this list will be empty. |
| 617 |
auto web_usb_devices = |
| 618 |
co_await_try(navigator_usb.call<val>("getDevices")); |
| 619 |
for (auto&& web_usb_device : web_usb_devices) { |
| 620 |
auto session_id = getDeviceSessionId(web_usb_device); |
| 621 |
|
| 622 |
auto dev = usbi_get_device_by_session_id(ctx, session_id); |
| 623 |
if (dev == NULL) { |
| 624 |
dev = usbi_alloc_device(ctx, session_id); |
| 625 |
if (dev == NULL) { |
| 626 |
usbi_err(ctx, "failed to allocate a new device structure"); |
| 627 |
continue; |
| 628 |
} |
| 629 |
|
| 630 |
auto statusVal = co_await CachedDevice::initFromDevice( |
| 631 |
std::move(web_usb_device), dev); |
| 632 |
if (auto error = statusVal.as<int>()) { |
| 633 |
usbi_err(ctx, "failed to read device information: %s", |
| 634 |
libusb_error_name(error)); |
| 635 |
libusb_unref_device(dev); |
| 636 |
continue; |
| 637 |
} |
| 638 |
|
| 639 |
// We don't have real buses in WebUSB, just pretend everything |
| 640 |
// is on bus 1. |
| 641 |
dev->bus_number = 1; |
| 642 |
// This can wrap around but it's the best approximation of a stable |
| 643 |
// device address and port number we can provide. |
| 644 |
dev->device_address = dev->port_number = (uint8_t)session_id; |
| 645 |
|
| 646 |
usbi_connect_device(dev); |
| 647 |
} |
| 648 |
*devs = discovered_devs_append(*devs, dev); |
| 649 |
libusb_unref_device(dev); |
| 650 |
} |
| 651 |
co_return (int) LIBUSB_SUCCESS; |
| 652 |
} |
| 653 |
|
| 654 |
int em_get_device_list(libusb_context* ctx, discovered_devs** devs) { |
| 655 |
// No need to wrap into CaughtPromise as we catch all individual ops in the |
| 656 |
// inner implementation and return just the error code. We do need a custom |
| 657 |
// promise type to ensure conversion to int happens on the main thread |
| 658 |
// though. |
| 659 |
struct IntPromise : val { |
| 660 |
IntPromise(val&& promise) : val(std::move(promise)) {} |
| 661 |
|
| 662 |
struct AwaitResult { |
| 663 |
int error; |
| 664 |
|
| 665 |
AwaitResult(val&& result) : error(result.as<int>()) {} |
| 666 |
}; |
| 667 |
}; |
| 668 |
|
| 669 |
return awaitOnMain( |
| 670 |
[ctx, devs] { return IntPromise(getDeviceList(ctx, devs)); }) |
| 671 |
.error; |
| 672 |
} |
| 673 |
|
| 674 |
int em_open(libusb_device_handle* handle) { |
| 675 |
return WebUsbDevicePtr(handle)->safeOpenCloseOnMain(OpenClose::Open); |
| 676 |
} |
| 677 |
|
| 678 |
void em_close(libusb_device_handle* handle) { |
| 679 |
// LibUSB API doesn't allow us to handle an error here, but we still need to |
| 680 |
// wait for the promise to make sure that subsequent attempt to reopen the |
| 681 |
// same device doesn't fail with a "device busy" error. |
| 682 |
if (auto error = |
| 683 |
WebUsbDevicePtr(handle)->safeOpenCloseOnMain(OpenClose::Close)) { |
| 684 |
usbi_err(handle->dev->ctx, "failed to close device: %s", |
| 685 |
libusb_error_name(error)); |
| 686 |
} |
| 687 |
} |
| 688 |
|
| 689 |
int em_get_active_config_descriptor(libusb_device* dev, void* buf, size_t len) { |
| 690 |
auto& cached_device = *WebUsbDevicePtr(dev); |
| 691 |
auto config_value = cached_device.getActiveConfigValue(); |
| 692 |
if (auto config = cached_device.findConfigDescriptorByValue(config_value)) { |
| 693 |
return cached_device.copyConfigDescriptor(config, buf, len); |
| 694 |
} else { |
| 695 |
return LIBUSB_ERROR_NOT_FOUND; |
| 696 |
} |
| 697 |
} |
| 698 |
|
| 699 |
int em_get_config_descriptor(libusb_device* dev, |
| 700 |
uint8_t config_id, |
| 701 |
void* buf, |
| 702 |
size_t len) { |
| 703 |
auto& cached_device = *WebUsbDevicePtr(dev); |
| 704 |
if (auto config = cached_device.getConfigDescriptor(config_id)) { |
| 705 |
return cached_device.copyConfigDescriptor(config, buf, len); |
| 706 |
} else { |
| 707 |
return LIBUSB_ERROR_NOT_FOUND; |
| 708 |
} |
| 709 |
} |
| 710 |
|
| 711 |
int em_get_configuration(libusb_device_handle* dev_handle, |
| 712 |
uint8_t* config_value) { |
| 713 |
*config_value = WebUsbDevicePtr(dev_handle)->getActiveConfigValue(); |
| 714 |
return LIBUSB_SUCCESS; |
| 715 |
} |
| 716 |
|
| 717 |
int em_get_config_descriptor_by_value(libusb_device* dev, |
| 718 |
uint8_t config_value, |
| 719 |
void** buf) { |
| 720 |
auto& cached_device = *WebUsbDevicePtr(dev); |
| 721 |
if (auto config = cached_device.findConfigDescriptorByValue(config_value)) { |
| 722 |
*buf = config; |
| 723 |
return config->wTotalLength; |
| 724 |
} else { |
| 725 |
return LIBUSB_ERROR_NOT_FOUND; |
| 726 |
} |
| 727 |
} |
| 728 |
|
| 729 |
int em_set_configuration(libusb_device_handle* dev_handle, int config) { |
| 730 |
return WebUsbDevicePtr(dev_handle)->awaitOnMain("selectConfiguration", config); |
| 731 |
} |
| 732 |
|
| 733 |
int em_claim_interface(libusb_device_handle* handle, uint8_t iface) { |
| 734 |
return WebUsbDevicePtr(handle)->awaitOnMain("claimInterface", iface); |
| 735 |
} |
| 736 |
|
| 737 |
int em_release_interface(libusb_device_handle* handle, uint8_t iface) { |
| 738 |
return WebUsbDevicePtr(handle)->awaitOnMain("releaseInterface", iface); |
| 739 |
} |
| 740 |
|
| 741 |
int em_set_interface_altsetting(libusb_device_handle* handle, |
| 742 |
uint8_t iface, |
| 743 |
uint8_t altsetting) { |
| 744 |
return WebUsbDevicePtr(handle)->awaitOnMain("selectAlternateInterface", |
| 745 |
iface, altsetting); |
| 746 |
} |
| 747 |
|
| 748 |
int em_clear_halt(libusb_device_handle* handle, unsigned char endpoint) { |
| 749 |
std::string direction = endpoint & LIBUSB_ENDPOINT_IN ? "in" : "out"; |
| 750 |
endpoint &= LIBUSB_ENDPOINT_ADDRESS_MASK; |
| 751 |
|
| 752 |
return WebUsbDevicePtr(handle)->awaitOnMain("clearHalt", direction, |
| 753 |
endpoint); |
| 754 |
} |
| 755 |
|
| 756 |
int em_reset_device(libusb_device_handle* handle) { |
| 757 |
return WebUsbDevicePtr(handle)->awaitOnMain("reset"); |
| 758 |
} |
| 759 |
|
| 760 |
void em_destroy_device(libusb_device* dev) { |
| 761 |
WebUsbDevicePtr(dev).free(); |
| 762 |
} |
| 763 |
|
| 764 |
int em_submit_transfer(usbi_transfer* itransfer) { |
| 765 |
return runOnMain([itransfer] { |
| 766 |
auto transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); |
| 767 |
auto& web_usb_device = WebUsbDevicePtr(transfer->dev_handle) |
| 768 |
->getDeviceAssumingMainThread(); |
| 769 |
val transfer_promise; |
| 770 |
switch (transfer->type) { |
| 771 |
case LIBUSB_TRANSFER_TYPE_CONTROL: { |
| 772 |
transfer_promise = makeControlTransferPromise( |
| 773 |
web_usb_device, |
| 774 |
libusb_control_transfer_get_setup(transfer)); |
| 775 |
break; |
| 776 |
} |
| 777 |
case LIBUSB_TRANSFER_TYPE_BULK: |
| 778 |
case LIBUSB_TRANSFER_TYPE_INTERRUPT: { |
| 779 |
auto endpoint = |
| 780 |
transfer->endpoint & LIBUSB_ENDPOINT_ADDRESS_MASK; |
| 781 |
|
| 782 |
if (IS_XFERIN(transfer)) { |
| 783 |
transfer_promise = web_usb_device.call<val>( |
| 784 |
"transferIn", endpoint, transfer->length); |
| 785 |
} else { |
| 786 |
auto data = getUnsharedMemoryView(transfer->buffer, |
| 787 |
transfer->length); |
| 788 |
transfer_promise = |
| 789 |
web_usb_device.call<val>("transferOut", endpoint, data); |
| 790 |
} |
| 791 |
|
| 792 |
break; |
| 793 |
} |
| 794 |
// TODO: add implementation for isochronous transfers too. |
| 795 |
default: |
| 796 |
return LIBUSB_ERROR_NOT_SUPPORTED; |
| 797 |
} |
| 798 |
// Not a coroutine because we don't want to block on this promise, just |
| 799 |
// schedule an asynchronous callback. |
| 800 |
promiseThen(CaughtPromise(std::move(transfer_promise)), |
| 801 |
[itransfer](auto&& result) { |
| 802 |
WebUsbTransferPtr(itransfer).emplace(std::move(result)); |
| 803 |
usbi_signal_transfer_completion(itransfer); |
| 804 |
}); |
| 805 |
return LIBUSB_SUCCESS; |
| 806 |
}); |
| 807 |
} |
| 808 |
|
| 809 |
void em_clear_transfer_priv(usbi_transfer* itransfer) { |
| 810 |
WebUsbTransferPtr(itransfer).free(); |
| 811 |
} |
| 812 |
|
| 813 |
int em_cancel_transfer(usbi_transfer* itransfer) { |
| 814 |
return LIBUSB_SUCCESS; |
| 815 |
} |
| 816 |
|
| 817 |
int em_handle_transfer_completion(usbi_transfer* itransfer) { |
| 818 |
libusb_transfer_status status = runOnMain([itransfer] { |
| 819 |
auto transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); |
| 820 |
|
| 821 |
// Take ownership of the transfer result, as `em_clear_transfer_priv` is |
| 822 |
// not called automatically for completed transfers and we must free it |
| 823 |
// to avoid leaks. |
| 824 |
|
| 825 |
auto result = WebUsbTransferPtr(itransfer).take(); |
| 826 |
|
| 827 |
if (itransfer->state_flags & USBI_TRANSFER_CANCELLING) { |
| 828 |
return LIBUSB_TRANSFER_CANCELLED; |
| 829 |
} |
| 830 |
|
| 831 |
if (result.error) { |
| 832 |
return LIBUSB_TRANSFER_ERROR; |
| 833 |
} |
| 834 |
|
| 835 |
auto& value = result.value; |
| 836 |
|
| 837 |
void* dataDest; |
| 838 |
unsigned char endpointDir; |
| 839 |
|
| 840 |
if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL) { |
| 841 |
dataDest = libusb_control_transfer_get_data(transfer); |
| 842 |
endpointDir = |
| 843 |
libusb_control_transfer_get_setup(transfer)->bmRequestType; |
| 844 |
} else { |
| 845 |
dataDest = transfer->buffer; |
| 846 |
endpointDir = transfer->endpoint; |
| 847 |
} |
| 848 |
|
| 849 |
if (endpointDir & LIBUSB_ENDPOINT_IN) { |
| 850 |
auto data = value["data"]; |
| 851 |
if (!data.isNull()) { |
| 852 |
itransfer->transferred = data["byteLength"].as<int>(); |
| 853 |
copyFromDataView(dataDest, data); |
| 854 |
} |
| 855 |
} else { |
| 856 |
itransfer->transferred = value["bytesWritten"].as<int>(); |
| 857 |
} |
| 858 |
|
| 859 |
return getTransferStatus(value); |
| 860 |
}); |
| 861 |
|
| 862 |
// Invoke user's handlers outside of the main thread to reduce pressure. |
| 863 |
return status == LIBUSB_TRANSFER_CANCELLED |
| 864 |
? usbi_handle_transfer_cancellation(itransfer) |
| 865 |
: usbi_handle_transfer_completion(itransfer, status); |
| 866 |
} |
| 867 |
|
| 868 |
} // namespace |
| 869 |
|
| 870 |
#pragma clang diagnostic ignored "-Wmissing-field-initializers" |
| 871 |
extern "C" const usbi_os_backend usbi_backend = { |
| 872 |
.name = "Emscripten + WebUSB backend", |
| 873 |
.caps = 0, |
| 874 |
.get_device_list = em_get_device_list, |
| 875 |
.open = em_open, |
| 876 |
.close = em_close, |
| 877 |
.get_active_config_descriptor = em_get_active_config_descriptor, |
| 878 |
.get_config_descriptor = em_get_config_descriptor, |
| 879 |
.get_config_descriptor_by_value = em_get_config_descriptor_by_value, |
| 880 |
.get_configuration = em_get_configuration, |
| 881 |
.set_configuration = em_set_configuration, |
| 882 |
.claim_interface = em_claim_interface, |
| 883 |
.release_interface = em_release_interface, |
| 884 |
.set_interface_altsetting = em_set_interface_altsetting, |
| 885 |
.clear_halt = em_clear_halt, |
| 886 |
.reset_device = em_reset_device, |
| 887 |
.destroy_device = em_destroy_device, |
| 888 |
.submit_transfer = em_submit_transfer, |
| 889 |
.cancel_transfer = em_cancel_transfer, |
| 890 |
.clear_transfer_priv = em_clear_transfer_priv, |
| 891 |
.handle_transfer_completion = em_handle_transfer_completion, |
| 892 |
.device_priv_size = sizeof(CachedDevice), |
| 893 |
.transfer_priv_size = sizeof(PromiseResult), |
| 894 |
}; |
| 895 |
|
| 896 |
#pragma clang diagnostic pop |