Repository navigation
host-JS: implement napi_is_detached_arraybuffer - #138
Merged
Merged
Conversation
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 <noreply@anthropic.com>
This was referenced Nov 6, 2026
syrusakbary
added a commit
that referenced
this pull request
Nov 6, 2026
Brings in #139 (a process-wide waker the host installs for V8 foreground tasks only a checkpoint runs: wasmer_napi::set_foreground_task_waker, snapi_bridge_set_foreground_task_waker, EdgeV8Platform::SetForegroundTaskWaker), #138 (host-JS napi_is_detached_arraybuffer) and #136 (a V8 CPU profile per env when NAPI_V8_CPU_PROFILE_DIR is set). Conflicts: - v8/src/unofficial_napi.cc, UnofficialEnvScope: next added `releasing` (a release called again from a hook is refused), main added `cpu_profile`. Both are kept. - v8/src/unofficial_napi.cc, before NearHeapLimitCallback: main adds StartEnvCPUProfile and FinishEnvCPUProfile next to its NearHeapLimitCallback(void* raw_env, ...), which next changed to take the agent. next's callback is kept, and main's two functions are moved onto next's agent. main keeps the CPU profiler and the profile sessions in g_profiler_states (EnsureProfilerState), under g_runtime_mu; next replaced that map with napi_agent__'s cpu_profiler and active_profiles, which only the isolate's thread touches. So the two functions read env->agent and take no lock. Both check the thread first (IsEnvThreadEntered, and in FinishEnvCPUProfile the session's owner thread), as unofficial_napi_profile_start and _stop do. The session is still listed with the agent's other sessions, so napi_agent__::Shutdown (DisposeProfilers) stops and frees it when FinishEnvCPUProfile can't. Merged without a conflict, and fixed: - src/snapi_js.rs, snapi_bridge_is_detached_arraybuffer and its test (#138): main looks the value up with state.get(id) and stores the test's values with state.insert. next moved the value table from HostJsEnv to its HostJsAgent, so these are state.agent.get and state.agent.insert, as everywhere else on next. HostJsEnv has neither method, so the wasm32 `js` build did not compile without this. Merged without a conflict, and checked: - ReleaseEnvScope: FinishEnvCPUProfile runs after next's refusal of a release called again, so such a call leaves the session alone, and before DestroyEnvInstance. - #136 against next's release contract: the profile is stopped and written at the start of unofficial_napi_release_env. Then napi_agent__::Shutdown disposes the agent's profiler, and only then does the env's teardown run the cleanup hooks, the finalizers and the instance-data finalizer. So the JS they run, which next's release contract allows, is not in the profile, as v8/README.md says (the profile ends at the start of the release) and as on main, whose DestroyEnvInstance also disposed the profiler before them. - #136 against realms: V8's CPU profiler samples the isolate, so JS that runs in any realm of the env is in the profile. - #136 against the sticky termination: FinishEnvCPUProfile runs no JS (it reads the profile through the public getters), so after an uncancelled termination the profile is still written, complete and valid. - #139 against the sticky termination: the waker is called when a task is posted, on the posting thread, and never by a checkpoint. A checkpoint the termination refuses (napi_pending_exception) runs no task and posts none, so a host that sleeps until it is woken takes one turn and sleeps again; it does not spin. The task stays queued and runs at the first checkpoint after the cancel, and the cancel does not call the waker for it. - #139 against the release: the waker takes no env. Hook JS that posts a task during the release (the target is cleared first) calls it on the env's thread. Once the isolate's shutdown begins, ForegroundTaskRunner drops a post without calling it. Drains of next's finalizer queues, which hold the env's drain token, go only to the embedder's enqueue hook and never call the waker. - #138 against next's host-JS realms: realms share the host's intrinsics and their values live in the agent's table, so the answer is the same for a buffer from any realm, asked in any realm, also after realm code replaced the ArrayBuffer getters, Function.prototype.call or Uint8Array, which the helper captured at load. - tests/CMakeLists.txt: main registers test_76_env_cpu_profile (V8, Linux and macOS) and napi_v8.foreground_task_waker. next's test_76_termination_until_cancelled was renumbered to test_78 before this merge, so no runner shares a number. - include/unofficial_napi.h, src/napi_bridge_init.cc, src/snapi.rs and tests/host-js/README.md take main's hunks; next's changes to them are elsewhere in those files. - QuickJS keeps next's pin: none of the three changes touches it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
On the host-JS backend,
napi_is_detached_arraybufferwas a stub:snapi_bridge_is_detached_arraybufferreturnednapi_generic_failurefor every value. WebkitWasm (WebKit compiled to Wasm, running on this provider) calls it on the ArrayBuffer behind anImageDatabefore it copies the pixels, for example for a WebGL texture upload, and throwsInvalidStateErrorfor a detached buffer, as WebCore does. On this backend every such call failed.The host-JS backend now answers as the V8 backend does. An ArrayBuffer gives
napi_okand whether it is detached. Anything else, aSharedArrayBufferincluded, givesnapi_arraybuffer_expectedand leaves the result alone. The host JavaScript calls ES2024'sArrayBuffer.prototype.detachedgetter, which throws for anything but an ArrayBuffer, so it is the brand check too. On engines that predate the getter, such as Node 20, thebyteLengthgetter checks the brand, and a probe decides: aUint8Arrayof no bytes at offset 0 over the buffer fits any live buffer, empty or resizable, and throws only for a detached one. All of these intrinsics are captured when the module loads. Page code that later replaces them, orFunction.prototype.call, changes no answer, and the helper never throws into the Wasm import.Changes
src/snapi_js.rs, bridge:snapi_bridge_is_detached_arraybufferreturnsnapi_invalid_argfor a bad env or an unknown handle, as the bridge's other functions do. It then asks the new host helper. For a value that is not an ArrayBuffer it returnsnapi_arraybuffer_expected, asv8/src/js_native_api_v8.ccdoes. Otherwise it writes 0 or 1 and returnsnapi_ok. The file gets a newNAPI_ARRAYBUFFER_EXPECTEDconstant (19).src/snapi_js.rs, host JavaScript: a newwasmer_napi_arraybuffer_detached_state(value)returns -1 for a value that is not an ArrayBuffer, 0 for a live one and 1 for a detached one, and catches everything. It does its own brand check with intrinsics captured at load (Function.call.bind, as the finalizer helpers at the top of the file do). It does not go throughwasmer_napi_is_arraybuffer, which reads its intrinsics on every call.snapi_js::tests:is_detached_arraybuffer_reports_like_the_v8_backendgoes through the bridge:napi_ok, 0.structuredClone(b, { transfer: [b] }), and a resizable buffer detached byb.transfer():napi_ok, 1.SharedArrayBuffer, aUint8Array,{ byteLength: 16 }, aProxyof an ArrayBuffer,undefined,nulland16:napi_arraybuffer_expected, with the result untouched.napi_invalid_arg.tests/host-js/detached-arraybuffer.test.mjs(new): loads all of the embedded JavaScript into avmrealm, asnative-realm.test.mjsdoes, and calls the helper. Each test runs twice, once as the realm comes and once withArrayBuffer.prototype.detacheddeleted before the load, so the fallback runs on any engine.DataViewand a plain object.detachedandbyteLengthgetters and replacesFunction.prototype.call,applyandbind,Reflect.applyandUint8Array. In one the replacements throw, in the other they accept anything.tests/host-js/README.md: describes the new file and adds it to the run commands..github/workflows/napi-host-js.yml: thenode-contextjob (Node 20, 22, 24 and 26) and thebun-contextjob now also run the new file, next toglobal-context.test.mjs.src/guest/napi_js.rsneeded no change: it already forwardsnapi_is_detached_arraybufferto the bridge and writes the result byte only onnapi_ok. Neither did the native providers.Testing
On macOS arm64:
node --expose-gc --test tests/host-js/*.test.mjs(Node 26.0.0): 41/41.mainhas 35/35; the 6 new tests make up the difference.node --expose-gc --test tests/host-js/detached-arraybuffer.test.mjson Node 22.22.3 and 24.18.0: 6/6 each.node-contextjob's new command on Node 26.0.0: 21/21.bun test tests/host-js/global-context.test.mjs tests/host-js/detached-arraybuffer.test.mjs(Bun 1.3.14, thebun-contextjob's new command): 18 pass, 3 skip, 0 fail. The 3 skips are theError.prepareStackTracetests that Bun always skips.snapi_js::tests, withwasm-bindgen-test-runner0.2.127 (the version inCargo.standalone.lock) and Node 26:mainplus the new one.RUSTFLAGS="-C target-feature=+atomics,+bulk-memory,+mutable-globals" ./cargo-standalone.sh +nightly check --target wasm32-unknown-unknown --features js --lib -Z build-stdpasses with the same 23 warnings asmain, none of them insrc/snapi_js.rs.rustfmt --edition 2024 --check src/snapi_js.rsandgit diff --checkare clean.598a65a.mainhas since gained Pass guest names to the engine with their exact bytes, and refuse lengths above INT_MAX #134 and Run the cargo unit tests and the WAT-guest tests in CI, and fixmanifest_testsundercargo-standalone.sh#135, which touch none of these files. Merged withmainat87937f1, the compile check,snapi_js::tests(14/14) andtests/host-js/*.test.mjs(41/41) pass.src/snapi_js.rsis only compiled for wasm32 with thejsfeature (src/lib.rs), and no native code changed.main,is_detached_arraybuffer_reports_like_the_v8_backendfails at its first case:new ArrayBuffer(16)gets status 9 (napi_generic_failure) instead of 0.napi_invalid_argfor a value that is not an ArrayBuffer, the same test fails atnew SharedArrayBuffer(16): status 1 instead of 19.main, all 6 host-JS tests fail withReferenceError: wasmer_napi_arraybuffer_detached_state is not defined.wasmer_napi_is_arraybufferfirst, the 4 page-code tests fail. Where the replacements throw, a live buffer is reported as not an ArrayBuffer. Where they accept anything, the captureddetachedgetter throwsTypeErrorfor theSharedArrayBuffer(an uncaught exception through the Wasm import), and without the getter thatSharedArrayBufferis reported as a live ArrayBuffer.detachedgetter, thebyteLengthgetter orUint8Arraylooked up on each call instead of captured, the matching page-code tests fail.byteLengthbrand check in the fallback, the 3 tests without the getter fail: aSharedArrayBufferis reported as a live ArrayBuffer.Notes for reviewers
The status for a value that is not an ArrayBuffer follows the V8 backend, not Node. The V8 backend returns
napi_arraybuffer_expected. Node returnsnapi_okandfalse(*result = value->IsArrayBuffer() && ...WasDetached()), and its docs say nothing about other values. The QuickJS backend returnsnapi_okandtrueforundefined,nulland objects with abyteLengthproperty, andnapi_arraybuffer_expectedfor everything else. That is left as it is. If the backends should follow Node instead, that is a change to the V8 backend too. WebkitWasm's own patch returnednapi_invalid_arghere. Its callers treat any status other thannapi_okthe same way, so the different status doesn't affect them.Buffers over guest memory. On host-JS,
napi_create_bufferand guest-backed typed arrays are views over the guest memory's own buffer, so thearraybufferthatnapi_get_buffer_infoornapi_get_typedarray_inforeturns for them is that buffer. With shared guest memory it is aSharedArrayBuffer: this PR answersnapi_arraybuffer_expectedthere, where the V8 backend, whose buffers are external ArrayBuffers, answersnapi_okand false. With unshared memory, amemory.growdetaches it, so the answer becomes true while the guest's allocation is still live.napi_is_arraybufferalready differs between the backends for these values in the same way. Traced through the code, not run. WebkitWasm doesn't hit it: the buffers it asks about, such as anImageData's, are made by host JavaScript.Only this helper is hardened against page code.
napi_is_arraybuffer,napi_is_dataviewand the typed-array kind check still read their intrinsics on every call, as onmain. This PR doesn't change them.Two related gaps are left out of this PR. On host-JS,
napi_detach_arraybufferstill returnsnapi_generic_failure. Andnapi_create_external_arraybufferwith NULL data and length 0 makes a live empty buffer there, so this PR reports it as not detached. The V8 backend detaches such a buffer, as Node does, and reports it as detached. Node'stest_typedarray(NullArrayBuffer) checks that, but this repo doesn't run it on host-JS.CI. The host-JS workflow already ran
global-context.test.mjson Node 20 to 26 and Bun. The new file runs next to it, so Node 20 runs the fallback natively.finalizer-queue.test.mjsandnative-realm.test.mjsare still not in CI, as onmain.Other PRs. Checked with
git merge-tree --write-tree:feat/contextify-enter-leave) and Let an embedder set the process time zone and an isolate's locale #130 (feat/intl-overrides) merge cleanly.feat/trusted-script) conflicts insrc/snapi.rsandtests/CMakeLists.txt. It conflicts withmainthe same way already, and this PR touches neither file.src/snapi_js.rs,tests/host-jsor the host-JS workflow.Merging into
next(next: realm handles and realm entry, with one env per engine instance #127). Git merges this branch intonextwithout a conflict, but the result does not compile.nextkeeps value handles on the env'sagentinstead of onHostJsEnv, so the two lookups this PR adds insrc/snapi_js.rsneed it too:snapi_bridge_is_detached_arraybuffer,state.get(id)becomesstate.agent.get(id), as intype_test!andsnapi_bridge_is_sharedarraybufferonnext.is_detached_arraybuffer_reports_like_the_v8_backend,state.insert(...)becomesstate.agent.insert(...).Nothing else has to change on
next.tests/host-js/README.mdand the workflow merge as they are. The host JavaScript helper uses none of the realm machinery, andsrc/guest/napi_js.rsonnextalready forwards the call to the bridge and writes the result only onnapi_ok. A tested resolution exists:next(f928811) merged withmain(87937f1), then this branch, with those two edits. On it,tests/host-js/*.test.mjspasses 49/49 (43/43 without this branch),snapi_js::tests27/27 (26/26 without), and the host-JS compile check passes with the same warnings as without. Thenode-contextcommand passes 29/29 on Node 26, and thebun-contextone has 26 pass, 3 skip, 0 fail. (nextitself conflicts withmaininv8/src/js_native_api_v8.cc, over Pass guest names to the engine with their exact bytes, and refuse lengths above INT_MAX #134's length checks innapi_create_function. That conflict isn't this PR's.)Not verified:
napi_invalid_argfor a value that is not an ArrayBuffer.🤖 Generated with Claude Code