Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/napi-host-js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
109 changes: 107 additions & 2 deletions src/snapi_js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -1507,6 +1537,7 @@ extern "C" {
) -> Result<JsValue, JsValue>;
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;
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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| {
Expand Down
13 changes: 11 additions & 2 deletions tests/host-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
111 changes: 111 additions & 0 deletions tests/host-js/detached-arraybuffer.test.mjs
Original file line number Diff line number Diff line change
@@ -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);
}
});
}
}
Loading