From d89fab782d7882557977fcd852a3bbc0dbfd7875 Mon Sep 17 00:00:00 2001 From: Syrus Akbary Date: Thu, 5 Nov 2026 21:47:43 -0800 Subject: [PATCH] host-JS: implement napi_is_detached_arraybuffer The host-JS backend's snapi_bridge_is_detached_arraybuffer was a stub that returned napi_generic_failure for every value. WebkitWasm (WebKit on this provider) calls napi_is_detached_arraybuffer on the ArrayBuffer behind an ImageData before it copies the pixels, as for a WebGL texture upload, and throws InvalidStateError for a detached one. On this backend every such call failed. It now answers as the V8 backend does. A value that is not an ArrayBuffer, a SharedArrayBuffer included, gives napi_arraybuffer_expected and leaves the result alone; an ArrayBuffer gives napi_ok and whether it is detached. (Node instead gives napi_ok and false for a value that is not an ArrayBuffer.) The host JavaScript calls ES2024's ArrayBuffer.prototype.detached getter, which throws for anything but an ArrayBuffer, so it is the brand check too. Engines that predate it, such as Node 20, check the brand with the byteLength getter, then construct a Uint8Array of no bytes at offset 0 over the buffer, which fits any live buffer, empty or resizable, and throws only for a detached one. All of these are captured at load, so page code replacing them, or Function.prototype.call, changes no answer, and the helper never throws into the wasm import. snapi_js::tests checks the bridge's status and result for live, empty, resizable and detached buffers and for values that are not ArrayBuffers. tests/host-js/detached-arraybuffer.test.mjs checks the host JavaScript, with and without the getter, on buffers from two realms, and again after page code replaces those intrinsics with functions that throw or that accept anything. The host-JS CI jobs run it on Node 20, 22, 24 and 26 and on Bun. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/napi-host-js.yml | 4 +- src/snapi_js.rs | 109 ++++++++++++++++++- tests/host-js/README.md | 13 ++- tests/host-js/detached-arraybuffer.test.mjs | 111 ++++++++++++++++++++ 4 files changed, 231 insertions(+), 6 deletions(-) create mode 100644 tests/host-js/detached-arraybuffer.test.mjs diff --git a/.github/workflows/napi-host-js.yml b/.github/workflows/napi-host-js.yml index 15b212030..5e4aeb41a 100644 --- a/.github/workflows/napi-host-js.yml +++ b/.github/workflows/napi-host-js.yml @@ -19,7 +19,7 @@ jobs: - uses: actions/setup-node@v4 with: node-version: ${{ matrix.node }} - - run: node --expose-gc --test tests/host-js/global-context.test.mjs + - run: node --expose-gc --test tests/host-js/global-context.test.mjs tests/host-js/detached-arraybuffer.test.mjs bun-context: runs-on: ubuntu-latest @@ -28,7 +28,7 @@ jobs: - uses: oven-sh/setup-bun@v2 with: bun-version: 1.3.14 - - run: bun test tests/host-js/global-context.test.mjs + - run: bun test tests/host-js/global-context.test.mjs tests/host-js/detached-arraybuffer.test.mjs wasm-callback-lifetime: runs-on: ubuntu-latest diff --git a/src/snapi_js.rs b/src/snapi_js.rs index a130e16c9..6809a347e 100644 --- a/src/snapi_js.rs +++ b/src/snapi_js.rs @@ -42,6 +42,7 @@ const NAPI_NUMBER_EXPECTED: i32 = 6; const NAPI_ARRAY_EXPECTED: i32 = 8; const NAPI_GENERIC_FAILURE: i32 = 9; const NAPI_PENDING_EXCEPTION: i32 = 10; +const NAPI_ARRAYBUFFER_EXPECTED: i32 = 19; const JS_BACKING_TOKEN_MARKER: u64 = 1 << 63; const CALLBACK_DEFERRED: u32 = u32::MAX; @@ -1186,6 +1187,35 @@ export function wasmer_napi_is_arraybuffer(value) { return false; } } +// The intrinsics behind napi_is_detached_arraybuffer, captured at load so page +// code replacing them, or Function.prototype.call, changes nothing. Like the +// byteLength getter, ES2024's detached getter throws for anything but an +// ArrayBuffer, a SharedArrayBuffer included, so it is the brand check too. +const wasmerNapiArrayBufferByteLength = Function.call.bind( + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength').get); +const wasmerNapiDetachedGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'detached')?.get; +const wasmerNapiArrayBufferDetached = wasmerNapiDetachedGetter && + Function.call.bind(wasmerNapiDetachedGetter); +const wasmerNapiUint8Array = Uint8Array; +// -1 for a value that is not an ArrayBuffer, 0 for a live one, 1 for a +// detached one. Never throws. +export function wasmer_napi_arraybuffer_detached_state(value) { + try { + if (wasmerNapiArrayBufferDetached) return wasmerNapiArrayBufferDetached(value) ? 1 : 0; + wasmerNapiArrayBufferByteLength(value); + } catch { + return -1; + } + // Engines that predate the getter (Node 20): a view of no bytes at offset 0 + // fits any live buffer, empty or resizable, and only a detached one throws. + try { + new wasmerNapiUint8Array(value, 0, 0); + return 0; + } catch { + return 1; + } +} export function wasmer_napi_is_dataview(value) { try { Object.getOwnPropertyDescriptor(DataView.prototype, 'byteLength').get.call(value); @@ -1507,6 +1537,7 @@ extern "C" { ) -> Result; fn wasmer_napi_typed_array_kind(value: &JsValue) -> i32; fn wasmer_napi_is_arraybuffer(value: &JsValue) -> bool; + fn wasmer_napi_arraybuffer_detached_state(value: &JsValue) -> i32; fn wasmer_napi_is_dataview(value: &JsValue) -> bool; fn wasmer_napi_is_buffer(value: &JsValue) -> bool; fn wasmer_napi_buffer_view(buffer: &JsValue, offset: u32, length: u32) -> JsValue; @@ -6632,8 +6663,20 @@ pub unsafe extern "C" fn snapi_bridge_is_detached_arraybuffer( id: u32, result: *mut i32, ) -> i32 { - let _ = (env, id, result); - NAPI_GENERIC_FAILURE + let Ok(state) = (unsafe { env_mut(env) }) else { + return NAPI_INVALID_ARG; + }; + let Some(value) = state.get(id) else { + return NAPI_INVALID_ARG; + }; + // As the V8 backend: anything but an ArrayBuffer, a SharedArrayBuffer + // included, is refused. (Node instead reports it as not detached.) + let detached = match wasmer_napi_arraybuffer_detached_state(value) { + 0 => 0, + 1 => 1, + _ => return NAPI_ARRAYBUFFER_EXPECTED, + }; + unsafe { write(result, detached) }.map_or_else(|error| error, |()| NAPI_OK) } #[unsafe(no_mangle)] pub unsafe extern "C" fn snapi_bridge_is_sharedarraybuffer( @@ -7819,6 +7862,68 @@ mod tests { }); } + #[wasm_bindgen_test] + fn is_detached_arraybuffer_reports_like_the_v8_backend() { + with_env(|env, state| { + let cases = [ + ("new ArrayBuffer(16)", NAPI_OK, 0), + ("new ArrayBuffer(0)", NAPI_OK, 0), + ("new ArrayBuffer(4, { maxByteLength: 16 })", NAPI_OK, 0), + ( + "(() => { const b = new ArrayBuffer(4, { maxByteLength: 16 }); \ + b.resize(0); return b; })()", + NAPI_OK, + 0, + ), + ( + "(() => { const b = new ArrayBuffer(16); \ + structuredClone(b, { transfer: [b] }); return b; })()", + NAPI_OK, + 1, + ), + ( + "(() => { const b = new ArrayBuffer(0); \ + structuredClone(b, { transfer: [b] }); return b; })()", + NAPI_OK, + 1, + ), + ( + "(() => { const b = new ArrayBuffer(4, { maxByteLength: 16 }); \ + b.transfer(); return b; })()", + NAPI_OK, + 1, + ), + // Not ArrayBuffers: the result is left alone. + ("new SharedArrayBuffer(16)", NAPI_ARRAYBUFFER_EXPECTED, -1), + ("new Uint8Array(16)", NAPI_ARRAYBUFFER_EXPECTED, -1), + ("({ byteLength: 16 })", NAPI_ARRAYBUFFER_EXPECTED, -1), + ( + "new Proxy(new ArrayBuffer(16), {})", + NAPI_ARRAYBUFFER_EXPECTED, + -1, + ), + ("undefined", NAPI_ARRAYBUFFER_EXPECTED, -1), + ("null", NAPI_ARRAYBUFFER_EXPECTED, -1), + ("16", NAPI_ARRAYBUFFER_EXPECTED, -1), + ]; + for (source, status, expected) in cases { + let id = state.insert(js_sys::eval(source).unwrap()); + let mut result = -1; + assert_eq!( + unsafe { snapi_bridge_is_detached_arraybuffer(env, id, &mut result) }, + status, + "{source}" + ); + assert_eq!(result, expected, "{source}"); + } + let mut result = -1; + assert_eq!( + unsafe { snapi_bridge_is_detached_arraybuffer(env, 0, &mut result) }, + NAPI_INVALID_ARG + ); + }); + } + #[wasm_bindgen_test] fn number_getters_convert_like_node() { with_env(|env, state| { diff --git a/tests/host-js/README.md b/tests/host-js/README.md index f3874b445..ed77c798b 100644 --- a/tests/host-js/README.md +++ b/tests/host-js/README.md @@ -3,8 +3,8 @@ Run the context tests directly, without compiling Wasmer or installing npm dependencies: ```sh -node --expose-gc --test tests/host-js/global-context.test.mjs tests/host-js/finalizer-queue.test.mjs tests/host-js/native-realm.test.mjs -bun test tests/host-js/global-context.test.mjs tests/host-js/finalizer-queue.test.mjs tests/host-js/native-realm.test.mjs +node --expose-gc --test tests/host-js/global-context.test.mjs tests/host-js/finalizer-queue.test.mjs tests/host-js/native-realm.test.mjs tests/host-js/detached-arraybuffer.test.mjs +bun test tests/host-js/global-context.test.mjs tests/host-js/finalizer-queue.test.mjs tests/host-js/native-realm.test.mjs tests/host-js/detached-arraybuffer.test.mjs ``` The tests extract the context implementation from the JavaScript embedded in @@ -35,6 +35,15 @@ bridge without letting its errors escape, and the bridge global is removed once captured; a bridge that can't be removed is refused. Without it, contexts stay isolated. +`detached-arraybuffer.test.mjs` loads the whole embedded JavaScript into a +`vm` realm, with and without ES2024's `ArrayBuffer.prototype.detached`, and +checks the inspection behind `napi_is_detached_arraybuffer`: live, empty and +resizable buffers, from that realm or another, are not detached; transferred +ones are; a SharedArrayBuffer, a view, a proxy or a look-alike is not an +ArrayBuffer. Page code that afterwards replaces the ArrayBuffer getters, +`Function.prototype.call` or `Uint8Array`, with functions that throw or that +accept anything, changes none of these answers. + Custom `Error.prepareStackTrace` tests detect whether the engine honors the hook. Bun 1.3.14 does not honor it in the same way as V8, so those three tests skip while the ownership and collection tests still run. diff --git a/tests/host-js/detached-arraybuffer.test.mjs b/tests/host-js/detached-arraybuffer.test.mjs new file mode 100644 index 000000000..e5c8dd207 --- /dev/null +++ b/tests/host-js/detached-arraybuffer.test.mjs @@ -0,0 +1,111 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { readFile } from 'node:fs/promises'; +import vm from 'node:vm'; + +// Test the ArrayBuffer inspection behind napi_is_detached_arraybuffer in the +// host JavaScript embedded in the wasm-bindgen module: with ES2024's +// ArrayBuffer.prototype.detached getter, and without it, as on engines that +// predate it, where a probe decides. +const rust = await readFile(new URL('../../src/snapi_js.rs', import.meta.url), 'utf8'); +const inline = rust.match(/#\[wasm_bindgen\(inline_js = r#"([\s\S]*?)"#\)\]/)?.[1]; +assert.ok(inline, 'host JavaScript implementation not found'); +const script = inline + .replace("import { parse as wasmerNapiParse } from 'acorn';", + 'const wasmerNapiParse = () => { throw new Error("Unexpected Acorn source preparation"); };') + .replaceAll('export function ', 'function '); +assert.ok(!/^import /m.test(script), 'unexpected import in the host JavaScript'); + +// Loads the host JavaScript into a fresh realm, optionally one without the +// getter, and returns what the bridge sees: null for a value that is not an +// ArrayBuffer (napi_arraybuffer_expected), else whether it is detached. +function load(withGetter) { + const context = vm.createContext({ setTimeout, queueMicrotask, console }); + if (!withGetter) vm.runInContext('delete ArrayBuffer.prototype.detached', context); + vm.runInContext(script, context); + const state = vm.runInContext('wasmer_napi_arraybuffer_detached_state', context); + const inspect = value => { + const result = state(value); + assert.ok(result === -1 || result === 0 || result === 1, `state ${result}`); + return result === -1 ? null : result === 1; + }; + return { context, inspect }; +} + +function detach(buffer) { + structuredClone(buffer, { transfer: [buffer] }); + return buffer; +} + +// Buffers from the provider's realm and from this one. +function cases(context) { + const local = source => vm.runInContext(source, context); + const shrunk = new ArrayBuffer(8, { maxByteLength: 16 }); + shrunk.resize(0); + return [ + ['live', local('new ArrayBuffer(16)'), false], + ['empty', local('new ArrayBuffer(0)'), false], + ['resizable', local('new ArrayBuffer(4, { maxByteLength: 16 })'), false], + ['resized to empty', shrunk, false], + ['live, another realm', new ArrayBuffer(8), false], + ['detached', detach(local('new ArrayBuffer(16)')), true], + ['detached empty', detach(local('new ArrayBuffer(0)')), true], + ['detached resizable', detach(local('new ArrayBuffer(4, { maxByteLength: 16 })')), true], + ['detached, another realm', detach(new ArrayBuffer(8)), true], + ['SharedArrayBuffer', local('new SharedArrayBuffer(16)'), null], + ['typed array', local('new Uint8Array(16)'), null], + ['DataView', new DataView(new ArrayBuffer(4)), null], + ['byteLength look-alike', { byteLength: 16 }, null], + ['proxy of an ArrayBuffer', local('new Proxy(new ArrayBuffer(16), {})'), null], + ['plain object', local('({})'), null], + ['undefined', undefined, null], + ['number', 16, null], + ]; +} + +// Page code replacing, after the load, the intrinsics a naive check would +// call: with ones that throw, and with ones that accept anything. +const tamperings = { + throw: ` + Object.defineProperty(ArrayBuffer.prototype, 'detached', { configurable: true, get() { throw new Error('detached'); } }); + Object.defineProperty(ArrayBuffer.prototype, 'byteLength', { configurable: true, get() { throw new Error('byteLength'); } }); + Function.prototype.call = function () { throw new Error('call'); }; + Function.prototype.apply = function () { throw new Error('apply'); }; + Function.prototype.bind = function () { throw new Error('bind'); }; + Reflect.apply = () => { throw new Error('Reflect.apply'); }; + globalThis.Uint8Array = function () { throw new Error('Uint8Array'); }; + `, + 'accept anything': ` + Object.defineProperty(ArrayBuffer.prototype, 'detached', { configurable: true, get() { return false; } }); + Object.defineProperty(ArrayBuffer.prototype, 'byteLength', { configurable: true, get() { return 16; } }); + Function.prototype.call = function () { return 0; }; + Function.prototype.apply = function () { return 0; }; + Function.prototype.bind = function () { return () => 0; }; + Reflect.apply = () => 0; + globalThis.Uint8Array = function () { return {}; }; + `, +}; + +for (const withGetter of [true, false]) { + const variant = withGetter ? 'with' : 'without'; + + test(`detached ArrayBuffers are told apart ${variant} ArrayBuffer.prototype.detached`, () => { + const { context, inspect } = load(withGetter); + assert.equal(vm.runInContext("'detached' in ArrayBuffer.prototype", context), + withGetter && 'detached' in ArrayBuffer.prototype); + for (const [name, value, expected] of cases(context)) { + assert.equal(inspect(value), expected, name); + } + }); + + for (const [kind, tampering] of Object.entries(tamperings)) { + test(`page code making intrinsics ${kind} changes nothing ${variant} ArrayBuffer.prototype.detached`, () => { + const { context, inspect } = load(withGetter); + const values = cases(context); + vm.runInContext(tampering, context); + for (const [name, value, expected] of values) { + assert.equal(inspect(value), expected, name); + } + }); + } +}